Imported Upstream version 3.13.6
[platform/upstream/nss.git] / mozilla / security / nss / lib / sqlite / sqlite3.c
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.6.22.  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 embedded within
14 ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
19 */
20 #define SQLITE_CORE 1
21 #define SQLITE_AMALGAMATION 1
22 #ifndef SQLITE_PRIVATE
23 # define SQLITE_PRIVATE static
24 #endif
25 #ifndef SQLITE_API
26 # define SQLITE_API
27 #endif
28 /************** Begin file sqliteInt.h ***************************************/
29 /*
30 ** 2001 September 15
31 **
32 ** The author disclaims copyright to this source code.  In place of
33 ** a legal notice, here is a blessing:
34 **
35 **    May you do good and not evil.
36 **    May you find forgiveness for yourself and forgive others.
37 **    May you share freely, never taking more than you give.
38 **
39 *************************************************************************
40 ** Internal interface definitions for SQLite.
41 **
42 */
43 #ifndef _SQLITEINT_H_
44 #define _SQLITEINT_H_
45
46 /*
47 ** These #defines should enable >2GB file support on POSIX if the
48 ** underlying operating system supports it.  If the OS lacks
49 ** large file support, or if the OS is windows, these should be no-ops.
50 **
51 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
52 ** system #includes.  Hence, this block of code must be the very first
53 ** code in all source files.
54 **
55 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
56 ** on the compiler command line.  This is necessary if you are compiling
57 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
58 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
59 ** without this option, LFS is enable.  But LFS does not exist in the kernel
60 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
61 ** portability you should omit LFS.
62 **
63 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
64 */
65 #ifndef SQLITE_DISABLE_LFS
66 # define _LARGE_FILE       1
67 # ifndef _FILE_OFFSET_BITS
68 #   define _FILE_OFFSET_BITS 64
69 # endif
70 # define _LARGEFILE_SOURCE 1
71 #endif
72
73 /*
74 ** Include the configuration header output by 'configure' if we're using the
75 ** autoconf-based build
76 */
77 #ifdef _HAVE_SQLITE_CONFIG_H
78 #include "config.h"
79 #endif
80
81 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
82 /************** Begin file sqliteLimit.h *************************************/
83 /*
84 ** 2007 May 7
85 **
86 ** The author disclaims copyright to this source code.  In place of
87 ** a legal notice, here is a blessing:
88 **
89 **    May you do good and not evil.
90 **    May you find forgiveness for yourself and forgive others.
91 **    May you share freely, never taking more than you give.
92 **
93 *************************************************************************
94 ** 
95 ** This file defines various limits of what SQLite can process.
96 */
97
98 /*
99 ** The maximum length of a TEXT or BLOB in bytes.   This also
100 ** limits the size of a row in a table or index.
101 **
102 ** The hard limit is the ability of a 32-bit signed integer
103 ** to count the size: 2^31-1 or 2147483647.
104 */
105 #ifndef SQLITE_MAX_LENGTH
106 # define SQLITE_MAX_LENGTH 1000000000
107 #endif
108
109 /*
110 ** This is the maximum number of
111 **
112 **    * Columns in a table
113 **    * Columns in an index
114 **    * Columns in a view
115 **    * Terms in the SET clause of an UPDATE statement
116 **    * Terms in the result set of a SELECT statement
117 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
118 **    * Terms in the VALUES clause of an INSERT statement
119 **
120 ** The hard upper limit here is 32676.  Most database people will
121 ** tell you that in a well-normalized database, you usually should
122 ** not have more than a dozen or so columns in any table.  And if
123 ** that is the case, there is no point in having more than a few
124 ** dozen values in any of the other situations described above.
125 */
126 #ifndef SQLITE_MAX_COLUMN
127 # define SQLITE_MAX_COLUMN 2000
128 #endif
129
130 /*
131 ** The maximum length of a single SQL statement in bytes.
132 **
133 ** It used to be the case that setting this value to zero would
134 ** turn the limit off.  That is no longer true.  It is not possible
135 ** to turn this limit off.
136 */
137 #ifndef SQLITE_MAX_SQL_LENGTH
138 # define SQLITE_MAX_SQL_LENGTH 1000000000
139 #endif
140
141 /*
142 ** The maximum depth of an expression tree. This is limited to 
143 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
144 ** want to place more severe limits on the complexity of an 
145 ** expression.
146 **
147 ** A value of 0 used to mean that the limit was not enforced.
148 ** But that is no longer true.  The limit is now strictly enforced
149 ** at all times.
150 */
151 #ifndef SQLITE_MAX_EXPR_DEPTH
152 # define SQLITE_MAX_EXPR_DEPTH 1000
153 #endif
154
155 /*
156 ** The maximum number of terms in a compound SELECT statement.
157 ** The code generator for compound SELECT statements does one
158 ** level of recursion for each term.  A stack overflow can result
159 ** if the number of terms is too large.  In practice, most SQL
160 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
161 ** any limit on the number of terms in a compount SELECT.
162 */
163 #ifndef SQLITE_MAX_COMPOUND_SELECT
164 # define SQLITE_MAX_COMPOUND_SELECT 500
165 #endif
166
167 /*
168 ** The maximum number of opcodes in a VDBE program.
169 ** Not currently enforced.
170 */
171 #ifndef SQLITE_MAX_VDBE_OP
172 # define SQLITE_MAX_VDBE_OP 25000
173 #endif
174
175 /*
176 ** The maximum number of arguments to an SQL function.
177 */
178 #ifndef SQLITE_MAX_FUNCTION_ARG
179 # define SQLITE_MAX_FUNCTION_ARG 127
180 #endif
181
182 /*
183 ** The maximum number of in-memory pages to use for the main database
184 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
185 */
186 #ifndef SQLITE_DEFAULT_CACHE_SIZE
187 # define SQLITE_DEFAULT_CACHE_SIZE  2000
188 #endif
189 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
190 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
191 #endif
192
193 /*
194 ** The maximum number of attached databases.  This must be between 0
195 ** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
196 ** is used internally to track attached databases.
197 */
198 #ifndef SQLITE_MAX_ATTACHED
199 # define SQLITE_MAX_ATTACHED 10
200 #endif
201
202
203 /*
204 ** The maximum value of a ?nnn wildcard that the parser will accept.
205 */
206 #ifndef SQLITE_MAX_VARIABLE_NUMBER
207 # define SQLITE_MAX_VARIABLE_NUMBER 999
208 #endif
209
210 /* Maximum page size.  The upper bound on this value is 32768.  This a limit
211 ** imposed by the necessity of storing the value in a 2-byte unsigned integer
212 ** and the fact that the page size must be a power of 2.
213 **
214 ** If this limit is changed, then the compiled library is technically
215 ** incompatible with an SQLite library compiled with a different limit. If
216 ** a process operating on a database with a page-size of 65536 bytes 
217 ** crashes, then an instance of SQLite compiled with the default page-size 
218 ** limit will not be able to rollback the aborted transaction. This could
219 ** lead to database corruption.
220 */
221 #ifndef SQLITE_MAX_PAGE_SIZE
222 # define SQLITE_MAX_PAGE_SIZE 32768
223 #endif
224
225
226 /*
227 ** The default size of a database page.
228 */
229 #ifndef SQLITE_DEFAULT_PAGE_SIZE
230 # define SQLITE_DEFAULT_PAGE_SIZE 1024
231 #endif
232 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
233 # undef SQLITE_DEFAULT_PAGE_SIZE
234 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
235 #endif
236
237 /*
238 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
239 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
240 ** device characteristics (sector-size and atomic write() support),
241 ** SQLite may choose a larger value. This constant is the maximum value
242 ** SQLite will choose on its own.
243 */
244 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
245 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
246 #endif
247 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
248 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
249 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
250 #endif
251
252
253 /*
254 ** Maximum number of pages in one database file.
255 **
256 ** This is really just the default value for the max_page_count pragma.
257 ** This value can be lowered (or raised) at run-time using that the
258 ** max_page_count macro.
259 */
260 #ifndef SQLITE_MAX_PAGE_COUNT
261 # define SQLITE_MAX_PAGE_COUNT 1073741823
262 #endif
263
264 /*
265 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
266 ** operator.
267 */
268 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
269 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
270 #endif
271
272 /*
273 ** Maximum depth of recursion for triggers.
274 **
275 ** A value of 1 means that a trigger program will not be able to itself
276 ** fire any triggers. A value of 0 means that no trigger programs at all 
277 ** may be executed.
278 */
279 #ifndef SQLITE_MAX_TRIGGER_DEPTH
280 # define SQLITE_MAX_TRIGGER_DEPTH 1000
281 #endif
282
283 /************** End of sqliteLimit.h *****************************************/
284 /************** Continuing where we left off in sqliteInt.h ******************/
285
286 /* Disable nuisance warnings on Borland compilers */
287 #if defined(__BORLANDC__)
288 #pragma warn -rch /* unreachable code */
289 #pragma warn -ccc /* Condition is always true or false */
290 #pragma warn -aus /* Assigned value is never used */
291 #pragma warn -csu /* Comparing signed and unsigned */
292 #pragma warn -spa /* Suspicious pointer arithmetic */
293 #endif
294
295 /* Needed for various definitions... */
296 #ifndef _GNU_SOURCE
297 # define _GNU_SOURCE
298 #endif
299
300 /*
301 ** Include standard header files as necessary
302 */
303 #ifdef HAVE_STDINT_H
304 #include <stdint.h>
305 #endif
306 #ifdef HAVE_INTTYPES_H
307 #include <inttypes.h>
308 #endif
309
310 #define SQLITE_INDEX_SAMPLES 10
311
312 /*
313 ** This macro is used to "hide" some ugliness in casting an int
314 ** value to a ptr value under the MSVC 64-bit compiler.   Casting
315 ** non 64-bit values to ptr types results in a "hard" error with 
316 ** the MSVC 64-bit compiler which this attempts to avoid.  
317 **
318 ** A simple compiler pragma or casting sequence could not be found
319 ** to correct this in all situations, so this macro was introduced.
320 **
321 ** It could be argued that the intptr_t type could be used in this
322 ** case, but that type is not available on all compilers, or 
323 ** requires the #include of specific headers which differs between
324 ** platforms.
325 **
326 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
327 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
328 ** So we have to define the macros in different ways depending on the
329 ** compiler.
330 */
331 #if defined(__GNUC__)
332 # if defined(HAVE_STDINT_H)
333 #   define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
334 #   define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
335 # else
336 #   define SQLITE_INT_TO_PTR(X)  ((void*)(X))
337 #   define SQLITE_PTR_TO_INT(X)  ((int)(X))
338 # endif
339 #else
340 # define SQLITE_INT_TO_PTR(X)   ((void*)&((char*)0)[X])
341 # define SQLITE_PTR_TO_INT(X)   ((int)(((char*)X)-(char*)0))
342 #endif
343
344
345 /*
346 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
347 ** Older versions of SQLite used an optional THREADSAFE macro.
348 ** We support that for legacy
349 */
350 #if !defined(SQLITE_THREADSAFE)
351 #if defined(THREADSAFE)
352 # define SQLITE_THREADSAFE THREADSAFE
353 #else
354 # define SQLITE_THREADSAFE 1
355 #endif
356 #endif
357
358 /*
359 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
360 ** It determines whether or not the features related to 
361 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
362 ** be overridden at runtime using the sqlite3_config() API.
363 */
364 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
365 # define SQLITE_DEFAULT_MEMSTATUS 1
366 #endif
367
368 /*
369 ** Exactly one of the following macros must be defined in order to
370 ** specify which memory allocation subsystem to use.
371 **
372 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
373 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
374 **     SQLITE_MEMORY_SIZE            // internal allocator #1
375 **     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
376 **     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
377 **
378 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
379 ** the default.
380 */
381 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
382     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
383     defined(SQLITE_POW2_MEMORY_SIZE)>1
384 # error "At most one of the following compile-time configuration options\
385  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
386  SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
387 #endif
388 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
389     defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
390     defined(SQLITE_POW2_MEMORY_SIZE)==0
391 # define SQLITE_SYSTEM_MALLOC 1
392 #endif
393
394 /*
395 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
396 ** sizes of memory allocations below this value where possible.
397 */
398 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
399 # define SQLITE_MALLOC_SOFT_LIMIT 1024
400 #endif
401
402 /*
403 ** We need to define _XOPEN_SOURCE as follows in order to enable
404 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
405 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
406 ** so it is omitted there.  See ticket #2673.
407 **
408 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
409 ** implemented on some systems.  So we avoid defining it at all
410 ** if it is already defined or if it is unneeded because we are
411 ** not doing a threadsafe build.  Ticket #2681.
412 **
413 ** See also ticket #2741.
414 */
415 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
416 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
417 #endif
418
419 /*
420 ** The TCL headers are only needed when compiling the TCL bindings.
421 */
422 #if defined(SQLITE_TCL) || defined(TCLSH)
423 # include <tcl.h>
424 #endif
425
426 /*
427 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
428 ** Setting NDEBUG makes the code smaller and run faster.  So the following
429 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
430 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
431 ** feature.
432 */
433 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
434 # define NDEBUG 1
435 #endif
436
437 /*
438 ** The testcase() macro is used to aid in coverage testing.  When 
439 ** doing coverage testing, the condition inside the argument to
440 ** testcase() must be evaluated both true and false in order to
441 ** get full branch coverage.  The testcase() macro is inserted
442 ** to help ensure adequate test coverage in places where simple
443 ** condition/decision coverage is inadequate.  For example, testcase()
444 ** can be used to make sure boundary values are tested.  For
445 ** bitmask tests, testcase() can be used to make sure each bit
446 ** is significant and used at least once.  On switch statements
447 ** where multiple cases go to the same block of code, testcase()
448 ** can insure that all cases are evaluated.
449 **
450 */
451 #ifdef SQLITE_COVERAGE_TEST
452 SQLITE_PRIVATE   void sqlite3Coverage(int);
453 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
454 #else
455 # define testcase(X)
456 #endif
457
458 /*
459 ** The TESTONLY macro is used to enclose variable declarations or
460 ** other bits of code that are needed to support the arguments
461 ** within testcase() and assert() macros.
462 */
463 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
464 # define TESTONLY(X)  X
465 #else
466 # define TESTONLY(X)
467 #endif
468
469 /*
470 ** Sometimes we need a small amount of code such as a variable initialization
471 ** to setup for a later assert() statement.  We do not want this code to
472 ** appear when assert() is disabled.  The following macro is therefore
473 ** used to contain that setup code.  The "VVA" acronym stands for
474 ** "Verification, Validation, and Accreditation".  In other words, the
475 ** code within VVA_ONLY() will only run during verification processes.
476 */
477 #ifndef NDEBUG
478 # define VVA_ONLY(X)  X
479 #else
480 # define VVA_ONLY(X)
481 #endif
482
483 /*
484 ** The ALWAYS and NEVER macros surround boolean expressions which 
485 ** are intended to always be true or false, respectively.  Such
486 ** expressions could be omitted from the code completely.  But they
487 ** are included in a few cases in order to enhance the resilience
488 ** of SQLite to unexpected behavior - to make the code "self-healing"
489 ** or "ductile" rather than being "brittle" and crashing at the first
490 ** hint of unplanned behavior.
491 **
492 ** In other words, ALWAYS and NEVER are added for defensive code.
493 **
494 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
495 ** be true and false so that the unreachable code then specify will
496 ** not be counted as untested code.
497 */
498 #if defined(SQLITE_COVERAGE_TEST)
499 # define ALWAYS(X)      (1)
500 # define NEVER(X)       (0)
501 #elif !defined(NDEBUG)
502 # define ALWAYS(X)      ((X)?1:(assert(0),0))
503 # define NEVER(X)       ((X)?(assert(0),1):0)
504 #else
505 # define ALWAYS(X)      (X)
506 # define NEVER(X)       (X)
507 #endif
508
509 /*
510 ** The macro unlikely() is a hint that surrounds a boolean
511 ** expression that is usually false.  Macro likely() surrounds
512 ** a boolean expression that is usually true.  GCC is able to
513 ** use these hints to generate better code, sometimes.
514 */
515 #if defined(__GNUC__) && 0
516 # define likely(X)    __builtin_expect((X),1)
517 # define unlikely(X)  __builtin_expect((X),0)
518 #else
519 # define likely(X)    !!(X)
520 # define unlikely(X)  !!(X)
521 #endif
522
523 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
524 /************** Begin file sqlite3.h *****************************************/
525 /*
526 ** 2001 September 15
527 **
528 ** The author disclaims copyright to this source code.  In place of
529 ** a legal notice, here is a blessing:
530 **
531 **    May you do good and not evil.
532 **    May you find forgiveness for yourself and forgive others.
533 **    May you share freely, never taking more than you give.
534 **
535 *************************************************************************
536 ** This header file defines the interface that the SQLite library
537 ** presents to client programs.  If a C-function, structure, datatype,
538 ** or constant definition does not appear in this file, then it is
539 ** not a published API of SQLite, is subject to change without
540 ** notice, and should not be referenced by programs that use SQLite.
541 **
542 ** Some of the definitions that are in this file are marked as
543 ** "experimental".  Experimental interfaces are normally new
544 ** features recently added to SQLite.  We do not anticipate changes
545 ** to experimental interfaces but reserve the right to make minor changes
546 ** if experience from use "in the wild" suggest such changes are prudent.
547 **
548 ** The official C-language API documentation for SQLite is derived
549 ** from comments in this file.  This file is the authoritative source
550 ** on how SQLite interfaces are suppose to operate.
551 **
552 ** The name of this file under configuration management is "sqlite.h.in".
553 ** The makefile makes some minor changes to this file (such as inserting
554 ** the version number) and changes its name to "sqlite3.h" as
555 ** part of the build process.
556 */
557 #ifndef _SQLITE3_H_
558 #define _SQLITE3_H_
559 #include <stdarg.h>     /* Needed for the definition of va_list */
560
561 /*
562 ** Make sure we can call this stuff from C++.
563 */
564 #if 0
565 extern "C" {
566 #endif
567
568
569 /*
570 ** Add the ability to override 'extern'
571 */
572 #ifndef SQLITE_EXTERN
573 # define SQLITE_EXTERN extern
574 #endif
575
576 #ifndef SQLITE_API
577 # define SQLITE_API
578 #endif
579
580
581 /*
582 ** These no-op macros are used in front of interfaces to mark those
583 ** interfaces as either deprecated or experimental.  New applications
584 ** should not use deprecated interfaces - they are support for backwards
585 ** compatibility only.  Application writers should be aware that
586 ** experimental interfaces are subject to change in point releases.
587 **
588 ** These macros used to resolve to various kinds of compiler magic that
589 ** would generate warning messages when they were used.  But that
590 ** compiler magic ended up generating such a flurry of bug reports
591 ** that we have taken it all out and gone back to using simple
592 ** noop macros.
593 */
594 #define SQLITE_DEPRECATED
595 #define SQLITE_EXPERIMENTAL
596
597 /*
598 ** Ensure these symbols were not defined by some previous header file.
599 */
600 #ifdef SQLITE_VERSION
601 # undef SQLITE_VERSION
602 #endif
603 #ifdef SQLITE_VERSION_NUMBER
604 # undef SQLITE_VERSION_NUMBER
605 #endif
606
607 /*
608 ** CAPI3REF: Compile-Time Library Version Numbers
609 **
610 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
611 ** evaluates to a string literal that is the SQLite version in the
612 ** format "X.Y.Z" where X is the major version number (always 3 for
613 ** SQLite3) and Y is the minor version number and Z is the release number.)^
614 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
615 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
616 ** numbers used in [SQLITE_VERSION].)^
617 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
618 ** be larger than the release from which it is derived.  Either Y will
619 ** be held constant and Z will be incremented or else Y will be incremented
620 ** and Z will be reset to zero.
621 **
622 ** Since version 3.6.18, SQLite source code has been stored in the
623 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
624 ** system</a>.  ^The SQLITE_SOURCE_ID macro evalutes to
625 ** a string which identifies a particular check-in of SQLite
626 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
627 ** string contains the date and time of the check-in (UTC) and an SHA1
628 ** hash of the entire source tree.
629 **
630 ** See also: [sqlite3_libversion()],
631 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
632 ** [sqlite_version()] and [sqlite_source_id()].
633 */
634 #define SQLITE_VERSION        "3.6.22"
635 #define SQLITE_VERSION_NUMBER 3006022
636 #define SQLITE_SOURCE_ID      "2010-01-05 15:30:36 28d0d7710761114a44a1a3a425a6883c661f06e7"
637
638 /*
639 ** CAPI3REF: Run-Time Library Version Numbers
640 ** KEYWORDS: sqlite3_version
641 **
642 ** These interfaces provide the same information as the [SQLITE_VERSION],
643 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
644 ** but are associated with the library instead of the header file.  ^(Cautious
645 ** programmers might include assert() statements in their application to
646 ** verify that values returned by these interfaces match the macros in
647 ** the header, and thus insure that the application is
648 ** compiled with matching library and header files.
649 **
650 ** <blockquote><pre>
651 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
652 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
653 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
654 ** </pre></blockquote>)^
655 **
656 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
657 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
658 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
659 ** function is provided for use in DLLs since DLL users usually do not have
660 ** direct access to string constants within the DLL.  ^The
661 ** sqlite3_libversion_number() function returns an integer equal to
662 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function a pointer
663 ** to a string constant whose value is the same as the [SQLITE_SOURCE_ID]
664 ** C preprocessor macro.
665 **
666 ** See also: [sqlite_version()] and [sqlite_source_id()].
667 */
668 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
669 SQLITE_API const char *sqlite3_libversion(void);
670 SQLITE_API const char *sqlite3_sourceid(void);
671 SQLITE_API int sqlite3_libversion_number(void);
672
673 /*
674 ** CAPI3REF: Test To See If The Library Is Threadsafe
675 **
676 ** ^The sqlite3_threadsafe() function returns zero if and only if
677 ** SQLite was compiled mutexing code omitted due to the
678 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
679 **
680 ** SQLite can be compiled with or without mutexes.  When
681 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
682 ** are enabled and SQLite is threadsafe.  When the
683 ** [SQLITE_THREADSAFE] macro is 0, 
684 ** the mutexes are omitted.  Without the mutexes, it is not safe
685 ** to use SQLite concurrently from more than one thread.
686 **
687 ** Enabling mutexes incurs a measurable performance penalty.
688 ** So if speed is of utmost importance, it makes sense to disable
689 ** the mutexes.  But for maximum safety, mutexes should be enabled.
690 ** ^The default behavior is for mutexes to be enabled.
691 **
692 ** This interface can be used by an application to make sure that the
693 ** version of SQLite that it is linking against was compiled with
694 ** the desired setting of the [SQLITE_THREADSAFE] macro.
695 **
696 ** This interface only reports on the compile-time mutex setting
697 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
698 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
699 ** can be fully or partially disabled using a call to [sqlite3_config()]
700 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
701 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
702 ** sqlite3_threadsafe() function shows only the compile-time setting of
703 ** thread safety, not any run-time changes to that setting made by
704 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
705 ** is unchanged by calls to sqlite3_config().)^
706 **
707 ** See the [threading mode] documentation for additional information.
708 */
709 SQLITE_API int sqlite3_threadsafe(void);
710
711 /*
712 ** CAPI3REF: Database Connection Handle
713 ** KEYWORDS: {database connection} {database connections}
714 **
715 ** Each open SQLite database is represented by a pointer to an instance of
716 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
717 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
718 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
719 ** is its destructor.  There are many other interfaces (such as
720 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
721 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
722 ** sqlite3 object.
723 */
724 typedef struct sqlite3 sqlite3;
725
726 /*
727 ** CAPI3REF: 64-Bit Integer Types
728 ** KEYWORDS: sqlite_int64 sqlite_uint64
729 **
730 ** Because there is no cross-platform way to specify 64-bit integer types
731 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
732 **
733 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
734 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
735 ** compatibility only.
736 **
737 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
738 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
739 ** sqlite3_uint64 and sqlite_uint64 types can store integer values 
740 ** between 0 and +18446744073709551615 inclusive.
741 */
742 #ifdef SQLITE_INT64_TYPE
743   typedef SQLITE_INT64_TYPE sqlite_int64;
744   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
745 #elif defined(_MSC_VER) || defined(__BORLANDC__)
746   typedef __int64 sqlite_int64;
747   typedef unsigned __int64 sqlite_uint64;
748 #else
749   typedef long long int sqlite_int64;
750   typedef unsigned long long int sqlite_uint64;
751 #endif
752 typedef sqlite_int64 sqlite3_int64;
753 typedef sqlite_uint64 sqlite3_uint64;
754
755 /*
756 ** If compiling for a processor that lacks floating point support,
757 ** substitute integer for floating-point.
758 */
759 #ifdef SQLITE_OMIT_FLOATING_POINT
760 # define double sqlite3_int64
761 #endif
762
763 /*
764 ** CAPI3REF: Closing A Database Connection
765 **
766 ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
767 ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
768 ** successfullly destroyed and all associated resources are deallocated.
769 **
770 ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
771 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
772 ** the [sqlite3] object prior to attempting to close the object.  ^If
773 ** sqlite3_close() is called on a [database connection] that still has
774 ** outstanding [prepared statements] or [BLOB handles], then it returns
775 ** SQLITE_BUSY.
776 **
777 ** ^If [sqlite3_close()] is invoked while a transaction is open,
778 ** the transaction is automatically rolled back.
779 **
780 ** The C parameter to [sqlite3_close(C)] must be either a NULL
781 ** pointer or an [sqlite3] object pointer obtained
782 ** from [sqlite3_open()], [sqlite3_open16()], or
783 ** [sqlite3_open_v2()], and not previously closed.
784 ** ^Calling sqlite3_close() with a NULL pointer argument is a 
785 ** harmless no-op.
786 */
787 SQLITE_API int sqlite3_close(sqlite3 *);
788
789 /*
790 ** The type for a callback function.
791 ** This is legacy and deprecated.  It is included for historical
792 ** compatibility and is not documented.
793 */
794 typedef int (*sqlite3_callback)(void*,int,char**, char**);
795
796 /*
797 ** CAPI3REF: One-Step Query Execution Interface
798 **
799 ** The sqlite3_exec() interface is a convenience wrapper around
800 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
801 ** that allows an application to run multiple statements of SQL
802 ** without having to use a lot of C code. 
803 **
804 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
805 ** semicolon-separate SQL statements passed into its 2nd argument,
806 ** in the context of the [database connection] passed in as its 1st
807 ** argument.  ^If the callback function of the 3rd argument to
808 ** sqlite3_exec() is not NULL, then it is invoked for each result row
809 ** coming out of the evaluated SQL statements.  ^The 4th argument to
810 ** to sqlite3_exec() is relayed through to the 1st argument of each
811 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
812 ** is NULL, then no callback is ever invoked and result rows are
813 ** ignored.
814 **
815 ** ^If an error occurs while evaluating the SQL statements passed into
816 ** sqlite3_exec(), then execution of the current statement stops and
817 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
818 ** is not NULL then any error message is written into memory obtained
819 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
820 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
821 ** on error message strings returned through the 5th parameter of
822 ** of sqlite3_exec() after the error message string is no longer needed.
823 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
824 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
825 ** NULL before returning.
826 **
827 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
828 ** routine returns SQLITE_ABORT without invoking the callback again and
829 ** without running any subsequent SQL statements.
830 **
831 ** ^The 2nd argument to the sqlite3_exec() callback function is the
832 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
833 ** callback is an array of pointers to strings obtained as if from
834 ** [sqlite3_column_text()], one for each column.  ^If an element of a
835 ** result row is NULL then the corresponding string pointer for the
836 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
837 ** sqlite3_exec() callback is an array of pointers to strings where each
838 ** entry represents the name of corresponding result column as obtained
839 ** from [sqlite3_column_name()].
840 **
841 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
842 ** to an empty string, or a pointer that contains only whitespace and/or 
843 ** SQL comments, then no SQL statements are evaluated and the database
844 ** is not changed.
845 **
846 ** Restrictions:
847 **
848 ** <ul>
849 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
850 **      is a valid and open [database connection].
851 ** <li> The application must not close [database connection] specified by
852 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
853 ** <li> The application must not modify the SQL statement text passed into
854 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
855 ** </ul>
856 */
857 SQLITE_API int sqlite3_exec(
858   sqlite3*,                                  /* An open database */
859   const char *sql,                           /* SQL to be evaluated */
860   int (*callback)(void*,int,char**,char**),  /* Callback function */
861   void *,                                    /* 1st argument to callback */
862   char **errmsg                              /* Error msg written here */
863 );
864
865 /*
866 ** CAPI3REF: Result Codes
867 ** KEYWORDS: SQLITE_OK {error code} {error codes}
868 ** KEYWORDS: {result code} {result codes}
869 **
870 ** Many SQLite functions return an integer result code from the set shown
871 ** here in order to indicates success or failure.
872 **
873 ** New error codes may be added in future versions of SQLite.
874 **
875 ** See also: [SQLITE_IOERR_READ | extended result codes]
876 */
877 #define SQLITE_OK           0   /* Successful result */
878 /* beginning-of-error-codes */
879 #define SQLITE_ERROR        1   /* SQL error or missing database */
880 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
881 #define SQLITE_PERM         3   /* Access permission denied */
882 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
883 #define SQLITE_BUSY         5   /* The database file is locked */
884 #define SQLITE_LOCKED       6   /* A table in the database is locked */
885 #define SQLITE_NOMEM        7   /* A malloc() failed */
886 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
887 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
888 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
889 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
890 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
891 #define SQLITE_FULL        13   /* Insertion failed because database is full */
892 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
893 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
894 #define SQLITE_EMPTY       16   /* Database is empty */
895 #define SQLITE_SCHEMA      17   /* The database schema changed */
896 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
897 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
898 #define SQLITE_MISMATCH    20   /* Data type mismatch */
899 #define SQLITE_MISUSE      21   /* Library used incorrectly */
900 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
901 #define SQLITE_AUTH        23   /* Authorization denied */
902 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
903 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
904 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
905 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
906 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
907 /* end-of-error-codes */
908
909 /*
910 ** CAPI3REF: Extended Result Codes
911 ** KEYWORDS: {extended error code} {extended error codes}
912 ** KEYWORDS: {extended result code} {extended result codes}
913 **
914 ** In its default configuration, SQLite API routines return one of 26 integer
915 ** [SQLITE_OK | result codes].  However, experience has shown that many of
916 ** these result codes are too coarse-grained.  They do not provide as
917 ** much information about problems as programmers might like.  In an effort to
918 ** address this, newer versions of SQLite (version 3.3.8 and later) include
919 ** support for additional result codes that provide more detailed information
920 ** about errors. The extended result codes are enabled or disabled
921 ** on a per database connection basis using the
922 ** [sqlite3_extended_result_codes()] API.
923 **
924 ** Some of the available extended result codes are listed here.
925 ** One may expect the number of extended result codes will be expand
926 ** over time.  Software that uses extended result codes should expect
927 ** to see new result codes in future releases of SQLite.
928 **
929 ** The SQLITE_OK result code will never be extended.  It will always
930 ** be exactly zero.
931 */
932 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
933 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
934 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
935 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
936 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
937 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
938 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
939 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
940 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
941 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
942 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
943 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
944 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
945 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
946 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
947 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
948 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
949 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED | (1<<8) )
950
951 /*
952 ** CAPI3REF: Flags For File Open Operations
953 **
954 ** These bit values are intended for use in the
955 ** 3rd parameter to the [sqlite3_open_v2()] interface and
956 ** in the 4th parameter to the xOpen method of the
957 ** [sqlite3_vfs] object.
958 */
959 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
960 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
961 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
962 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
963 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
964 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
965 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
966 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
967 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
968 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
969 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
970 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
971 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
972 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
973 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
974 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
975
976 /*
977 ** CAPI3REF: Device Characteristics
978 **
979 ** The xDeviceCapabilities method of the [sqlite3_io_methods]
980 ** object returns an integer which is a vector of the these
981 ** bit values expressing I/O characteristics of the mass storage
982 ** device that holds the file that the [sqlite3_io_methods]
983 ** refers to.
984 **
985 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
986 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
987 ** mean that writes of blocks that are nnn bytes in size and
988 ** are aligned to an address which is an integer multiple of
989 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
990 ** that when data is appended to a file, the data is appended
991 ** first then the size of the file is extended, never the other
992 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
993 ** information is written to disk in the same order as calls
994 ** to xWrite().
995 */
996 #define SQLITE_IOCAP_ATOMIC          0x00000001
997 #define SQLITE_IOCAP_ATOMIC512       0x00000002
998 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
999 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
1000 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
1001 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
1002 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
1003 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
1004 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
1005 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
1006 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
1007
1008 /*
1009 ** CAPI3REF: File Locking Levels
1010 **
1011 ** SQLite uses one of these integer values as the second
1012 ** argument to calls it makes to the xLock() and xUnlock() methods
1013 ** of an [sqlite3_io_methods] object.
1014 */
1015 #define SQLITE_LOCK_NONE          0
1016 #define SQLITE_LOCK_SHARED        1
1017 #define SQLITE_LOCK_RESERVED      2
1018 #define SQLITE_LOCK_PENDING       3
1019 #define SQLITE_LOCK_EXCLUSIVE     4
1020
1021 /*
1022 ** CAPI3REF: Synchronization Type Flags
1023 **
1024 ** When SQLite invokes the xSync() method of an
1025 ** [sqlite3_io_methods] object it uses a combination of
1026 ** these integer values as the second argument.
1027 **
1028 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1029 ** sync operation only needs to flush data to mass storage.  Inode
1030 ** information need not be flushed. If the lower four bits of the flag
1031 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1032 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1033 ** to use Mac OS X style fullsync instead of fsync().
1034 */
1035 #define SQLITE_SYNC_NORMAL        0x00002
1036 #define SQLITE_SYNC_FULL          0x00003
1037 #define SQLITE_SYNC_DATAONLY      0x00010
1038
1039 /*
1040 ** CAPI3REF: OS Interface Open File Handle
1041 **
1042 ** An [sqlite3_file] object represents an open file in the 
1043 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1044 ** implementations will
1045 ** want to subclass this object by appending additional fields
1046 ** for their own use.  The pMethods entry is a pointer to an
1047 ** [sqlite3_io_methods] object that defines methods for performing
1048 ** I/O operations on the open file.
1049 */
1050 typedef struct sqlite3_file sqlite3_file;
1051 struct sqlite3_file {
1052   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1053 };
1054
1055 /*
1056 ** CAPI3REF: OS Interface File Virtual Methods Object
1057 **
1058 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
1059 ** [sqlite3_file] object (or, more commonly, a subclass of the
1060 ** [sqlite3_file] object) with a pointer to an instance of this object.
1061 ** This object defines the methods used to perform various operations
1062 ** against the open file represented by the [sqlite3_file] object.
1063 **
1064 ** If the xOpen method sets the sqlite3_file.pMethods element 
1065 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1066 ** may be invoked even if the xOpen reported that it failed.  The
1067 ** only way to prevent a call to xClose following a failed xOpen
1068 ** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
1069 **
1070 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1071 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1072 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1073 ** flag may be ORed in to indicate that only the data of the file
1074 ** and not its inode needs to be synced.
1075 **
1076 ** The integer values to xLock() and xUnlock() are one of
1077 ** <ul>
1078 ** <li> [SQLITE_LOCK_NONE],
1079 ** <li> [SQLITE_LOCK_SHARED],
1080 ** <li> [SQLITE_LOCK_RESERVED],
1081 ** <li> [SQLITE_LOCK_PENDING], or
1082 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1083 ** </ul>
1084 ** xLock() increases the lock. xUnlock() decreases the lock.
1085 ** The xCheckReservedLock() method checks whether any database connection,
1086 ** either in this process or in some other process, is holding a RESERVED,
1087 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1088 ** if such a lock exists and false otherwise.
1089 **
1090 ** The xFileControl() method is a generic interface that allows custom
1091 ** VFS implementations to directly control an open file using the
1092 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1093 ** integer opcode.  The third argument is a generic pointer intended to
1094 ** point to a structure that may contain arguments or space in which to
1095 ** write return values.  Potential uses for xFileControl() might be
1096 ** functions to enable blocking locks with timeouts, to change the
1097 ** locking strategy (for example to use dot-file locks), to inquire
1098 ** about the status of a lock, or to break stale locks.  The SQLite
1099 ** core reserves all opcodes less than 100 for its own use.
1100 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1101 ** Applications that define a custom xFileControl method should use opcodes
1102 ** greater than 100 to avoid conflicts.
1103 **
1104 ** The xSectorSize() method returns the sector size of the
1105 ** device that underlies the file.  The sector size is the
1106 ** minimum write that can be performed without disturbing
1107 ** other bytes in the file.  The xDeviceCharacteristics()
1108 ** method returns a bit vector describing behaviors of the
1109 ** underlying device:
1110 **
1111 ** <ul>
1112 ** <li> [SQLITE_IOCAP_ATOMIC]
1113 ** <li> [SQLITE_IOCAP_ATOMIC512]
1114 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1115 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1116 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1117 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1118 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1119 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1120 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1121 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1122 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1123 ** </ul>
1124 **
1125 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1126 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1127 ** mean that writes of blocks that are nnn bytes in size and
1128 ** are aligned to an address which is an integer multiple of
1129 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1130 ** that when data is appended to a file, the data is appended
1131 ** first then the size of the file is extended, never the other
1132 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1133 ** information is written to disk in the same order as calls
1134 ** to xWrite().
1135 **
1136 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1137 ** in the unread portions of the buffer with zeros.  A VFS that
1138 ** fails to zero-fill short reads might seem to work.  However,
1139 ** failure to zero-fill short reads will eventually lead to
1140 ** database corruption.
1141 */
1142 typedef struct sqlite3_io_methods sqlite3_io_methods;
1143 struct sqlite3_io_methods {
1144   int iVersion;
1145   int (*xClose)(sqlite3_file*);
1146   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1147   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1148   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1149   int (*xSync)(sqlite3_file*, int flags);
1150   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1151   int (*xLock)(sqlite3_file*, int);
1152   int (*xUnlock)(sqlite3_file*, int);
1153   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1154   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1155   int (*xSectorSize)(sqlite3_file*);
1156   int (*xDeviceCharacteristics)(sqlite3_file*);
1157   /* Additional methods may be added in future releases */
1158 };
1159
1160 /*
1161 ** CAPI3REF: Standard File Control Opcodes
1162 **
1163 ** These integer constants are opcodes for the xFileControl method
1164 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1165 ** interface.
1166 **
1167 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1168 ** opcode causes the xFileControl method to write the current state of
1169 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1170 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1171 ** into an integer that the pArg argument points to. This capability
1172 ** is used during testing and only needs to be supported when SQLITE_TEST
1173 ** is defined.
1174 */
1175 #define SQLITE_FCNTL_LOCKSTATE        1
1176 #define SQLITE_GET_LOCKPROXYFILE      2
1177 #define SQLITE_SET_LOCKPROXYFILE      3
1178 #define SQLITE_LAST_ERRNO             4
1179
1180 /*
1181 ** CAPI3REF: Mutex Handle
1182 **
1183 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1184 ** abstract type for a mutex object.  The SQLite core never looks
1185 ** at the internal representation of an [sqlite3_mutex].  It only
1186 ** deals with pointers to the [sqlite3_mutex] object.
1187 **
1188 ** Mutexes are created using [sqlite3_mutex_alloc()].
1189 */
1190 typedef struct sqlite3_mutex sqlite3_mutex;
1191
1192 /*
1193 ** CAPI3REF: OS Interface Object
1194 **
1195 ** An instance of the sqlite3_vfs object defines the interface between
1196 ** the SQLite core and the underlying operating system.  The "vfs"
1197 ** in the name of the object stands for "virtual file system".
1198 **
1199 ** The value of the iVersion field is initially 1 but may be larger in
1200 ** future versions of SQLite.  Additional fields may be appended to this
1201 ** object when the iVersion value is increased.  Note that the structure
1202 ** of the sqlite3_vfs object changes in the transaction between
1203 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1204 ** modified.
1205 **
1206 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1207 ** structure used by this VFS.  mxPathname is the maximum length of
1208 ** a pathname in this VFS.
1209 **
1210 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1211 ** the pNext pointer.  The [sqlite3_vfs_register()]
1212 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1213 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1214 ** searches the list.  Neither the application code nor the VFS
1215 ** implementation should use the pNext pointer.
1216 **
1217 ** The pNext field is the only field in the sqlite3_vfs
1218 ** structure that SQLite will ever modify.  SQLite will only access
1219 ** or modify this field while holding a particular static mutex.
1220 ** The application should never modify anything within the sqlite3_vfs
1221 ** object once the object has been registered.
1222 **
1223 ** The zName field holds the name of the VFS module.  The name must
1224 ** be unique across all VFS modules.
1225 **
1226 ** SQLite will guarantee that the zFilename parameter to xOpen
1227 ** is either a NULL pointer or string obtained
1228 ** from xFullPathname().  SQLite further guarantees that
1229 ** the string will be valid and unchanged until xClose() is
1230 ** called. Because of the previous sentence,
1231 ** the [sqlite3_file] can safely store a pointer to the
1232 ** filename if it needs to remember the filename for some reason.
1233 ** If the zFilename parameter is xOpen is a NULL pointer then xOpen
1234 ** must invent its own temporary name for the file.  Whenever the 
1235 ** xFilename parameter is NULL it will also be the case that the
1236 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1237 **
1238 ** The flags argument to xOpen() includes all bits set in
1239 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1240 ** or [sqlite3_open16()] is used, then flags includes at least
1241 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
1242 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1243 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1244 **
1245 ** SQLite will also add one of the following flags to the xOpen()
1246 ** call, depending on the object being opened:
1247 **
1248 ** <ul>
1249 ** <li>  [SQLITE_OPEN_MAIN_DB]
1250 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1251 ** <li>  [SQLITE_OPEN_TEMP_DB]
1252 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1253 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1254 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1255 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1256 ** </ul>
1257 **
1258 ** The file I/O implementation can use the object type flags to
1259 ** change the way it deals with files.  For example, an application
1260 ** that does not care about crash recovery or rollback might make
1261 ** the open of a journal file a no-op.  Writes to this journal would
1262 ** also be no-ops, and any attempt to read the journal would return
1263 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1264 ** file will be doing page-aligned sector reads and writes in a random
1265 ** order and set up its I/O subsystem accordingly.
1266 **
1267 ** SQLite might also add one of the following flags to the xOpen method:
1268 **
1269 ** <ul>
1270 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1271 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1272 ** </ul>
1273 **
1274 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1275 ** deleted when it is closed.  The [SQLITE_OPEN_DELETEONCLOSE]
1276 ** will be set for TEMP  databases, journals and for subjournals.
1277 **
1278 ** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1279 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1280 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1281 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
1282 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1283 ** be created, and that it is an error if it already exists.
1284 ** It is <i>not</i> used to indicate the file should be opened 
1285 ** for exclusive access.
1286 **
1287 ** At least szOsFile bytes of memory are allocated by SQLite
1288 ** to hold the  [sqlite3_file] structure passed as the third
1289 ** argument to xOpen.  The xOpen method does not have to
1290 ** allocate the structure; it should just fill it in.  Note that
1291 ** the xOpen method must set the sqlite3_file.pMethods to either
1292 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1293 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1294 ** element will be valid after xOpen returns regardless of the success
1295 ** or failure of the xOpen call.
1296 **
1297 ** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1298 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1299 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1300 ** to test whether a file is at least readable.   The file can be a
1301 ** directory.
1302 **
1303 ** SQLite will always allocate at least mxPathname+1 bytes for the
1304 ** output buffer xFullPathname.  The exact size of the output buffer
1305 ** is also passed as a parameter to both  methods. If the output buffer
1306 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1307 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1308 ** to prevent this by setting mxPathname to a sufficiently large value.
1309 **
1310 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
1311 ** are not strictly a part of the filesystem, but they are
1312 ** included in the VFS structure for completeness.
1313 ** The xRandomness() function attempts to return nBytes bytes
1314 ** of good-quality randomness into zOut.  The return value is
1315 ** the actual number of bytes of randomness obtained.
1316 ** The xSleep() method causes the calling thread to sleep for at
1317 ** least the number of microseconds given.  The xCurrentTime()
1318 ** method returns a Julian Day Number for the current date and time.
1319 **
1320 */
1321 typedef struct sqlite3_vfs sqlite3_vfs;
1322 struct sqlite3_vfs {
1323   int iVersion;            /* Structure version number */
1324   int szOsFile;            /* Size of subclassed sqlite3_file */
1325   int mxPathname;          /* Maximum file pathname length */
1326   sqlite3_vfs *pNext;      /* Next registered VFS */
1327   const char *zName;       /* Name of this virtual file system */
1328   void *pAppData;          /* Pointer to application-specific data */
1329   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1330                int flags, int *pOutFlags);
1331   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1332   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1333   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1334   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1335   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1336   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1337   void (*xDlClose)(sqlite3_vfs*, void*);
1338   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1339   int (*xSleep)(sqlite3_vfs*, int microseconds);
1340   int (*xCurrentTime)(sqlite3_vfs*, double*);
1341   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1342   /* New fields may be appended in figure versions.  The iVersion
1343   ** value will increment whenever this happens. */
1344 };
1345
1346 /*
1347 ** CAPI3REF: Flags for the xAccess VFS method
1348 **
1349 ** These integer constants can be used as the third parameter to
1350 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1351 ** what kind of permissions the xAccess method is looking for.
1352 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1353 ** simply checks whether the file exists.
1354 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1355 ** checks whether the file is both readable and writable.
1356 ** With SQLITE_ACCESS_READ, the xAccess method
1357 ** checks whether the file is readable.
1358 */
1359 #define SQLITE_ACCESS_EXISTS    0
1360 #define SQLITE_ACCESS_READWRITE 1
1361 #define SQLITE_ACCESS_READ      2
1362
1363 /*
1364 ** CAPI3REF: Initialize The SQLite Library
1365 **
1366 ** ^The sqlite3_initialize() routine initializes the
1367 ** SQLite library.  ^The sqlite3_shutdown() routine
1368 ** deallocates any resources that were allocated by sqlite3_initialize().
1369 ** These routines are designed to aid in process initialization and
1370 ** shutdown on embedded systems.  Workstation applications using
1371 ** SQLite normally do not need to invoke either of these routines.
1372 **
1373 ** A call to sqlite3_initialize() is an "effective" call if it is
1374 ** the first time sqlite3_initialize() is invoked during the lifetime of
1375 ** the process, or if it is the first time sqlite3_initialize() is invoked
1376 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1377 ** of sqlite3_initialize() does any initialization.  All other calls
1378 ** are harmless no-ops.)^
1379 **
1380 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1381 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1382 ** an effective call to sqlite3_shutdown() does any deinitialization.
1383 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1384 **
1385 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1386 ** is not.  The sqlite3_shutdown() interface must only be called from a
1387 ** single thread.  All open [database connections] must be closed and all
1388 ** other SQLite resources must be deallocated prior to invoking
1389 ** sqlite3_shutdown().
1390 **
1391 ** Among other things, ^sqlite3_initialize() will invoke
1392 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1393 ** will invoke sqlite3_os_end().
1394 **
1395 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1396 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1397 ** the library (perhaps it is unable to allocate a needed resource such
1398 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1399 **
1400 ** ^The sqlite3_initialize() routine is called internally by many other
1401 ** SQLite interfaces so that an application usually does not need to
1402 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1403 ** calls sqlite3_initialize() so the SQLite library will be automatically
1404 ** initialized when [sqlite3_open()] is called if it has not be initialized
1405 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1406 ** compile-time option, then the automatic calls to sqlite3_initialize()
1407 ** are omitted and the application must call sqlite3_initialize() directly
1408 ** prior to using any other SQLite interface.  For maximum portability,
1409 ** it is recommended that applications always invoke sqlite3_initialize()
1410 ** directly prior to using any other SQLite interface.  Future releases
1411 ** of SQLite may require this.  In other words, the behavior exhibited
1412 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1413 ** default behavior in some future release of SQLite.
1414 **
1415 ** The sqlite3_os_init() routine does operating-system specific
1416 ** initialization of the SQLite library.  The sqlite3_os_end()
1417 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1418 ** performed by these routines include allocation or deallocation
1419 ** of static resources, initialization of global variables,
1420 ** setting up a default [sqlite3_vfs] module, or setting up
1421 ** a default configuration using [sqlite3_config()].
1422 **
1423 ** The application should never invoke either sqlite3_os_init()
1424 ** or sqlite3_os_end() directly.  The application should only invoke
1425 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1426 ** interface is called automatically by sqlite3_initialize() and
1427 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1428 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1429 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1430 ** When [custom builds | built for other platforms]
1431 ** (using the [SQLITE_OS_OTHER=1] compile-time
1432 ** option) the application must supply a suitable implementation for
1433 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1434 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1435 ** must return [SQLITE_OK] on success and some other [error code] upon
1436 ** failure.
1437 */
1438 SQLITE_API int sqlite3_initialize(void);
1439 SQLITE_API int sqlite3_shutdown(void);
1440 SQLITE_API int sqlite3_os_init(void);
1441 SQLITE_API int sqlite3_os_end(void);
1442
1443 /*
1444 ** CAPI3REF: Configuring The SQLite Library
1445 ** EXPERIMENTAL
1446 **
1447 ** The sqlite3_config() interface is used to make global configuration
1448 ** changes to SQLite in order to tune SQLite to the specific needs of
1449 ** the application.  The default configuration is recommended for most
1450 ** applications and so this routine is usually not necessary.  It is
1451 ** provided to support rare applications with unusual needs.
1452 **
1453 ** The sqlite3_config() interface is not threadsafe.  The application
1454 ** must insure that no other SQLite interfaces are invoked by other
1455 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1456 ** may only be invoked prior to library initialization using
1457 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1458 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1459 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1460 ** Note, however, that ^sqlite3_config() can be called as part of the
1461 ** implementation of an application-defined [sqlite3_os_init()].
1462 **
1463 ** The first argument to sqlite3_config() is an integer
1464 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1465 ** what property of SQLite is to be configured.  Subsequent arguments
1466 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1467 ** in the first argument.
1468 **
1469 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1470 ** ^If the option is unknown or SQLite is unable to set the option
1471 ** then this routine returns a non-zero [error code].
1472 */
1473 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
1474
1475 /*
1476 ** CAPI3REF: Configure database connections
1477 ** EXPERIMENTAL
1478 **
1479 ** The sqlite3_db_config() interface is used to make configuration
1480 ** changes to a [database connection].  The interface is similar to
1481 ** [sqlite3_config()] except that the changes apply to a single
1482 ** [database connection] (specified in the first argument).  The
1483 ** sqlite3_db_config() interface should only be used immediately after
1484 ** the database connection is created using [sqlite3_open()],
1485 ** [sqlite3_open16()], or [sqlite3_open_v2()].  
1486 **
1487 ** The second argument to sqlite3_db_config(D,V,...)  is the
1488 ** configuration verb - an integer code that indicates what
1489 ** aspect of the [database connection] is being configured.
1490 ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1491 ** New verbs are likely to be added in future releases of SQLite.
1492 ** Additional arguments depend on the verb.
1493 **
1494 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1495 ** the call is considered successful.
1496 */
1497 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
1498
1499 /*
1500 ** CAPI3REF: Memory Allocation Routines
1501 ** EXPERIMENTAL
1502 **
1503 ** An instance of this object defines the interface between SQLite
1504 ** and low-level memory allocation routines.
1505 **
1506 ** This object is used in only one place in the SQLite interface.
1507 ** A pointer to an instance of this object is the argument to
1508 ** [sqlite3_config()] when the configuration option is
1509 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
1510 ** By creating an instance of this object
1511 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1512 ** during configuration, an application can specify an alternative
1513 ** memory allocation subsystem for SQLite to use for all of its
1514 ** dynamic memory needs.
1515 **
1516 ** Note that SQLite comes with several [built-in memory allocators]
1517 ** that are perfectly adequate for the overwhelming majority of applications
1518 ** and that this object is only useful to a tiny minority of applications
1519 ** with specialized memory allocation requirements.  This object is
1520 ** also used during testing of SQLite in order to specify an alternative
1521 ** memory allocator that simulates memory out-of-memory conditions in
1522 ** order to verify that SQLite recovers gracefully from such
1523 ** conditions.
1524 **
1525 ** The xMalloc and xFree methods must work like the
1526 ** malloc() and free() functions from the standard C library.
1527 ** The xRealloc method must work like realloc() from the standard C library
1528 ** with the exception that if the second argument to xRealloc is zero,
1529 ** xRealloc must be a no-op - it must not perform any allocation or
1530 ** deallocation.  ^SQLite guarantees that the second argument to
1531 ** xRealloc is always a value returned by a prior call to xRoundup.
1532 ** And so in cases where xRoundup always returns a positive number,
1533 ** xRealloc can perform exactly as the standard library realloc() and
1534 ** still be in compliance with this specification.
1535 **
1536 ** xSize should return the allocated size of a memory allocation
1537 ** previously obtained from xMalloc or xRealloc.  The allocated size
1538 ** is always at least as big as the requested size but may be larger.
1539 **
1540 ** The xRoundup method returns what would be the allocated size of
1541 ** a memory allocation given a particular requested size.  Most memory
1542 ** allocators round up memory allocations at least to the next multiple
1543 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1544 ** Every memory allocation request coming in through [sqlite3_malloc()]
1545 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1546 ** that causes the corresponding memory allocation to fail.
1547 **
1548 ** The xInit method initializes the memory allocator.  (For example,
1549 ** it might allocate any require mutexes or initialize internal data
1550 ** structures.  The xShutdown method is invoked (indirectly) by
1551 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1552 ** by xInit.  The pAppData pointer is used as the only parameter to
1553 ** xInit and xShutdown.
1554 **
1555 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1556 ** the xInit method, so the xInit method need not be threadsafe.  The
1557 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1558 ** not need to be threadsafe either.  For all other methods, SQLite
1559 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1560 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1561 ** it is by default) and so the methods are automatically serialized.
1562 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1563 ** methods must be threadsafe or else make their own arrangements for
1564 ** serialization.
1565 **
1566 ** SQLite will never invoke xInit() more than once without an intervening
1567 ** call to xShutdown().
1568 */
1569 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1570 struct sqlite3_mem_methods {
1571   void *(*xMalloc)(int);         /* Memory allocation function */
1572   void (*xFree)(void*);          /* Free a prior allocation */
1573   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1574   int (*xSize)(void*);           /* Return the size of an allocation */
1575   int (*xRoundup)(int);          /* Round up request size to allocation size */
1576   int (*xInit)(void*);           /* Initialize the memory allocator */
1577   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1578   void *pAppData;                /* Argument to xInit() and xShutdown() */
1579 };
1580
1581 /*
1582 ** CAPI3REF: Configuration Options
1583 ** EXPERIMENTAL
1584 **
1585 ** These constants are the available integer configuration options that
1586 ** can be passed as the first argument to the [sqlite3_config()] interface.
1587 **
1588 ** New configuration options may be added in future releases of SQLite.
1589 ** Existing configuration options might be discontinued.  Applications
1590 ** should check the return code from [sqlite3_config()] to make sure that
1591 ** the call worked.  The [sqlite3_config()] interface will return a
1592 ** non-zero [error code] if a discontinued or unsupported configuration option
1593 ** is invoked.
1594 **
1595 ** <dl>
1596 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1597 ** <dd>There are no arguments to this option.  ^This option sets the
1598 ** [threading mode] to Single-thread.  In other words, it disables
1599 ** all mutexing and puts SQLite into a mode where it can only be used
1600 ** by a single thread.   ^If SQLite is compiled with
1601 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1602 ** it is not possible to change the [threading mode] from its default
1603 ** value of Single-thread and so [sqlite3_config()] will return 
1604 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1605 ** configuration option.</dd>
1606 **
1607 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1608 ** <dd>There are no arguments to this option.  ^This option sets the
1609 ** [threading mode] to Multi-thread.  In other words, it disables
1610 ** mutexing on [database connection] and [prepared statement] objects.
1611 ** The application is responsible for serializing access to
1612 ** [database connections] and [prepared statements].  But other mutexes
1613 ** are enabled so that SQLite will be safe to use in a multi-threaded
1614 ** environment as long as no two threads attempt to use the same
1615 ** [database connection] at the same time.  ^If SQLite is compiled with
1616 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1617 ** it is not possible to set the Multi-thread [threading mode] and
1618 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1619 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1620 **
1621 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1622 ** <dd>There are no arguments to this option.  ^This option sets the
1623 ** [threading mode] to Serialized. In other words, this option enables
1624 ** all mutexes including the recursive
1625 ** mutexes on [database connection] and [prepared statement] objects.
1626 ** In this mode (which is the default when SQLite is compiled with
1627 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1628 ** to [database connections] and [prepared statements] so that the
1629 ** application is free to use the same [database connection] or the
1630 ** same [prepared statement] in different threads at the same time.
1631 ** ^If SQLite is compiled with
1632 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1633 ** it is not possible to set the Serialized [threading mode] and
1634 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1635 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1636 **
1637 ** <dt>SQLITE_CONFIG_MALLOC</dt>
1638 ** <dd> ^(This option takes a single argument which is a pointer to an
1639 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1640 ** alternative low-level memory allocation routines to be used in place of
1641 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1642 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1643 ** before the [sqlite3_config()] call returns.</dd>
1644 **
1645 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1646 ** <dd> ^(This option takes a single argument which is a pointer to an
1647 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1648 ** structure is filled with the currently defined memory allocation routines.)^
1649 ** This option can be used to overload the default memory allocation
1650 ** routines with a wrapper that simulations memory allocation failure or
1651 ** tracks memory usage, for example. </dd>
1652 **
1653 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1654 ** <dd> ^This option takes single argument of type int, interpreted as a 
1655 ** boolean, which enables or disables the collection of memory allocation 
1656 ** statistics. ^(When memory allocation statistics are disabled, the 
1657 ** following SQLite interfaces become non-operational:
1658 **   <ul>
1659 **   <li> [sqlite3_memory_used()]
1660 **   <li> [sqlite3_memory_highwater()]
1661 **   <li> [sqlite3_soft_heap_limit()]
1662 **   <li> [sqlite3_status()]
1663 **   </ul>)^
1664 ** ^Memory allocation statistics are enabled by default unless SQLite is
1665 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1666 ** allocation statistics are disabled by default.
1667 ** </dd>
1668 **
1669 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
1670 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1671 ** scratch memory.  There are three arguments:  A pointer an 8-byte
1672 ** aligned memory buffer from which the scrach allocations will be
1673 ** drawn, the size of each scratch allocation (sz),
1674 ** and the maximum number of scratch allocations (N).  The sz
1675 ** argument must be a multiple of 16. The sz parameter should be a few bytes
1676 ** larger than the actual scratch space required due to internal overhead.
1677 ** The first argument must be a pointer to an 8-byte aligned buffer
1678 ** of at least sz*N bytes of memory.
1679 ** ^SQLite will use no more than one scratch buffer per thread.  So
1680 ** N should be set to the expected maximum number of threads.  ^SQLite will
1681 ** never require a scratch buffer that is more than 6 times the database
1682 ** page size. ^If SQLite needs needs additional scratch memory beyond 
1683 ** what is provided by this configuration option, then 
1684 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1685 **
1686 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1687 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1688 ** the database page cache with the default page cache implemenation.  
1689 ** This configuration should not be used if an application-define page
1690 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1691 ** There are three arguments to this option: A pointer to 8-byte aligned
1692 ** memory, the size of each page buffer (sz), and the number of pages (N).
1693 ** The sz argument should be the size of the largest database page
1694 ** (a power of two between 512 and 32768) plus a little extra for each
1695 ** page header.  ^The page header size is 20 to 40 bytes depending on
1696 ** the host architecture.  ^It is harmless, apart from the wasted memory,
1697 ** to make sz a little too large.  The first
1698 ** argument should point to an allocation of at least sz*N bytes of memory.
1699 ** ^SQLite will use the memory provided by the first argument to satisfy its
1700 ** memory needs for the first N pages that it adds to cache.  ^If additional
1701 ** page cache memory is needed beyond what is provided by this option, then
1702 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1703 ** ^The implementation might use one or more of the N buffers to hold 
1704 ** memory accounting information. The pointer in the first argument must
1705 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1706 ** will be undefined.</dd>
1707 **
1708 ** <dt>SQLITE_CONFIG_HEAP</dt>
1709 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1710 ** for all of its dynamic memory allocation needs beyond those provided
1711 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1712 ** There are three arguments: An 8-byte aligned pointer to the memory,
1713 ** the number of bytes in the memory buffer, and the minimum allocation size.
1714 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1715 ** to using its default memory allocator (the system malloc() implementation),
1716 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1717 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1718 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1719 ** allocator is engaged to handle all of SQLites memory allocation needs.
1720 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1721 ** boundary or subsequent behavior of SQLite will be undefined.</dd>
1722 **
1723 ** <dt>SQLITE_CONFIG_MUTEX</dt>
1724 ** <dd> ^(This option takes a single argument which is a pointer to an
1725 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1726 ** alternative low-level mutex routines to be used in place
1727 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1728 ** content of the [sqlite3_mutex_methods] structure before the call to
1729 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1730 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1731 ** the entire mutexing subsystem is omitted from the build and hence calls to
1732 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1733 ** return [SQLITE_ERROR].</dd>
1734 **
1735 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1736 ** <dd> ^(This option takes a single argument which is a pointer to an
1737 ** instance of the [sqlite3_mutex_methods] structure.  The
1738 ** [sqlite3_mutex_methods]
1739 ** structure is filled with the currently defined mutex routines.)^
1740 ** This option can be used to overload the default mutex allocation
1741 ** routines with a wrapper used to track mutex usage for performance
1742 ** profiling or testing, for example.   ^If SQLite is compiled with
1743 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1744 ** the entire mutexing subsystem is omitted from the build and hence calls to
1745 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1746 ** return [SQLITE_ERROR].</dd>
1747 **
1748 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1749 ** <dd> ^(This option takes two arguments that determine the default
1750 ** memory allocation for the lookaside memory allocator on each
1751 ** [database connection].  The first argument is the
1752 ** size of each lookaside buffer slot and the second is the number of
1753 ** slots allocated to each database connection.)^  ^(This option sets the
1754 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1755 ** verb to [sqlite3_db_config()] can be used to change the lookaside
1756 ** configuration on individual connections.)^ </dd>
1757 **
1758 ** <dt>SQLITE_CONFIG_PCACHE</dt>
1759 ** <dd> ^(This option takes a single argument which is a pointer to
1760 ** an [sqlite3_pcache_methods] object.  This object specifies the interface
1761 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1762 ** object and uses it for page cache memory allocations.</dd>
1763 **
1764 ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1765 ** <dd> ^(This option takes a single argument which is a pointer to an
1766 ** [sqlite3_pcache_methods] object.  SQLite copies of the current
1767 ** page cache implementation into that object.)^ </dd>
1768 **
1769 ** </dl>
1770 */
1771 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1772 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1773 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1774 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1775 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1776 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1777 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1778 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1779 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1780 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1781 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1782 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
1783 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1784 #define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1785 #define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1786
1787 /*
1788 ** CAPI3REF: Configuration Options
1789 ** EXPERIMENTAL
1790 **
1791 ** These constants are the available integer configuration options that
1792 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1793 **
1794 ** New configuration options may be added in future releases of SQLite.
1795 ** Existing configuration options might be discontinued.  Applications
1796 ** should check the return code from [sqlite3_db_config()] to make sure that
1797 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
1798 ** non-zero [error code] if a discontinued or unsupported configuration option
1799 ** is invoked.
1800 **
1801 ** <dl>
1802 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1803 ** <dd> ^This option takes three additional arguments that determine the 
1804 ** [lookaside memory allocator] configuration for the [database connection].
1805 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
1806 ** pointer to an memory buffer to use for lookaside memory.
1807 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
1808 ** may be NULL in which case SQLite will allocate the
1809 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
1810 ** size of each lookaside buffer slot.  ^The third argument is the number of
1811 ** slots.  The size of the buffer in the first argument must be greater than
1812 ** or equal to the product of the second and third arguments.  The buffer
1813 ** must be aligned to an 8-byte boundary.  ^If the second argument to
1814 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1815 ** rounded down to the next smaller
1816 ** multiple of 8.  See also: [SQLITE_CONFIG_LOOKASIDE]</dd>
1817 **
1818 ** </dl>
1819 */
1820 #define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
1821
1822
1823 /*
1824 ** CAPI3REF: Enable Or Disable Extended Result Codes
1825 **
1826 ** ^The sqlite3_extended_result_codes() routine enables or disables the
1827 ** [extended result codes] feature of SQLite. ^The extended result
1828 ** codes are disabled by default for historical compatibility.
1829 */
1830 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1831
1832 /*
1833 ** CAPI3REF: Last Insert Rowid
1834 **
1835 ** ^Each entry in an SQLite table has a unique 64-bit signed
1836 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
1837 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1838 ** names are not also used by explicitly declared columns. ^If
1839 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
1840 ** is another alias for the rowid.
1841 **
1842 ** ^This routine returns the [rowid] of the most recent
1843 ** successful [INSERT] into the database from the [database connection]
1844 ** in the first argument.  ^If no successful [INSERT]s
1845 ** have ever occurred on that database connection, zero is returned.
1846 **
1847 ** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
1848 ** row is returned by this routine as long as the trigger is running.
1849 ** But once the trigger terminates, the value returned by this routine
1850 ** reverts to the last value inserted before the trigger fired.)^
1851 **
1852 ** ^An [INSERT] that fails due to a constraint violation is not a
1853 ** successful [INSERT] and does not change the value returned by this
1854 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1855 ** and INSERT OR ABORT make no changes to the return value of this
1856 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
1857 ** encounters a constraint violation, it does not fail.  The
1858 ** INSERT continues to completion after deleting rows that caused
1859 ** the constraint problem so INSERT OR REPLACE will always change
1860 ** the return value of this interface.)^
1861 **
1862 ** ^For the purposes of this routine, an [INSERT] is considered to
1863 ** be successful even if it is subsequently rolled back.
1864 **
1865 ** This function is accessible to SQL statements via the
1866 ** [last_insert_rowid() SQL function].
1867 **
1868 ** If a separate thread performs a new [INSERT] on the same
1869 ** database connection while the [sqlite3_last_insert_rowid()]
1870 ** function is running and thus changes the last insert [rowid],
1871 ** then the value returned by [sqlite3_last_insert_rowid()] is
1872 ** unpredictable and might not equal either the old or the new
1873 ** last insert [rowid].
1874 */
1875 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1876
1877 /*
1878 ** CAPI3REF: Count The Number Of Rows Modified
1879 **
1880 ** ^This function returns the number of database rows that were changed
1881 ** or inserted or deleted by the most recently completed SQL statement
1882 ** on the [database connection] specified by the first parameter.
1883 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
1884 ** or [DELETE] statement are counted.  Auxiliary changes caused by
1885 ** triggers or [foreign key actions] are not counted.)^ Use the
1886 ** [sqlite3_total_changes()] function to find the total number of changes
1887 ** including changes caused by triggers and foreign key actions.
1888 **
1889 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
1890 ** are not counted.  Only real table changes are counted.
1891 **
1892 ** ^(A "row change" is a change to a single row of a single table
1893 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
1894 ** are changed as side effects of [REPLACE] constraint resolution,
1895 ** rollback, ABORT processing, [DROP TABLE], or by any other
1896 ** mechanisms do not count as direct row changes.)^
1897 **
1898 ** A "trigger context" is a scope of execution that begins and
1899 ** ends with the script of a [CREATE TRIGGER | trigger]. 
1900 ** Most SQL statements are
1901 ** evaluated outside of any trigger.  This is the "top level"
1902 ** trigger context.  If a trigger fires from the top level, a
1903 ** new trigger context is entered for the duration of that one
1904 ** trigger.  Subtriggers create subcontexts for their duration.
1905 **
1906 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
1907 ** not create a new trigger context.
1908 **
1909 ** ^This function returns the number of direct row changes in the
1910 ** most recent INSERT, UPDATE, or DELETE statement within the same
1911 ** trigger context.
1912 **
1913 ** ^Thus, when called from the top level, this function returns the
1914 ** number of changes in the most recent INSERT, UPDATE, or DELETE
1915 ** that also occurred at the top level.  ^(Within the body of a trigger,
1916 ** the sqlite3_changes() interface can be called to find the number of
1917 ** changes in the most recently completed INSERT, UPDATE, or DELETE
1918 ** statement within the body of the same trigger.
1919 ** However, the number returned does not include changes
1920 ** caused by subtriggers since those have their own context.)^
1921 **
1922 ** See also the [sqlite3_total_changes()] interface, the
1923 ** [count_changes pragma], and the [changes() SQL function].
1924 **
1925 ** If a separate thread makes changes on the same database connection
1926 ** while [sqlite3_changes()] is running then the value returned
1927 ** is unpredictable and not meaningful.
1928 */
1929 SQLITE_API int sqlite3_changes(sqlite3*);
1930
1931 /*
1932 ** CAPI3REF: Total Number Of Rows Modified
1933 **
1934 ** ^This function returns the number of row changes caused by [INSERT],
1935 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
1936 ** ^(The count returned by sqlite3_total_changes() includes all changes
1937 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
1938 ** [foreign key actions]. However,
1939 ** the count does not include changes used to implement [REPLACE] constraints,
1940 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
1941 ** count does not include rows of views that fire an [INSTEAD OF trigger],
1942 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
1943 ** are counted.)^
1944 ** ^The sqlite3_total_changes() function counts the changes as soon as
1945 ** the statement that makes them is completed (when the statement handle
1946 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
1947 **
1948 ** See also the [sqlite3_changes()] interface, the
1949 ** [count_changes pragma], and the [total_changes() SQL function].
1950 **
1951 ** If a separate thread makes changes on the same database connection
1952 ** while [sqlite3_total_changes()] is running then the value
1953 ** returned is unpredictable and not meaningful.
1954 */
1955 SQLITE_API int sqlite3_total_changes(sqlite3*);
1956
1957 /*
1958 ** CAPI3REF: Interrupt A Long-Running Query
1959 **
1960 ** ^This function causes any pending database operation to abort and
1961 ** return at its earliest opportunity. This routine is typically
1962 ** called in response to a user action such as pressing "Cancel"
1963 ** or Ctrl-C where the user wants a long query operation to halt
1964 ** immediately.
1965 **
1966 ** ^It is safe to call this routine from a thread different from the
1967 ** thread that is currently running the database operation.  But it
1968 ** is not safe to call this routine with a [database connection] that
1969 ** is closed or might close before sqlite3_interrupt() returns.
1970 **
1971 ** ^If an SQL operation is very nearly finished at the time when
1972 ** sqlite3_interrupt() is called, then it might not have an opportunity
1973 ** to be interrupted and might continue to completion.
1974 **
1975 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
1976 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
1977 ** that is inside an explicit transaction, then the entire transaction
1978 ** will be rolled back automatically.
1979 **
1980 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
1981 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
1982 ** that are started after the sqlite3_interrupt() call and before the 
1983 ** running statements reaches zero are interrupted as if they had been
1984 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
1985 ** that are started after the running statement count reaches zero are
1986 ** not effected by the sqlite3_interrupt().
1987 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
1988 ** SQL statements is a no-op and has no effect on SQL statements
1989 ** that are started after the sqlite3_interrupt() call returns.
1990 **
1991 ** If the database connection closes while [sqlite3_interrupt()]
1992 ** is running then bad things will likely happen.
1993 */
1994 SQLITE_API void sqlite3_interrupt(sqlite3*);
1995
1996 /*
1997 ** CAPI3REF: Determine If An SQL Statement Is Complete
1998 **
1999 ** These routines are useful during command-line input to determine if the
2000 ** currently entered text seems to form a complete SQL statement or
2001 ** if additional input is needed before sending the text into
2002 ** SQLite for parsing.  ^These routines return 1 if the input string
2003 ** appears to be a complete SQL statement.  ^A statement is judged to be
2004 ** complete if it ends with a semicolon token and is not a prefix of a
2005 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2006 ** string literals or quoted identifier names or comments are not
2007 ** independent tokens (they are part of the token in which they are
2008 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2009 ** and comments that follow the final semicolon are ignored.
2010 **
2011 ** ^These routines return 0 if the statement is incomplete.  ^If a
2012 ** memory allocation fails, then SQLITE_NOMEM is returned.
2013 **
2014 ** ^These routines do not parse the SQL statements thus
2015 ** will not detect syntactically incorrect SQL.
2016 **
2017 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
2018 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2019 ** automatically by sqlite3_complete16().  If that initialization fails,
2020 ** then the return value from sqlite3_complete16() will be non-zero
2021 ** regardless of whether or not the input SQL is complete.)^
2022 **
2023 ** The input to [sqlite3_complete()] must be a zero-terminated
2024 ** UTF-8 string.
2025 **
2026 ** The input to [sqlite3_complete16()] must be a zero-terminated
2027 ** UTF-16 string in native byte order.
2028 */
2029 SQLITE_API int sqlite3_complete(const char *sql);
2030 SQLITE_API int sqlite3_complete16(const void *sql);
2031
2032 /*
2033 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2034 **
2035 ** ^This routine sets a callback function that might be invoked whenever
2036 ** an attempt is made to open a database table that another thread
2037 ** or process has locked.
2038 **
2039 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2040 ** is returned immediately upon encountering the lock.  ^If the busy callback
2041 ** is not NULL, then the callback might be invoked with two arguments.
2042 **
2043 ** ^The first argument to the busy handler is a copy of the void* pointer which
2044 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2045 ** the busy handler callback is the number of times that the busy handler has
2046 ** been invoked for this locking event.  ^If the
2047 ** busy callback returns 0, then no additional attempts are made to
2048 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2049 ** ^If the callback returns non-zero, then another attempt
2050 ** is made to open the database for reading and the cycle repeats.
2051 **
2052 ** The presence of a busy handler does not guarantee that it will be invoked
2053 ** when there is lock contention. ^If SQLite determines that invoking the busy
2054 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2055 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2056 ** Consider a scenario where one process is holding a read lock that
2057 ** it is trying to promote to a reserved lock and
2058 ** a second process is holding a reserved lock that it is trying
2059 ** to promote to an exclusive lock.  The first process cannot proceed
2060 ** because it is blocked by the second and the second process cannot
2061 ** proceed because it is blocked by the first.  If both processes
2062 ** invoke the busy handlers, neither will make any progress.  Therefore,
2063 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2064 ** will induce the first process to release its read lock and allow
2065 ** the second process to proceed.
2066 **
2067 ** ^The default busy callback is NULL.
2068 **
2069 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2070 ** when SQLite is in the middle of a large transaction where all the
2071 ** changes will not fit into the in-memory cache.  SQLite will
2072 ** already hold a RESERVED lock on the database file, but it needs
2073 ** to promote this lock to EXCLUSIVE so that it can spill cache
2074 ** pages into the database file without harm to concurrent
2075 ** readers.  ^If it is unable to promote the lock, then the in-memory
2076 ** cache will be left in an inconsistent state and so the error
2077 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2078 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2079 ** forces an automatic rollback of the changes.  See the
2080 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2081 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2082 ** this is important.
2083 **
2084 ** ^(There can only be a single busy handler defined for each
2085 ** [database connection].  Setting a new busy handler clears any
2086 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2087 ** will also set or clear the busy handler.
2088 **
2089 ** The busy callback should not take any actions which modify the
2090 ** database connection that invoked the busy handler.  Any such actions
2091 ** result in undefined behavior.
2092 ** 
2093 ** A busy handler must not close the database connection
2094 ** or [prepared statement] that invoked the busy handler.
2095 */
2096 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2097
2098 /*
2099 ** CAPI3REF: Set A Busy Timeout
2100 **
2101 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2102 ** for a specified amount of time when a table is locked.  ^The handler
2103 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2104 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2105 ** the handler returns 0 which causes [sqlite3_step()] to return
2106 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2107 **
2108 ** ^Calling this routine with an argument less than or equal to zero
2109 ** turns off all busy handlers.
2110 **
2111 ** ^(There can only be a single busy handler for a particular
2112 ** [database connection] any any given moment.  If another busy handler
2113 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2114 ** this routine, that other busy handler is cleared.)^
2115 */
2116 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2117
2118 /*
2119 ** CAPI3REF: Convenience Routines For Running Queries
2120 **
2121 ** Definition: A <b>result table</b> is memory data structure created by the
2122 ** [sqlite3_get_table()] interface.  A result table records the
2123 ** complete query results from one or more queries.
2124 **
2125 ** The table conceptually has a number of rows and columns.  But
2126 ** these numbers are not part of the result table itself.  These
2127 ** numbers are obtained separately.  Let N be the number of rows
2128 ** and M be the number of columns.
2129 **
2130 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2131 ** There are (N+1)*M elements in the array.  The first M pointers point
2132 ** to zero-terminated strings that  contain the names of the columns.
2133 ** The remaining entries all point to query results.  NULL values result
2134 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2135 ** string representation as returned by [sqlite3_column_text()].
2136 **
2137 ** A result table might consist of one or more memory allocations.
2138 ** It is not safe to pass a result table directly to [sqlite3_free()].
2139 ** A result table should be deallocated using [sqlite3_free_table()].
2140 **
2141 ** As an example of the result table format, suppose a query result
2142 ** is as follows:
2143 **
2144 ** <blockquote><pre>
2145 **        Name        | Age
2146 **        -----------------------
2147 **        Alice       | 43
2148 **        Bob         | 28
2149 **        Cindy       | 21
2150 ** </pre></blockquote>
2151 **
2152 ** There are two column (M==2) and three rows (N==3).  Thus the
2153 ** result table has 8 entries.  Suppose the result table is stored
2154 ** in an array names azResult.  Then azResult holds this content:
2155 **
2156 ** <blockquote><pre>
2157 **        azResult&#91;0] = "Name";
2158 **        azResult&#91;1] = "Age";
2159 **        azResult&#91;2] = "Alice";
2160 **        azResult&#91;3] = "43";
2161 **        azResult&#91;4] = "Bob";
2162 **        azResult&#91;5] = "28";
2163 **        azResult&#91;6] = "Cindy";
2164 **        azResult&#91;7] = "21";
2165 ** </pre></blockquote>
2166 **
2167 ** ^The sqlite3_get_table() function evaluates one or more
2168 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2169 ** string of its 2nd parameter and returns a result table to the
2170 ** pointer given in its 3rd parameter.
2171 **
2172 ** After the application has finished with the result from sqlite3_get_table(),
2173 ** it should pass the result table pointer to sqlite3_free_table() in order to
2174 ** release the memory that was malloced.  Because of the way the
2175 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2176 ** function must not try to call [sqlite3_free()] directly.  Only
2177 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2178 **
2179 ** ^(The sqlite3_get_table() interface is implemented as a wrapper around
2180 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2181 ** to any internal data structures of SQLite.  It uses only the public
2182 ** interface defined here.  As a consequence, errors that occur in the
2183 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2184 ** reflected in subsequent calls to [sqlite3_errcode()] or
2185 ** [sqlite3_errmsg()].)^
2186 */
2187 SQLITE_API int sqlite3_get_table(
2188   sqlite3 *db,          /* An open database */
2189   const char *zSql,     /* SQL to be evaluated */
2190   char ***pazResult,    /* Results of the query */
2191   int *pnRow,           /* Number of result rows written here */
2192   int *pnColumn,        /* Number of result columns written here */
2193   char **pzErrmsg       /* Error msg written here */
2194 );
2195 SQLITE_API void sqlite3_free_table(char **result);
2196
2197 /*
2198 ** CAPI3REF: Formatted String Printing Functions
2199 **
2200 ** These routines are work-alikes of the "printf()" family of functions
2201 ** from the standard C library.
2202 **
2203 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2204 ** results into memory obtained from [sqlite3_malloc()].
2205 ** The strings returned by these two routines should be
2206 ** released by [sqlite3_free()].  ^Both routines return a
2207 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2208 ** memory to hold the resulting string.
2209 **
2210 ** ^(In sqlite3_snprintf() routine is similar to "snprintf()" from
2211 ** the standard C library.  The result is written into the
2212 ** buffer supplied as the second parameter whose size is given by
2213 ** the first parameter. Note that the order of the
2214 ** first two parameters is reversed from snprintf().)^  This is an
2215 ** historical accident that cannot be fixed without breaking
2216 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2217 ** returns a pointer to its buffer instead of the number of
2218 ** characters actually written into the buffer.)^  We admit that
2219 ** the number of characters written would be a more useful return
2220 ** value but we cannot change the implementation of sqlite3_snprintf()
2221 ** now without breaking compatibility.
2222 **
2223 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2224 ** guarantees that the buffer is always zero-terminated.  ^The first
2225 ** parameter "n" is the total size of the buffer, including space for
2226 ** the zero terminator.  So the longest string that can be completely
2227 ** written will be n-1 characters.
2228 **
2229 ** These routines all implement some additional formatting
2230 ** options that are useful for constructing SQL statements.
2231 ** All of the usual printf() formatting options apply.  In addition, there
2232 ** is are "%q", "%Q", and "%z" options.
2233 **
2234 ** ^(The %q option works like %s in that it substitutes a null-terminated
2235 ** string from the argument list.  But %q also doubles every '\'' character.
2236 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2237 ** character it escapes that character and allows it to be inserted into
2238 ** the string.
2239 **
2240 ** For example, assume the string variable zText contains text as follows:
2241 **
2242 ** <blockquote><pre>
2243 **  char *zText = "It's a happy day!";
2244 ** </pre></blockquote>
2245 **
2246 ** One can use this text in an SQL statement as follows:
2247 **
2248 ** <blockquote><pre>
2249 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2250 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2251 **  sqlite3_free(zSQL);
2252 ** </pre></blockquote>
2253 **
2254 ** Because the %q format string is used, the '\'' character in zText
2255 ** is escaped and the SQL generated is as follows:
2256 **
2257 ** <blockquote><pre>
2258 **  INSERT INTO table1 VALUES('It''s a happy day!')
2259 ** </pre></blockquote>
2260 **
2261 ** This is correct.  Had we used %s instead of %q, the generated SQL
2262 ** would have looked like this:
2263 **
2264 ** <blockquote><pre>
2265 **  INSERT INTO table1 VALUES('It's a happy day!');
2266 ** </pre></blockquote>
2267 **
2268 ** This second example is an SQL syntax error.  As a general rule you should
2269 ** always use %q instead of %s when inserting text into a string literal.
2270 **
2271 ** ^(The %Q option works like %q except it also adds single quotes around
2272 ** the outside of the total string.  Additionally, if the parameter in the
2273 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2274 ** single quotes).)^  So, for example, one could say:
2275 **
2276 ** <blockquote><pre>
2277 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2278 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2279 **  sqlite3_free(zSQL);
2280 ** </pre></blockquote>
2281 **
2282 ** The code above will render a correct SQL statement in the zSQL
2283 ** variable even if the zText variable is a NULL pointer.
2284 **
2285 ** ^(The "%z" formatting option works like "%s" but with the
2286 ** addition that after the string has been read and copied into
2287 ** the result, [sqlite3_free()] is called on the input string.)^
2288 */
2289 SQLITE_API char *sqlite3_mprintf(const char*,...);
2290 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2291 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2292
2293 /*
2294 ** CAPI3REF: Memory Allocation Subsystem
2295 **
2296 ** The SQLite core uses these three routines for all of its own
2297 ** internal memory allocation needs. "Core" in the previous sentence
2298 ** does not include operating-system specific VFS implementation.  The
2299 ** Windows VFS uses native malloc() and free() for some operations.
2300 **
2301 ** ^The sqlite3_malloc() routine returns a pointer to a block
2302 ** of memory at least N bytes in length, where N is the parameter.
2303 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2304 ** memory, it returns a NULL pointer.  ^If the parameter N to
2305 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2306 ** a NULL pointer.
2307 **
2308 ** ^Calling sqlite3_free() with a pointer previously returned
2309 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2310 ** that it might be reused.  ^The sqlite3_free() routine is
2311 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2312 ** to sqlite3_free() is harmless.  After being freed, memory
2313 ** should neither be read nor written.  Even reading previously freed
2314 ** memory might result in a segmentation fault or other severe error.
2315 ** Memory corruption, a segmentation fault, or other severe error
2316 ** might result if sqlite3_free() is called with a non-NULL pointer that
2317 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2318 **
2319 ** ^(The sqlite3_realloc() interface attempts to resize a
2320 ** prior memory allocation to be at least N bytes, where N is the
2321 ** second parameter.  The memory allocation to be resized is the first
2322 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2323 ** is a NULL pointer then its behavior is identical to calling
2324 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2325 ** ^If the second parameter to sqlite3_realloc() is zero or
2326 ** negative then the behavior is exactly the same as calling
2327 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2328 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2329 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2330 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2331 ** of the prior allocation are copied into the beginning of buffer returned
2332 ** by sqlite3_realloc() and the prior allocation is freed.
2333 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2334 ** is not freed.
2335 **
2336 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2337 ** is always aligned to at least an 8 byte boundary.
2338 **
2339 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2340 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2341 ** implementation of these routines to be omitted.  That capability
2342 ** is no longer provided.  Only built-in memory allocators can be used.
2343 **
2344 ** The Windows OS interface layer calls
2345 ** the system malloc() and free() directly when converting
2346 ** filenames between the UTF-8 encoding used by SQLite
2347 ** and whatever filename encoding is used by the particular Windows
2348 ** installation.  Memory allocation errors are detected, but
2349 ** they are reported back as [SQLITE_CANTOPEN] or
2350 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2351 **
2352 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2353 ** must be either NULL or else pointers obtained from a prior
2354 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2355 ** not yet been released.
2356 **
2357 ** The application must not read or write any part of
2358 ** a block of memory after it has been released using
2359 ** [sqlite3_free()] or [sqlite3_realloc()].
2360 */
2361 SQLITE_API void *sqlite3_malloc(int);
2362 SQLITE_API void *sqlite3_realloc(void*, int);
2363 SQLITE_API void sqlite3_free(void*);
2364
2365 /*
2366 ** CAPI3REF: Memory Allocator Statistics
2367 **
2368 ** SQLite provides these two interfaces for reporting on the status
2369 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2370 ** routines, which form the built-in memory allocation subsystem.
2371 **
2372 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2373 ** of memory currently outstanding (malloced but not freed).
2374 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2375 ** value of [sqlite3_memory_used()] since the high-water mark
2376 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2377 ** [sqlite3_memory_highwater()] include any overhead
2378 ** added by SQLite in its implementation of [sqlite3_malloc()],
2379 ** but not overhead added by the any underlying system library
2380 ** routines that [sqlite3_malloc()] may call.
2381 **
2382 ** ^The memory high-water mark is reset to the current value of
2383 ** [sqlite3_memory_used()] if and only if the parameter to
2384 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2385 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2386 ** prior to the reset.
2387 */
2388 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2389 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2390
2391 /*
2392 ** CAPI3REF: Pseudo-Random Number Generator
2393 **
2394 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2395 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2396 ** already uses the largest possible [ROWID].  The PRNG is also used for
2397 ** the build-in random() and randomblob() SQL functions.  This interface allows
2398 ** applications to access the same PRNG for other purposes.
2399 **
2400 ** ^A call to this routine stores N bytes of randomness into buffer P.
2401 **
2402 ** ^The first time this routine is invoked (either internally or by
2403 ** the application) the PRNG is seeded using randomness obtained
2404 ** from the xRandomness method of the default [sqlite3_vfs] object.
2405 ** ^On all subsequent invocations, the pseudo-randomness is generated
2406 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2407 ** method.
2408 */
2409 SQLITE_API void sqlite3_randomness(int N, void *P);
2410
2411 /*
2412 ** CAPI3REF: Compile-Time Authorization Callbacks
2413 **
2414 ** ^This routine registers a authorizer callback with a particular
2415 ** [database connection], supplied in the first argument.
2416 ** ^The authorizer callback is invoked as SQL statements are being compiled
2417 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2418 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2419 ** points during the compilation process, as logic is being created
2420 ** to perform various actions, the authorizer callback is invoked to
2421 ** see if those actions are allowed.  ^The authorizer callback should
2422 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2423 ** specific action but allow the SQL statement to continue to be
2424 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2425 ** rejected with an error.  ^If the authorizer callback returns
2426 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2427 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2428 ** the authorizer will fail with an error message.
2429 **
2430 ** When the callback returns [SQLITE_OK], that means the operation
2431 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2432 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2433 ** authorizer will fail with an error message explaining that
2434 ** access is denied. 
2435 **
2436 ** ^The first parameter to the authorizer callback is a copy of the third
2437 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2438 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2439 ** the particular action to be authorized. ^The third through sixth parameters
2440 ** to the callback are zero-terminated strings that contain additional
2441 ** details about the action to be authorized.
2442 **
2443 ** ^If the action code is [SQLITE_READ]
2444 ** and the callback returns [SQLITE_IGNORE] then the
2445 ** [prepared statement] statement is constructed to substitute
2446 ** a NULL value in place of the table column that would have
2447 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2448 ** return can be used to deny an untrusted user access to individual
2449 ** columns of a table.
2450 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2451 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2452 ** [truncate optimization] is disabled and all rows are deleted individually.
2453 **
2454 ** An authorizer is used when [sqlite3_prepare | preparing]
2455 ** SQL statements from an untrusted source, to ensure that the SQL statements
2456 ** do not try to access data they are not allowed to see, or that they do not
2457 ** try to execute malicious statements that damage the database.  For
2458 ** example, an application may allow a user to enter arbitrary
2459 ** SQL queries for evaluation by a database.  But the application does
2460 ** not want the user to be able to make arbitrary changes to the
2461 ** database.  An authorizer could then be put in place while the
2462 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2463 ** disallows everything except [SELECT] statements.
2464 **
2465 ** Applications that need to process SQL from untrusted sources
2466 ** might also consider lowering resource limits using [sqlite3_limit()]
2467 ** and limiting database size using the [max_page_count] [PRAGMA]
2468 ** in addition to using an authorizer.
2469 **
2470 ** ^(Only a single authorizer can be in place on a database connection
2471 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2472 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2473 ** The authorizer is disabled by default.
2474 **
2475 ** The authorizer callback must not do anything that will modify
2476 ** the database connection that invoked the authorizer callback.
2477 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2478 ** database connections for the meaning of "modify" in this paragraph.
2479 **
2480 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2481 ** statement might be re-prepared during [sqlite3_step()] due to a 
2482 ** schema change.  Hence, the application should ensure that the
2483 ** correct authorizer callback remains in place during the [sqlite3_step()].
2484 **
2485 ** ^Note that the authorizer callback is invoked only during
2486 ** [sqlite3_prepare()] or its variants.  Authorization is not
2487 ** performed during statement evaluation in [sqlite3_step()], unless
2488 ** as stated in the previous paragraph, sqlite3_step() invokes
2489 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2490 */
2491 SQLITE_API int sqlite3_set_authorizer(
2492   sqlite3*,
2493   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2494   void *pUserData
2495 );
2496
2497 /*
2498 ** CAPI3REF: Authorizer Return Codes
2499 **
2500 ** The [sqlite3_set_authorizer | authorizer callback function] must
2501 ** return either [SQLITE_OK] or one of these two constants in order
2502 ** to signal SQLite whether or not the action is permitted.  See the
2503 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2504 ** information.
2505 */
2506 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2507 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2508
2509 /*
2510 ** CAPI3REF: Authorizer Action Codes
2511 **
2512 ** The [sqlite3_set_authorizer()] interface registers a callback function
2513 ** that is invoked to authorize certain SQL statement actions.  The
2514 ** second parameter to the callback is an integer code that specifies
2515 ** what action is being authorized.  These are the integer action codes that
2516 ** the authorizer callback may be passed.
2517 **
2518 ** These action code values signify what kind of operation is to be
2519 ** authorized.  The 3rd and 4th parameters to the authorization
2520 ** callback function will be parameters or NULL depending on which of these
2521 ** codes is used as the second parameter.  ^(The 5th parameter to the
2522 ** authorizer callback is the name of the database ("main", "temp",
2523 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2524 ** is the name of the inner-most trigger or view that is responsible for
2525 ** the access attempt or NULL if this access attempt is directly from
2526 ** top-level SQL code.
2527 */
2528 /******************************************* 3rd ************ 4th ***********/
2529 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2530 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2531 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2532 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2533 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2534 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2535 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2536 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2537 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2538 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2539 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2540 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2541 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2542 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2543 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2544 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2545 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2546 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2547 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2548 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2549 #define SQLITE_SELECT               21   /* NULL            NULL            */
2550 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2551 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2552 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2553 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2554 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2555 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2556 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2557 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2558 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2559 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2560 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2561 #define SQLITE_COPY                  0   /* No longer used */
2562
2563 /*
2564 ** CAPI3REF: Tracing And Profiling Functions
2565 ** EXPERIMENTAL
2566 **
2567 ** These routines register callback functions that can be used for
2568 ** tracing and profiling the execution of SQL statements.
2569 **
2570 ** ^The callback function registered by sqlite3_trace() is invoked at
2571 ** various times when an SQL statement is being run by [sqlite3_step()].
2572 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2573 ** SQL statement text as the statement first begins executing.
2574 ** ^(Additional sqlite3_trace() callbacks might occur
2575 ** as each triggered subprogram is entered.  The callbacks for triggers
2576 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2577 **
2578 ** ^The callback function registered by sqlite3_profile() is invoked
2579 ** as each SQL statement finishes.  ^The profile callback contains
2580 ** the original statement text and an estimate of wall-clock time
2581 ** of how long that statement took to run.
2582 */
2583 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2584 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2585    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2586
2587 /*
2588 ** CAPI3REF: Query Progress Callbacks
2589 **
2590 ** ^This routine configures a callback function - the
2591 ** progress callback - that is invoked periodically during long
2592 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
2593 ** [sqlite3_get_table()].  An example use for this
2594 ** interface is to keep a GUI updated during a large query.
2595 **
2596 ** ^If the progress callback returns non-zero, the operation is
2597 ** interrupted.  This feature can be used to implement a
2598 ** "Cancel" button on a GUI progress dialog box.
2599 **
2600 ** The progress handler must not do anything that will modify
2601 ** the database connection that invoked the progress handler.
2602 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2603 ** database connections for the meaning of "modify" in this paragraph.
2604 **
2605 */
2606 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2607
2608 /*
2609 ** CAPI3REF: Opening A New Database Connection
2610 **
2611 ** ^These routines open an SQLite database file whose name is given by the
2612 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2613 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2614 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2615 ** returned in *ppDb, even if an error occurs.  The only exception is that
2616 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2617 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2618 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2619 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2620 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2621 ** an English language description of the error following a failure of any
2622 ** of the sqlite3_open() routines.
2623 **
2624 ** ^The default encoding for the database will be UTF-8 if
2625 ** sqlite3_open() or sqlite3_open_v2() is called and
2626 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2627 **
2628 ** Whether or not an error occurs when it is opened, resources
2629 ** associated with the [database connection] handle should be released by
2630 ** passing it to [sqlite3_close()] when it is no longer required.
2631 **
2632 ** The sqlite3_open_v2() interface works like sqlite3_open()
2633 ** except that it accepts two additional parameters for additional control
2634 ** over the new database connection.  ^(The flags parameter to
2635 ** sqlite3_open_v2() can take one of
2636 ** the following three values, optionally combined with the 
2637 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2638 ** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
2639 **
2640 ** <dl>
2641 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2642 ** <dd>The database is opened in read-only mode.  If the database does not
2643 ** already exist, an error is returned.</dd>)^
2644 **
2645 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2646 ** <dd>The database is opened for reading and writing if possible, or reading
2647 ** only if the file is write protected by the operating system.  In either
2648 ** case the database must already exist, otherwise an error is returned.</dd>)^
2649 **
2650 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2651 ** <dd>The database is opened for reading and writing, and is creates it if
2652 ** it does not already exist. This is the behavior that is always used for
2653 ** sqlite3_open() and sqlite3_open16().</dd>)^
2654 ** </dl>
2655 **
2656 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2657 ** combinations shown above or one of the combinations shown above combined
2658 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2659 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
2660 ** then the behavior is undefined.
2661 **
2662 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2663 ** opens in the multi-thread [threading mode] as long as the single-thread
2664 ** mode has not been set at compile-time or start-time.  ^If the
2665 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2666 ** in the serialized [threading mode] unless single-thread was
2667 ** previously selected at compile-time or start-time.
2668 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2669 ** eligible to use [shared cache mode], regardless of whether or not shared
2670 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2671 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2672 ** participate in [shared cache mode] even if it is enabled.
2673 **
2674 ** ^If the filename is ":memory:", then a private, temporary in-memory database
2675 ** is created for the connection.  ^This in-memory database will vanish when
2676 ** the database connection is closed.  Future versions of SQLite might
2677 ** make use of additional special filenames that begin with the ":" character.
2678 ** It is recommended that when a database filename actually does begin with
2679 ** a ":" character you should prefix the filename with a pathname such as
2680 ** "./" to avoid ambiguity.
2681 **
2682 ** ^If the filename is an empty string, then a private, temporary
2683 ** on-disk database will be created.  ^This private database will be
2684 ** automatically deleted as soon as the database connection is closed.
2685 **
2686 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2687 ** [sqlite3_vfs] object that defines the operating system interface that
2688 ** the new database connection should use.  ^If the fourth parameter is
2689 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2690 **
2691 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
2692 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2693 ** codepage is currently defined.  Filenames containing international
2694 ** characters must be converted to UTF-8 prior to passing them into
2695 ** sqlite3_open() or sqlite3_open_v2().
2696 */
2697 SQLITE_API int sqlite3_open(
2698   const char *filename,   /* Database filename (UTF-8) */
2699   sqlite3 **ppDb          /* OUT: SQLite db handle */
2700 );
2701 SQLITE_API int sqlite3_open16(
2702   const void *filename,   /* Database filename (UTF-16) */
2703   sqlite3 **ppDb          /* OUT: SQLite db handle */
2704 );
2705 SQLITE_API int sqlite3_open_v2(
2706   const char *filename,   /* Database filename (UTF-8) */
2707   sqlite3 **ppDb,         /* OUT: SQLite db handle */
2708   int flags,              /* Flags */
2709   const char *zVfs        /* Name of VFS module to use */
2710 );
2711
2712 /*
2713 ** CAPI3REF: Error Codes And Messages
2714 **
2715 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
2716 ** [extended result code] for the most recent failed sqlite3_* API call
2717 ** associated with a [database connection]. If a prior API call failed
2718 ** but the most recent API call succeeded, the return value from
2719 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
2720 ** interface is the same except that it always returns the 
2721 ** [extended result code] even when extended result codes are
2722 ** disabled.
2723 **
2724 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2725 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
2726 ** ^(Memory to hold the error message string is managed internally.
2727 ** The application does not need to worry about freeing the result.
2728 ** However, the error string might be overwritten or deallocated by
2729 ** subsequent calls to other SQLite interface functions.)^
2730 **
2731 ** When the serialized [threading mode] is in use, it might be the
2732 ** case that a second error occurs on a separate thread in between
2733 ** the time of the first error and the call to these interfaces.
2734 ** When that happens, the second error will be reported since these
2735 ** interfaces always report the most recent result.  To avoid
2736 ** this, each thread can obtain exclusive use of the [database connection] D
2737 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2738 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2739 ** all calls to the interfaces listed here are completed.
2740 **
2741 ** If an interface fails with SQLITE_MISUSE, that means the interface
2742 ** was invoked incorrectly by the application.  In that case, the
2743 ** error code and message may or may not be set.
2744 */
2745 SQLITE_API int sqlite3_errcode(sqlite3 *db);
2746 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
2747 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
2748 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
2749
2750 /*
2751 ** CAPI3REF: SQL Statement Object
2752 ** KEYWORDS: {prepared statement} {prepared statements}
2753 **
2754 ** An instance of this object represents a single SQL statement.
2755 ** This object is variously known as a "prepared statement" or a
2756 ** "compiled SQL statement" or simply as a "statement".
2757 **
2758 ** The life of a statement object goes something like this:
2759 **
2760 ** <ol>
2761 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
2762 **      function.
2763 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
2764 **      interfaces.
2765 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
2766 ** <li> Reset the statement using [sqlite3_reset()] then go back
2767 **      to step 2.  Do this zero or more times.
2768 ** <li> Destroy the object using [sqlite3_finalize()].
2769 ** </ol>
2770 **
2771 ** Refer to documentation on individual methods above for additional
2772 ** information.
2773 */
2774 typedef struct sqlite3_stmt sqlite3_stmt;
2775
2776 /*
2777 ** CAPI3REF: Run-time Limits
2778 **
2779 ** ^(This interface allows the size of various constructs to be limited
2780 ** on a connection by connection basis.  The first parameter is the
2781 ** [database connection] whose limit is to be set or queried.  The
2782 ** second parameter is one of the [limit categories] that define a
2783 ** class of constructs to be size limited.  The third parameter is the
2784 ** new limit for that construct.  The function returns the old limit.)^
2785 **
2786 ** ^If the new limit is a negative number, the limit is unchanged.
2787 ** ^(For the limit category of SQLITE_LIMIT_XYZ there is a 
2788 ** [limits | hard upper bound]
2789 ** set by a compile-time C preprocessor macro named 
2790 ** [limits | SQLITE_MAX_XYZ].
2791 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
2792 ** ^Attempts to increase a limit above its hard upper bound are
2793 ** silently truncated to the hard upper bound.
2794 **
2795 ** Run-time limits are intended for use in applications that manage
2796 ** both their own internal database and also databases that are controlled
2797 ** by untrusted external sources.  An example application might be a
2798 ** web browser that has its own databases for storing history and
2799 ** separate databases controlled by JavaScript applications downloaded
2800 ** off the Internet.  The internal databases can be given the
2801 ** large, default limits.  Databases managed by external sources can
2802 ** be given much smaller limits designed to prevent a denial of service
2803 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
2804 ** interface to further control untrusted SQL.  The size of the database
2805 ** created by an untrusted script can be contained using the
2806 ** [max_page_count] [PRAGMA].
2807 **
2808 ** New run-time limit categories may be added in future releases.
2809 */
2810 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
2811
2812 /*
2813 ** CAPI3REF: Run-Time Limit Categories
2814 ** KEYWORDS: {limit category} {*limit categories}
2815 **
2816 ** These constants define various performance limits
2817 ** that can be lowered at run-time using [sqlite3_limit()].
2818 ** The synopsis of the meanings of the various limits is shown below.
2819 ** Additional information is available at [limits | Limits in SQLite].
2820 **
2821 ** <dl>
2822 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
2823 ** <dd>The maximum size of any string or BLOB or table row.<dd>)^
2824 **
2825 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
2826 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
2827 **
2828 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
2829 ** <dd>The maximum number of columns in a table definition or in the
2830 ** result set of a [SELECT] or the maximum number of columns in an index
2831 ** or in an ORDER BY or GROUP BY clause.</dd>)^
2832 **
2833 ** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
2834 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
2835 **
2836 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
2837 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
2838 **
2839 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
2840 ** <dd>The maximum number of instructions in a virtual machine program
2841 ** used to implement an SQL statement.</dd>)^
2842 **
2843 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
2844 ** <dd>The maximum number of arguments on a function.</dd>)^
2845 **
2846 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
2847 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
2848 **
2849 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
2850 ** <dd>The maximum length of the pattern argument to the [LIKE] or
2851 ** [GLOB] operators.</dd>)^
2852 **
2853 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
2854 ** <dd>The maximum number of variables in an SQL statement that can
2855 ** be bound.</dd>)^
2856 **
2857 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
2858 ** <dd>The maximum depth of recursion for triggers.</dd>)^
2859 ** </dl>
2860 */
2861 #define SQLITE_LIMIT_LENGTH                    0
2862 #define SQLITE_LIMIT_SQL_LENGTH                1
2863 #define SQLITE_LIMIT_COLUMN                    2
2864 #define SQLITE_LIMIT_EXPR_DEPTH                3
2865 #define SQLITE_LIMIT_COMPOUND_SELECT           4
2866 #define SQLITE_LIMIT_VDBE_OP                   5
2867 #define SQLITE_LIMIT_FUNCTION_ARG              6
2868 #define SQLITE_LIMIT_ATTACHED                  7
2869 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
2870 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
2871 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
2872
2873 /*
2874 ** CAPI3REF: Compiling An SQL Statement
2875 ** KEYWORDS: {SQL statement compiler}
2876 **
2877 ** To execute an SQL query, it must first be compiled into a byte-code
2878 ** program using one of these routines.
2879 **
2880 ** The first argument, "db", is a [database connection] obtained from a
2881 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
2882 ** [sqlite3_open16()].  The database connection must not have been closed.
2883 **
2884 ** The second argument, "zSql", is the statement to be compiled, encoded
2885 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
2886 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
2887 ** use UTF-16.
2888 **
2889 ** ^If the nByte argument is less than zero, then zSql is read up to the
2890 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
2891 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
2892 ** zSql string ends at either the first '\000' or '\u0000' character or
2893 ** the nByte-th byte, whichever comes first. If the caller knows
2894 ** that the supplied string is nul-terminated, then there is a small
2895 ** performance advantage to be gained by passing an nByte parameter that
2896 ** is equal to the number of bytes in the input string <i>including</i>
2897 ** the nul-terminator bytes.
2898 **
2899 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
2900 ** past the end of the first SQL statement in zSql.  These routines only
2901 ** compile the first statement in zSql, so *pzTail is left pointing to
2902 ** what remains uncompiled.
2903 **
2904 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
2905 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
2906 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
2907 ** string or a comment) then *ppStmt is set to NULL.
2908 ** The calling procedure is responsible for deleting the compiled
2909 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
2910 ** ppStmt may not be NULL.
2911 **
2912 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
2913 ** otherwise an [error code] is returned.
2914 **
2915 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
2916 ** recommended for all new programs. The two older interfaces are retained
2917 ** for backwards compatibility, but their use is discouraged.
2918 ** ^In the "v2" interfaces, the prepared statement
2919 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
2920 ** original SQL text. This causes the [sqlite3_step()] interface to
2921 ** behave differently in three ways:
2922 **
2923 ** <ol>
2924 ** <li>
2925 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
2926 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
2927 ** statement and try to run it again.  ^If the schema has changed in
2928 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
2929 ** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
2930 ** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
2931 ** error go away.  Note: use [sqlite3_errmsg()] to find the text
2932 ** of the parsing error that results in an [SQLITE_SCHEMA] return.
2933 ** </li>
2934 **
2935 ** <li>
2936 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
2937 ** [error codes] or [extended error codes].  ^The legacy behavior was that
2938 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
2939 ** and the application would have to make a second call to [sqlite3_reset()]
2940 ** in order to find the underlying cause of the problem. With the "v2" prepare
2941 ** interfaces, the underlying reason for the error is returned immediately.
2942 ** </li>
2943 **
2944 ** <li>
2945 ** ^If the value of a [parameter | host parameter] in the WHERE clause might
2946 ** change the query plan for a statement, then the statement may be
2947 ** automatically recompiled (as if there had been a schema change) on the first 
2948 ** [sqlite3_step()] call following any change to the 
2949 ** [sqlite3_bind_text | bindings] of the [parameter]. 
2950 ** </li>
2951 ** </ol>
2952 */
2953 SQLITE_API int sqlite3_prepare(
2954   sqlite3 *db,            /* Database handle */
2955   const char *zSql,       /* SQL statement, UTF-8 encoded */
2956   int nByte,              /* Maximum length of zSql in bytes. */
2957   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2958   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
2959 );
2960 SQLITE_API int sqlite3_prepare_v2(
2961   sqlite3 *db,            /* Database handle */
2962   const char *zSql,       /* SQL statement, UTF-8 encoded */
2963   int nByte,              /* Maximum length of zSql in bytes. */
2964   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2965   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
2966 );
2967 SQLITE_API int sqlite3_prepare16(
2968   sqlite3 *db,            /* Database handle */
2969   const void *zSql,       /* SQL statement, UTF-16 encoded */
2970   int nByte,              /* Maximum length of zSql in bytes. */
2971   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2972   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
2973 );
2974 SQLITE_API int sqlite3_prepare16_v2(
2975   sqlite3 *db,            /* Database handle */
2976   const void *zSql,       /* SQL statement, UTF-16 encoded */
2977   int nByte,              /* Maximum length of zSql in bytes. */
2978   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2979   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
2980 );
2981
2982 /*
2983 ** CAPI3REF: Retrieving Statement SQL
2984 **
2985 ** ^This interface can be used to retrieve a saved copy of the original
2986 ** SQL text used to create a [prepared statement] if that statement was
2987 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
2988 */
2989 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
2990
2991 /*
2992 ** CAPI3REF: Dynamically Typed Value Object
2993 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
2994 **
2995 ** SQLite uses the sqlite3_value object to represent all values
2996 ** that can be stored in a database table. SQLite uses dynamic typing
2997 ** for the values it stores.  ^Values stored in sqlite3_value objects
2998 ** can be integers, floating point values, strings, BLOBs, or NULL.
2999 **
3000 ** An sqlite3_value object may be either "protected" or "unprotected".
3001 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3002 ** will accept either a protected or an unprotected sqlite3_value.
3003 ** Every interface that accepts sqlite3_value arguments specifies
3004 ** whether or not it requires a protected sqlite3_value.
3005 **
3006 ** The terms "protected" and "unprotected" refer to whether or not
3007 ** a mutex is held.  A internal mutex is held for a protected
3008 ** sqlite3_value object but no mutex is held for an unprotected
3009 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3010 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3011 ** or if SQLite is run in one of reduced mutex modes 
3012 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3013 ** then there is no distinction between protected and unprotected
3014 ** sqlite3_value objects and they can be used interchangeably.  However,
3015 ** for maximum code portability it is recommended that applications
3016 ** still make the distinction between between protected and unprotected
3017 ** sqlite3_value objects even when not strictly required.
3018 **
3019 ** ^The sqlite3_value objects that are passed as parameters into the
3020 ** implementation of [application-defined SQL functions] are protected.
3021 ** ^The sqlite3_value object returned by
3022 ** [sqlite3_column_value()] is unprotected.
3023 ** Unprotected sqlite3_value objects may only be used with
3024 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3025 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3026 ** interfaces require protected sqlite3_value objects.
3027 */
3028 typedef struct Mem sqlite3_value;
3029
3030 /*
3031 ** CAPI3REF: SQL Function Context Object
3032 **
3033 ** The context in which an SQL function executes is stored in an
3034 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3035 ** is always first parameter to [application-defined SQL functions].
3036 ** The application-defined SQL function implementation will pass this
3037 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3038 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3039 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3040 ** and/or [sqlite3_set_auxdata()].
3041 */
3042 typedef struct sqlite3_context sqlite3_context;
3043
3044 /*
3045 ** CAPI3REF: Binding Values To Prepared Statements
3046 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3047 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3048 **
3049 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3050 ** literals may be replaced by a [parameter] that matches one of following
3051 ** templates:
3052 **
3053 ** <ul>
3054 ** <li>  ?
3055 ** <li>  ?NNN
3056 ** <li>  :VVV
3057 ** <li>  @VVV
3058 ** <li>  $VVV
3059 ** </ul>
3060 **
3061 ** In the templates above, NNN represents an integer literal,
3062 ** and VVV represents an alphanumeric identifer.)^  ^The values of these
3063 ** parameters (also called "host parameter names" or "SQL parameters")
3064 ** can be set using the sqlite3_bind_*() routines defined here.
3065 **
3066 ** ^The first argument to the sqlite3_bind_*() routines is always
3067 ** a pointer to the [sqlite3_stmt] object returned from
3068 ** [sqlite3_prepare_v2()] or its variants.
3069 **
3070 ** ^The second argument is the index of the SQL parameter to be set.
3071 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3072 ** SQL parameter is used more than once, second and subsequent
3073 ** occurrences have the same index as the first occurrence.
3074 ** ^The index for named parameters can be looked up using the
3075 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3076 ** for "?NNN" parameters is the value of NNN.
3077 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3078 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3079 **
3080 ** ^The third argument is the value to bind to the parameter.
3081 **
3082 ** ^(In those routines that have a fourth argument, its value is the
3083 ** number of bytes in the parameter.  To be clear: the value is the
3084 ** number of <u>bytes</u> in the value, not the number of characters.)^
3085 ** ^If the fourth parameter is negative, the length of the string is
3086 ** the number of bytes up to the first zero terminator.
3087 **
3088 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3089 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3090 ** string after SQLite has finished with it. ^If the fifth argument is
3091 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3092 ** information is in static, unmanaged space and does not need to be freed.
3093 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3094 ** SQLite makes its own private copy of the data immediately, before
3095 ** the sqlite3_bind_*() routine returns.
3096 **
3097 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3098 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3099 ** (just an integer to hold its size) while it is being processed.
3100 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3101 ** content is later written using
3102 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3103 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3104 **
3105 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3106 ** for the [prepared statement] or with a prepared statement for which
3107 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3108 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3109 ** routine is passed a [prepared statement] that has been finalized, the
3110 ** result is undefined and probably harmful.
3111 **
3112 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3113 ** ^Unbound parameters are interpreted as NULL.
3114 **
3115 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3116 ** [error code] if anything goes wrong.
3117 ** ^[SQLITE_RANGE] is returned if the parameter
3118 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3119 **
3120 ** See also: [sqlite3_bind_parameter_count()],
3121 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3122 */
3123 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3124 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3125 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3126 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3127 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3128 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3129 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3130 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3131 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3132
3133 /*
3134 ** CAPI3REF: Number Of SQL Parameters
3135 **
3136 ** ^This routine can be used to find the number of [SQL parameters]
3137 ** in a [prepared statement].  SQL parameters are tokens of the
3138 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3139 ** placeholders for values that are [sqlite3_bind_blob | bound]
3140 ** to the parameters at a later time.
3141 **
3142 ** ^(This routine actually returns the index of the largest (rightmost)
3143 ** parameter. For all forms except ?NNN, this will correspond to the
3144 ** number of unique parameters.  If parameters of the ?NNN form are used,
3145 ** there may be gaps in the list.)^
3146 **
3147 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3148 ** [sqlite3_bind_parameter_name()], and
3149 ** [sqlite3_bind_parameter_index()].
3150 */
3151 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3152
3153 /*
3154 ** CAPI3REF: Name Of A Host Parameter
3155 **
3156 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3157 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3158 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3159 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3160 ** respectively.
3161 ** In other words, the initial ":" or "$" or "@" or "?"
3162 ** is included as part of the name.)^
3163 ** ^Parameters of the form "?" without a following integer have no name
3164 ** and are referred to as "nameless" or "anonymous parameters".
3165 **
3166 ** ^The first host parameter has an index of 1, not 0.
3167 **
3168 ** ^If the value N is out of range or if the N-th parameter is
3169 ** nameless, then NULL is returned.  ^The returned string is
3170 ** always in UTF-8 encoding even if the named parameter was
3171 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3172 ** [sqlite3_prepare16_v2()].
3173 **
3174 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3175 ** [sqlite3_bind_parameter_count()], and
3176 ** [sqlite3_bind_parameter_index()].
3177 */
3178 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3179
3180 /*
3181 ** CAPI3REF: Index Of A Parameter With A Given Name
3182 **
3183 ** ^Return the index of an SQL parameter given its name.  ^The
3184 ** index value returned is suitable for use as the second
3185 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3186 ** is returned if no matching parameter is found.  ^The parameter
3187 ** name must be given in UTF-8 even if the original statement
3188 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3189 **
3190 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3191 ** [sqlite3_bind_parameter_count()], and
3192 ** [sqlite3_bind_parameter_index()].
3193 */
3194 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3195
3196 /*
3197 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3198 **
3199 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3200 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3201 ** ^Use this routine to reset all host parameters to NULL.
3202 */
3203 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3204
3205 /*
3206 ** CAPI3REF: Number Of Columns In A Result Set
3207 **
3208 ** ^Return the number of columns in the result set returned by the
3209 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3210 ** statement that does not return data (for example an [UPDATE]).
3211 */
3212 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3213
3214 /*
3215 ** CAPI3REF: Column Names In A Result Set
3216 **
3217 ** ^These routines return the name assigned to a particular column
3218 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3219 ** interface returns a pointer to a zero-terminated UTF-8 string
3220 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3221 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3222 ** that implements the [SELECT] statement. ^The second parameter is the
3223 ** column number.  ^The leftmost column is number 0.
3224 **
3225 ** ^The returned string pointer is valid until either the [prepared statement]
3226 ** is destroyed by [sqlite3_finalize()] or until the next call to
3227 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3228 **
3229 ** ^If sqlite3_malloc() fails during the processing of either routine
3230 ** (for example during a conversion from UTF-8 to UTF-16) then a
3231 ** NULL pointer is returned.
3232 **
3233 ** ^The name of a result column is the value of the "AS" clause for
3234 ** that column, if there is an AS clause.  If there is no AS clause
3235 ** then the name of the column is unspecified and may change from
3236 ** one release of SQLite to the next.
3237 */
3238 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3239 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3240
3241 /*
3242 ** CAPI3REF: Source Of Data In A Query Result
3243 **
3244 ** ^These routines provide a means to determine the database, table, and
3245 ** table column that is the origin of a particular result column in
3246 ** [SELECT] statement.
3247 ** ^The name of the database or table or column can be returned as
3248 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3249 ** the database name, the _table_ routines return the table name, and
3250 ** the origin_ routines return the column name.
3251 ** ^The returned string is valid until the [prepared statement] is destroyed
3252 ** using [sqlite3_finalize()] or until the same information is requested
3253 ** again in a different encoding.
3254 **
3255 ** ^The names returned are the original un-aliased names of the
3256 ** database, table, and column.
3257 **
3258 ** ^The first argument to these interfaces is a [prepared statement].
3259 ** ^These functions return information about the Nth result column returned by
3260 ** the statement, where N is the second function argument.
3261 ** ^The left-most column is column 0 for these routines.
3262 **
3263 ** ^If the Nth column returned by the statement is an expression or
3264 ** subquery and is not a column value, then all of these functions return
3265 ** NULL.  ^These routine might also return NULL if a memory allocation error
3266 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3267 ** or column that query result column was extracted from.
3268 **
3269 ** ^As with all other SQLite APIs, those whose names end with "16" return
3270 ** UTF-16 encoded strings and the other functions return UTF-8.
3271 **
3272 ** ^These APIs are only available if the library was compiled with the
3273 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3274 **
3275 ** If two or more threads call one or more of these routines against the same
3276 ** prepared statement and column at the same time then the results are
3277 ** undefined.
3278 **
3279 ** If two or more threads call one or more
3280 ** [sqlite3_column_database_name | column metadata interfaces]
3281 ** for the same [prepared statement] and result column
3282 ** at the same time then the results are undefined.
3283 */
3284 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3285 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3286 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3287 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3288 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3289 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3290
3291 /*
3292 ** CAPI3REF: Declared Datatype Of A Query Result
3293 **
3294 ** ^(The first parameter is a [prepared statement].
3295 ** If this statement is a [SELECT] statement and the Nth column of the
3296 ** returned result set of that [SELECT] is a table column (not an
3297 ** expression or subquery) then the declared type of the table
3298 ** column is returned.)^  ^If the Nth column of the result set is an
3299 ** expression or subquery, then a NULL pointer is returned.
3300 ** ^The returned string is always UTF-8 encoded.
3301 **
3302 ** ^(For example, given the database schema:
3303 **
3304 ** CREATE TABLE t1(c1 VARIANT);
3305 **
3306 ** and the following statement to be compiled:
3307 **
3308 ** SELECT c1 + 1, c1 FROM t1;
3309 **
3310 ** this routine would return the string "VARIANT" for the second result
3311 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3312 **
3313 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3314 ** is declared to contain a particular type does not mean that the
3315 ** data stored in that column is of the declared type.  SQLite is
3316 ** strongly typed, but the typing is dynamic not static.  ^Type
3317 ** is associated with individual values, not with the containers
3318 ** used to hold those values.
3319 */
3320 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3321 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3322
3323 /*
3324 ** CAPI3REF: Evaluate An SQL Statement
3325 **
3326 ** After a [prepared statement] has been prepared using either
3327 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3328 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3329 ** must be called one or more times to evaluate the statement.
3330 **
3331 ** The details of the behavior of the sqlite3_step() interface depend
3332 ** on whether the statement was prepared using the newer "v2" interface
3333 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3334 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3335 ** new "v2" interface is recommended for new applications but the legacy
3336 ** interface will continue to be supported.
3337 **
3338 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3339 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3340 ** ^With the "v2" interface, any of the other [result codes] or
3341 ** [extended result codes] might be returned as well.
3342 **
3343 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3344 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3345 ** or occurs outside of an explicit transaction, then you can retry the
3346 ** statement.  If the statement is not a [COMMIT] and occurs within a
3347 ** explicit transaction then you should rollback the transaction before
3348 ** continuing.
3349 **
3350 ** ^[SQLITE_DONE] means that the statement has finished executing
3351 ** successfully.  sqlite3_step() should not be called again on this virtual
3352 ** machine without first calling [sqlite3_reset()] to reset the virtual
3353 ** machine back to its initial state.
3354 **
3355 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3356 ** is returned each time a new row of data is ready for processing by the
3357 ** caller. The values may be accessed using the [column access functions].
3358 ** sqlite3_step() is called again to retrieve the next row of data.
3359 **
3360 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3361 ** violation) has occurred.  sqlite3_step() should not be called again on
3362 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3363 ** ^With the legacy interface, a more specific error code (for example,
3364 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3365 ** can be obtained by calling [sqlite3_reset()] on the
3366 ** [prepared statement].  ^In the "v2" interface,
3367 ** the more specific error code is returned directly by sqlite3_step().
3368 **
3369 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3370 ** Perhaps it was called on a [prepared statement] that has
3371 ** already been [sqlite3_finalize | finalized] or on one that had
3372 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3373 ** be the case that the same database connection is being used by two or
3374 ** more threads at the same moment in time.
3375 **
3376 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3377 ** API always returns a generic error code, [SQLITE_ERROR], following any
3378 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3379 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3380 ** specific [error codes] that better describes the error.
3381 ** We admit that this is a goofy design.  The problem has been fixed
3382 ** with the "v2" interface.  If you prepare all of your SQL statements
3383 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3384 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3385 ** then the more specific [error codes] are returned directly
3386 ** by sqlite3_step().  The use of the "v2" interface is recommended.
3387 */
3388 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3389
3390 /*
3391 ** CAPI3REF: Number of columns in a result set
3392 **
3393 ** ^The sqlite3_data_count(P) the number of columns in the
3394 ** of the result set of [prepared statement] P.
3395 */
3396 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3397
3398 /*
3399 ** CAPI3REF: Fundamental Datatypes
3400 ** KEYWORDS: SQLITE_TEXT
3401 **
3402 ** ^(Every value in SQLite has one of five fundamental datatypes:
3403 **
3404 ** <ul>
3405 ** <li> 64-bit signed integer
3406 ** <li> 64-bit IEEE floating point number
3407 ** <li> string
3408 ** <li> BLOB
3409 ** <li> NULL
3410 ** </ul>)^
3411 **
3412 ** These constants are codes for each of those types.
3413 **
3414 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3415 ** for a completely different meaning.  Software that links against both
3416 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3417 ** SQLITE_TEXT.
3418 */
3419 #define SQLITE_INTEGER  1
3420 #define SQLITE_FLOAT    2
3421 #define SQLITE_BLOB     4
3422 #define SQLITE_NULL     5
3423 #ifdef SQLITE_TEXT
3424 # undef SQLITE_TEXT
3425 #else
3426 # define SQLITE_TEXT     3
3427 #endif
3428 #define SQLITE3_TEXT     3
3429
3430 /*
3431 ** CAPI3REF: Result Values From A Query
3432 ** KEYWORDS: {column access functions}
3433 **
3434 ** These routines form the "result set" interface.
3435 **
3436 ** ^These routines return information about a single column of the current
3437 ** result row of a query.  ^In every case the first argument is a pointer
3438 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3439 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3440 ** and the second argument is the index of the column for which information
3441 ** should be returned. ^The leftmost column of the result set has the index 0.
3442 ** ^The number of columns in the result can be determined using
3443 ** [sqlite3_column_count()].
3444 **
3445 ** If the SQL statement does not currently point to a valid row, or if the
3446 ** column index is out of range, the result is undefined.
3447 ** These routines may only be called when the most recent call to
3448 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3449 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3450 ** If any of these routines are called after [sqlite3_reset()] or
3451 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3452 ** something other than [SQLITE_ROW], the results are undefined.
3453 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3454 ** are called from a different thread while any of these routines
3455 ** are pending, then the results are undefined.
3456 **
3457 ** ^The sqlite3_column_type() routine returns the
3458 ** [SQLITE_INTEGER | datatype code] for the initial data type
3459 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3460 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3461 ** returned by sqlite3_column_type() is only meaningful if no type
3462 ** conversions have occurred as described below.  After a type conversion,
3463 ** the value returned by sqlite3_column_type() is undefined.  Future
3464 ** versions of SQLite may change the behavior of sqlite3_column_type()
3465 ** following a type conversion.
3466 **
3467 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3468 ** routine returns the number of bytes in that BLOB or string.
3469 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3470 ** the string to UTF-8 and then returns the number of bytes.
3471 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3472 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3473 ** the number of bytes in that string.
3474 ** ^The value returned does not include the zero terminator at the end
3475 ** of the string.  ^For clarity: the value returned is the number of
3476 ** bytes in the string, not the number of characters.
3477 **
3478 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3479 ** even empty strings, are always zero terminated.  ^The return
3480 ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
3481 ** pointer, possibly even a NULL pointer.
3482 **
3483 ** ^The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
3484 ** but leaves the result in UTF-16 in native byte order instead of UTF-8.
3485 ** ^The zero terminator is not included in this count.
3486 **
3487 ** ^The object returned by [sqlite3_column_value()] is an
3488 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3489 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3490 ** If the [unprotected sqlite3_value] object returned by
3491 ** [sqlite3_column_value()] is used in any other way, including calls
3492 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3493 ** or [sqlite3_value_bytes()], then the behavior is undefined.
3494 **
3495 ** These routines attempt to convert the value where appropriate.  ^For
3496 ** example, if the internal representation is FLOAT and a text result
3497 ** is requested, [sqlite3_snprintf()] is used internally to perform the
3498 ** conversion automatically.  ^(The following table details the conversions
3499 ** that are applied:
3500 **
3501 ** <blockquote>
3502 ** <table border="1">
3503 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3504 **
3505 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3506 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3507 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3508 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3509 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3510 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3511 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
3512 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3513 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3514 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3515 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3516 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3517 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
3518 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3519 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3520 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3521 ** </table>
3522 ** </blockquote>)^
3523 **
3524 ** The table above makes reference to standard C library functions atoi()
3525 ** and atof().  SQLite does not really use these functions.  It has its
3526 ** own equivalent internal routines.  The atoi() and atof() names are
3527 ** used in the table for brevity and because they are familiar to most
3528 ** C programmers.
3529 **
3530 ** ^Note that when type conversions occur, pointers returned by prior
3531 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3532 ** sqlite3_column_text16() may be invalidated.
3533 ** ^(Type conversions and pointer invalidations might occur
3534 ** in the following cases:
3535 **
3536 ** <ul>
3537 ** <li> The initial content is a BLOB and sqlite3_column_text() or
3538 **      sqlite3_column_text16() is called.  A zero-terminator might
3539 **      need to be added to the string.</li>
3540 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3541 **      sqlite3_column_text16() is called.  The content must be converted
3542 **      to UTF-16.</li>
3543 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3544 **      sqlite3_column_text() is called.  The content must be converted
3545 **      to UTF-8.</li>
3546 ** </ul>)^
3547 **
3548 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3549 ** not invalidate a prior pointer, though of course the content of the buffer
3550 ** that the prior pointer points to will have been modified.  Other kinds
3551 ** of conversion are done in place when it is possible, but sometimes they
3552 ** are not possible and in those cases prior pointers are invalidated.
3553 **
3554 ** ^(The safest and easiest to remember policy is to invoke these routines
3555 ** in one of the following ways:
3556 **
3557 ** <ul>
3558 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3559 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3560 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3561 ** </ul>)^
3562 **
3563 ** In other words, you should call sqlite3_column_text(),
3564 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3565 ** into the desired format, then invoke sqlite3_column_bytes() or
3566 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
3567 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3568 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3569 ** with calls to sqlite3_column_bytes().
3570 **
3571 ** ^The pointers returned are valid until a type conversion occurs as
3572 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3573 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
3574 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
3575 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3576 ** [sqlite3_free()].
3577 **
3578 ** ^(If a memory allocation error occurs during the evaluation of any
3579 ** of these routines, a default value is returned.  The default value
3580 ** is either the integer 0, the floating point number 0.0, or a NULL
3581 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3582 ** [SQLITE_NOMEM].)^
3583 */
3584 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3585 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3586 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3587 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3588 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3589 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3590 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3591 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3592 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3593 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3594
3595 /*
3596 ** CAPI3REF: Destroy A Prepared Statement Object
3597 **
3598 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3599 ** ^If the statement was executed successfully or not executed at all, then
3600 ** SQLITE_OK is returned. ^If execution of the statement failed then an
3601 ** [error code] or [extended error code] is returned.
3602 **
3603 ** ^This routine can be called at any point during the execution of the
3604 ** [prepared statement].  ^If the virtual machine has not
3605 ** completed execution when this routine is called, that is like
3606 ** encountering an error or an [sqlite3_interrupt | interrupt].
3607 ** ^Incomplete updates may be rolled back and transactions canceled,
3608 ** depending on the circumstances, and the
3609 ** [error code] returned will be [SQLITE_ABORT].
3610 */
3611 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3612
3613 /*
3614 ** CAPI3REF: Reset A Prepared Statement Object
3615 **
3616 ** The sqlite3_reset() function is called to reset a [prepared statement]
3617 ** object back to its initial state, ready to be re-executed.
3618 ** ^Any SQL statement variables that had values bound to them using
3619 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3620 ** Use [sqlite3_clear_bindings()] to reset the bindings.
3621 **
3622 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3623 ** back to the beginning of its program.
3624 **
3625 ** ^If the most recent call to [sqlite3_step(S)] for the
3626 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3627 ** or if [sqlite3_step(S)] has never before been called on S,
3628 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
3629 **
3630 ** ^If the most recent call to [sqlite3_step(S)] for the
3631 ** [prepared statement] S indicated an error, then
3632 ** [sqlite3_reset(S)] returns an appropriate [error code].
3633 **
3634 ** ^The [sqlite3_reset(S)] interface does not change the values
3635 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3636 */
3637 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3638
3639 /*
3640 ** CAPI3REF: Create Or Redefine SQL Functions
3641 ** KEYWORDS: {function creation routines}
3642 ** KEYWORDS: {application-defined SQL function}
3643 ** KEYWORDS: {application-defined SQL functions}
3644 **
3645 ** ^These two functions (collectively known as "function creation routines")
3646 ** are used to add SQL functions or aggregates or to redefine the behavior
3647 ** of existing SQL functions or aggregates.  The only difference between the
3648 ** two is that the second parameter, the name of the (scalar) function or
3649 ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
3650 ** for sqlite3_create_function16().
3651 **
3652 ** ^The first parameter is the [database connection] to which the SQL
3653 ** function is to be added.  ^If an application uses more than one database
3654 ** connection then application-defined SQL functions must be added
3655 ** to each database connection separately.
3656 **
3657 ** The second parameter is the name of the SQL function to be created or
3658 ** redefined.  ^The length of the name is limited to 255 bytes, exclusive of
3659 ** the zero-terminator.  Note that the name length limit is in bytes, not
3660 ** characters.  ^Any attempt to create a function with a longer name
3661 ** will result in [SQLITE_ERROR] being returned.
3662 **
3663 ** ^The third parameter (nArg)
3664 ** is the number of arguments that the SQL function or
3665 ** aggregate takes. ^If this parameter is -1, then the SQL function or
3666 ** aggregate may take any number of arguments between 0 and the limit
3667 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
3668 ** parameter is less than -1 or greater than 127 then the behavior is
3669 ** undefined.
3670 **
3671 ** The fourth parameter, eTextRep, specifies what
3672 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3673 ** its parameters.  Any SQL function implementation should be able to work
3674 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
3675 ** more efficient with one encoding than another.  ^An application may
3676 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3677 ** times with the same function but with different values of eTextRep.
3678 ** ^When multiple implementations of the same function are available, SQLite
3679 ** will pick the one that involves the least amount of data conversion.
3680 ** If there is only a single implementation which does not care what text
3681 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
3682 **
3683 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
3684 ** function can gain access to this pointer using [sqlite3_user_data()].)^
3685 **
3686 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3687 ** pointers to C-language functions that implement the SQL function or
3688 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3689 ** callback only; NULL pointers should be passed as the xStep and xFinal
3690 ** parameters. ^An aggregate SQL function requires an implementation of xStep
3691 ** and xFinal and NULL should be passed for xFunc. ^To delete an existing
3692 ** SQL function or aggregate, pass NULL for all three function callbacks.
3693 **
3694 ** ^It is permitted to register multiple implementations of the same
3695 ** functions with the same name but with either differing numbers of
3696 ** arguments or differing preferred text encodings.  ^SQLite will use
3697 ** the implementation that most closely matches the way in which the
3698 ** SQL function is used.  ^A function implementation with a non-negative
3699 ** nArg parameter is a better match than a function implementation with
3700 ** a negative nArg.  ^A function where the preferred text encoding
3701 ** matches the database encoding is a better
3702 ** match than a function where the encoding is different.  
3703 ** ^A function where the encoding difference is between UTF16le and UTF16be
3704 ** is a closer match than a function where the encoding difference is
3705 ** between UTF8 and UTF16.
3706 **
3707 ** ^Built-in functions may be overloaded by new application-defined functions.
3708 ** ^The first application-defined function with a given name overrides all
3709 ** built-in functions in the same [database connection] with the same name.
3710 ** ^Subsequent application-defined functions of the same name only override 
3711 ** prior application-defined functions that are an exact match for the
3712 ** number of parameters and preferred encoding.
3713 **
3714 ** ^An application-defined function is permitted to call other
3715 ** SQLite interfaces.  However, such calls must not
3716 ** close the database connection nor finalize or reset the prepared
3717 ** statement in which the function is running.
3718 */
3719 SQLITE_API int sqlite3_create_function(
3720   sqlite3 *db,
3721   const char *zFunctionName,
3722   int nArg,
3723   int eTextRep,
3724   void *pApp,
3725   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3726   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3727   void (*xFinal)(sqlite3_context*)
3728 );
3729 SQLITE_API int sqlite3_create_function16(
3730   sqlite3 *db,
3731   const void *zFunctionName,
3732   int nArg,
3733   int eTextRep,
3734   void *pApp,
3735   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3736   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3737   void (*xFinal)(sqlite3_context*)
3738 );
3739
3740 /*
3741 ** CAPI3REF: Text Encodings
3742 **
3743 ** These constant define integer codes that represent the various
3744 ** text encodings supported by SQLite.
3745 */
3746 #define SQLITE_UTF8           1
3747 #define SQLITE_UTF16LE        2
3748 #define SQLITE_UTF16BE        3
3749 #define SQLITE_UTF16          4    /* Use native byte order */
3750 #define SQLITE_ANY            5    /* sqlite3_create_function only */
3751 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
3752
3753 /*
3754 ** CAPI3REF: Deprecated Functions
3755 ** DEPRECATED
3756 **
3757 ** These functions are [deprecated].  In order to maintain
3758 ** backwards compatibility with older code, these functions continue 
3759 ** to be supported.  However, new applications should avoid
3760 ** the use of these functions.  To help encourage people to avoid
3761 ** using these functions, we are not going to tell you what they do.
3762 */
3763 #ifndef SQLITE_OMIT_DEPRECATED
3764 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
3765 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
3766 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
3767 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
3768 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
3769 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
3770 #endif
3771
3772 /*
3773 ** CAPI3REF: Obtaining SQL Function Parameter Values
3774 **
3775 ** The C-language implementation of SQL functions and aggregates uses
3776 ** this set of interface routines to access the parameter values on
3777 ** the function or aggregate.
3778 **
3779 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
3780 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
3781 ** define callbacks that implement the SQL functions and aggregates.
3782 ** The 4th parameter to these callbacks is an array of pointers to
3783 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
3784 ** each parameter to the SQL function.  These routines are used to
3785 ** extract values from the [sqlite3_value] objects.
3786 **
3787 ** These routines work only with [protected sqlite3_value] objects.
3788 ** Any attempt to use these routines on an [unprotected sqlite3_value]
3789 ** object results in undefined behavior.
3790 **
3791 ** ^These routines work just like the corresponding [column access functions]
3792 ** except that  these routines take a single [protected sqlite3_value] object
3793 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
3794 **
3795 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
3796 ** in the native byte-order of the host machine.  ^The
3797 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
3798 ** extract UTF-16 strings as big-endian and little-endian respectively.
3799 **
3800 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
3801 ** numeric affinity to the value.  This means that an attempt is
3802 ** made to convert the value to an integer or floating point.  If
3803 ** such a conversion is possible without loss of information (in other
3804 ** words, if the value is a string that looks like a number)
3805 ** then the conversion is performed.  Otherwise no conversion occurs.
3806 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
3807 **
3808 ** Please pay particular attention to the fact that the pointer returned
3809 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
3810 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
3811 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
3812 ** or [sqlite3_value_text16()].
3813 **
3814 ** These routines must be called from the same thread as
3815 ** the SQL function that supplied the [sqlite3_value*] parameters.
3816 */
3817 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
3818 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
3819 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
3820 SQLITE_API double sqlite3_value_double(sqlite3_value*);
3821 SQLITE_API int sqlite3_value_int(sqlite3_value*);
3822 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
3823 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
3824 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
3825 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
3826 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
3827 SQLITE_API int sqlite3_value_type(sqlite3_value*);
3828 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
3829
3830 /*
3831 ** CAPI3REF: Obtain Aggregate Function Context
3832 **
3833 ** Implementions of aggregate SQL functions use this
3834 ** routine to allocate memory for storing their state.
3835 **
3836 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
3837 ** for a particular aggregate function, SQLite
3838 ** allocates N of memory, zeroes out that memory, and returns a pointer
3839 ** to the new memory. ^On second and subsequent calls to
3840 ** sqlite3_aggregate_context() for the same aggregate function instance,
3841 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
3842 ** called once for each invocation of the xStep callback and then one
3843 ** last time when the xFinal callback is invoked.  ^(When no rows match
3844 ** an aggregate query, the xStep() callback of the aggregate function
3845 ** implementation is never called and xFinal() is called exactly once.
3846 ** In those cases, sqlite3_aggregate_context() might be called for the
3847 ** first time from within xFinal().)^
3848 **
3849 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
3850 ** less than or equal to zero or if a memory allocate error occurs.
3851 **
3852 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
3853 ** determined by the N parameter on first successful call.  Changing the
3854 ** value of N in subsequent call to sqlite3_aggregate_context() within
3855 ** the same aggregate function instance will not resize the memory
3856 ** allocation.)^
3857 **
3858 ** ^SQLite automatically frees the memory allocated by 
3859 ** sqlite3_aggregate_context() when the aggregate query concludes.
3860 **
3861 ** The first parameter must be a copy of the
3862 ** [sqlite3_context | SQL function context] that is the first parameter
3863 ** to the xStep or xFinal callback routine that implements the aggregate
3864 ** function.
3865 **
3866 ** This routine must be called from the same thread in which
3867 ** the aggregate SQL function is running.
3868 */
3869 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
3870
3871 /*
3872 ** CAPI3REF: User Data For Functions
3873 **
3874 ** ^The sqlite3_user_data() interface returns a copy of
3875 ** the pointer that was the pUserData parameter (the 5th parameter)
3876 ** of the [sqlite3_create_function()]
3877 ** and [sqlite3_create_function16()] routines that originally
3878 ** registered the application defined function.
3879 **
3880 ** This routine must be called from the same thread in which
3881 ** the application-defined function is running.
3882 */
3883 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
3884
3885 /*
3886 ** CAPI3REF: Database Connection For Functions
3887 **
3888 ** ^The sqlite3_context_db_handle() interface returns a copy of
3889 ** the pointer to the [database connection] (the 1st parameter)
3890 ** of the [sqlite3_create_function()]
3891 ** and [sqlite3_create_function16()] routines that originally
3892 ** registered the application defined function.
3893 */
3894 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
3895
3896 /*
3897 ** CAPI3REF: Function Auxiliary Data
3898 **
3899 ** The following two functions may be used by scalar SQL functions to
3900 ** associate metadata with argument values. If the same value is passed to
3901 ** multiple invocations of the same SQL function during query execution, under
3902 ** some circumstances the associated metadata may be preserved. This may
3903 ** be used, for example, to add a regular-expression matching scalar
3904 ** function. The compiled version of the regular expression is stored as
3905 ** metadata associated with the SQL value passed as the regular expression
3906 ** pattern.  The compiled regular expression can be reused on multiple
3907 ** invocations of the same function so that the original pattern string
3908 ** does not need to be recompiled on each invocation.
3909 **
3910 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
3911 ** associated by the sqlite3_set_auxdata() function with the Nth argument
3912 ** value to the application-defined function. ^If no metadata has been ever
3913 ** been set for the Nth argument of the function, or if the corresponding
3914 ** function parameter has changed since the meta-data was set,
3915 ** then sqlite3_get_auxdata() returns a NULL pointer.
3916 **
3917 ** ^The sqlite3_set_auxdata() interface saves the metadata
3918 ** pointed to by its 3rd parameter as the metadata for the N-th
3919 ** argument of the application-defined function.  Subsequent
3920 ** calls to sqlite3_get_auxdata() might return this data, if it has
3921 ** not been destroyed.
3922 ** ^If it is not NULL, SQLite will invoke the destructor
3923 ** function given by the 4th parameter to sqlite3_set_auxdata() on
3924 ** the metadata when the corresponding function parameter changes
3925 ** or when the SQL statement completes, whichever comes first.
3926 **
3927 ** SQLite is free to call the destructor and drop metadata on any
3928 ** parameter of any function at any time.  ^The only guarantee is that
3929 ** the destructor will be called before the metadata is dropped.
3930 **
3931 ** ^(In practice, metadata is preserved between function calls for
3932 ** expressions that are constant at compile time. This includes literal
3933 ** values and [parameters].)^
3934 **
3935 ** These routines must be called from the same thread in which
3936 ** the SQL function is running.
3937 */
3938 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
3939 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
3940
3941
3942 /*
3943 ** CAPI3REF: Constants Defining Special Destructor Behavior
3944 **
3945 ** These are special values for the destructor that is passed in as the
3946 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
3947 ** argument is SQLITE_STATIC, it means that the content pointer is constant
3948 ** and will never change.  It does not need to be destroyed.  ^The
3949 ** SQLITE_TRANSIENT value means that the content will likely change in
3950 ** the near future and that SQLite should make its own private copy of
3951 ** the content before returning.
3952 **
3953 ** The typedef is necessary to work around problems in certain
3954 ** C++ compilers.  See ticket #2191.
3955 */
3956 typedef void (*sqlite3_destructor_type)(void*);
3957 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
3958 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
3959
3960 /*
3961 ** CAPI3REF: Setting The Result Of An SQL Function
3962 **
3963 ** These routines are used by the xFunc or xFinal callbacks that
3964 ** implement SQL functions and aggregates.  See
3965 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
3966 ** for additional information.
3967 **
3968 ** These functions work very much like the [parameter binding] family of
3969 ** functions used to bind values to host parameters in prepared statements.
3970 ** Refer to the [SQL parameter] documentation for additional information.
3971 **
3972 ** ^The sqlite3_result_blob() interface sets the result from
3973 ** an application-defined function to be the BLOB whose content is pointed
3974 ** to by the second parameter and which is N bytes long where N is the
3975 ** third parameter.
3976 **
3977 ** ^The sqlite3_result_zeroblob() interfaces set the result of
3978 ** the application-defined function to be a BLOB containing all zero
3979 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
3980 **
3981 ** ^The sqlite3_result_double() interface sets the result from
3982 ** an application-defined function to be a floating point value specified
3983 ** by its 2nd argument.
3984 **
3985 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
3986 ** cause the implemented SQL function to throw an exception.
3987 ** ^SQLite uses the string pointed to by the
3988 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
3989 ** as the text of an error message.  ^SQLite interprets the error
3990 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
3991 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
3992 ** byte order.  ^If the third parameter to sqlite3_result_error()
3993 ** or sqlite3_result_error16() is negative then SQLite takes as the error
3994 ** message all text up through the first zero character.
3995 ** ^If the third parameter to sqlite3_result_error() or
3996 ** sqlite3_result_error16() is non-negative then SQLite takes that many
3997 ** bytes (not characters) from the 2nd parameter as the error message.
3998 ** ^The sqlite3_result_error() and sqlite3_result_error16()
3999 ** routines make a private copy of the error message text before
4000 ** they return.  Hence, the calling function can deallocate or
4001 ** modify the text after they return without harm.
4002 ** ^The sqlite3_result_error_code() function changes the error code
4003 ** returned by SQLite as a result of an error in a function.  ^By default,
4004 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4005 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4006 **
4007 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4008 ** indicating that a string or BLOB is too long to represent.
4009 **
4010 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4011 ** indicating that a memory allocation failed.
4012 **
4013 ** ^The sqlite3_result_int() interface sets the return value
4014 ** of the application-defined function to be the 32-bit signed integer
4015 ** value given in the 2nd argument.
4016 ** ^The sqlite3_result_int64() interface sets the return value
4017 ** of the application-defined function to be the 64-bit signed integer
4018 ** value given in the 2nd argument.
4019 **
4020 ** ^The sqlite3_result_null() interface sets the return value
4021 ** of the application-defined function to be NULL.
4022 **
4023 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4024 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4025 ** set the return value of the application-defined function to be
4026 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4027 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4028 ** ^SQLite takes the text result from the application from
4029 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4030 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4031 ** is negative, then SQLite takes result text from the 2nd parameter
4032 ** through the first zero character.
4033 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4034 ** is non-negative, then as many bytes (not characters) of the text
4035 ** pointed to by the 2nd parameter are taken as the application-defined
4036 ** function result.
4037 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4038 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4039 ** function as the destructor on the text or BLOB result when it has
4040 ** finished using that result.
4041 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4042 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4043 ** assumes that the text or BLOB result is in constant space and does not
4044 ** copy the content of the parameter nor call a destructor on the content
4045 ** when it has finished using that result.
4046 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4047 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4048 ** then SQLite makes a copy of the result into space obtained from
4049 ** from [sqlite3_malloc()] before it returns.
4050 **
4051 ** ^The sqlite3_result_value() interface sets the result of
4052 ** the application-defined function to be a copy the
4053 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4054 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4055 ** so that the [sqlite3_value] specified in the parameter may change or
4056 ** be deallocated after sqlite3_result_value() returns without harm.
4057 ** ^A [protected sqlite3_value] object may always be used where an
4058 ** [unprotected sqlite3_value] object is required, so either
4059 ** kind of [sqlite3_value] object can be used with this interface.
4060 **
4061 ** If these routines are called from within the different thread
4062 ** than the one containing the application-defined function that received
4063 ** the [sqlite3_context] pointer, the results are undefined.
4064 */
4065 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4066 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4067 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4068 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4069 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4070 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4071 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4072 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4073 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4074 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4075 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4076 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4077 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4078 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4079 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4080 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4081
4082 /*
4083 ** CAPI3REF: Define New Collating Sequences
4084 **
4085 ** These functions are used to add new collation sequences to the
4086 ** [database connection] specified as the first argument.
4087 **
4088 ** ^The name of the new collation sequence is specified as a UTF-8 string
4089 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4090 ** and a UTF-16 string for sqlite3_create_collation16(). ^In all cases
4091 ** the name is passed as the second function argument.
4092 **
4093 ** ^The third argument may be one of the constants [SQLITE_UTF8],
4094 ** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
4095 ** routine expects to be passed pointers to strings encoded using UTF-8,
4096 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. ^The
4097 ** third argument might also be [SQLITE_UTF16] to indicate that the routine
4098 ** expects pointers to be UTF-16 strings in the native byte order, or the
4099 ** argument can be [SQLITE_UTF16_ALIGNED] if the
4100 ** the routine expects pointers to 16-bit word aligned strings
4101 ** of UTF-16 in the native byte order.
4102 **
4103 ** A pointer to the user supplied routine must be passed as the fifth
4104 ** argument.  ^If it is NULL, this is the same as deleting the collation
4105 ** sequence (so that SQLite cannot call it anymore).
4106 ** ^Each time the application supplied function is invoked, it is passed
4107 ** as its first parameter a copy of the void* passed as the fourth argument
4108 ** to sqlite3_create_collation() or sqlite3_create_collation16().
4109 **
4110 ** ^The remaining arguments to the application-supplied routine are two strings,
4111 ** each represented by a (length, data) pair and encoded in the encoding
4112 ** that was passed as the third argument when the collation sequence was
4113 ** registered.  The application defined collation routine should
4114 ** return negative, zero or positive if the first string is less than,
4115 ** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
4116 **
4117 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4118 ** except that it takes an extra argument which is a destructor for
4119 ** the collation.  ^The destructor is called when the collation is
4120 ** destroyed and is passed a copy of the fourth parameter void* pointer
4121 ** of the sqlite3_create_collation_v2().
4122 ** ^Collations are destroyed when they are overridden by later calls to the
4123 ** collation creation functions or when the [database connection] is closed
4124 ** using [sqlite3_close()].
4125 **
4126 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4127 */
4128 SQLITE_API int sqlite3_create_collation(
4129   sqlite3*, 
4130   const char *zName, 
4131   int eTextRep, 
4132   void*,
4133   int(*xCompare)(void*,int,const void*,int,const void*)
4134 );
4135 SQLITE_API int sqlite3_create_collation_v2(
4136   sqlite3*, 
4137   const char *zName, 
4138   int eTextRep, 
4139   void*,
4140   int(*xCompare)(void*,int,const void*,int,const void*),
4141   void(*xDestroy)(void*)
4142 );
4143 SQLITE_API int sqlite3_create_collation16(
4144   sqlite3*, 
4145   const void *zName,
4146   int eTextRep, 
4147   void*,
4148   int(*xCompare)(void*,int,const void*,int,const void*)
4149 );
4150
4151 /*
4152 ** CAPI3REF: Collation Needed Callbacks
4153 **
4154 ** ^To avoid having to register all collation sequences before a database
4155 ** can be used, a single callback function may be registered with the
4156 ** [database connection] to be invoked whenever an undefined collation
4157 ** sequence is required.
4158 **
4159 ** ^If the function is registered using the sqlite3_collation_needed() API,
4160 ** then it is passed the names of undefined collation sequences as strings
4161 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4162 ** the names are passed as UTF-16 in machine native byte order.
4163 ** ^A call to either function replaces the existing collation-needed callback.
4164 **
4165 ** ^(When the callback is invoked, the first argument passed is a copy
4166 ** of the second argument to sqlite3_collation_needed() or
4167 ** sqlite3_collation_needed16().  The second argument is the database
4168 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4169 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4170 ** sequence function required.  The fourth parameter is the name of the
4171 ** required collation sequence.)^
4172 **
4173 ** The callback function should register the desired collation using
4174 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4175 ** [sqlite3_create_collation_v2()].
4176 */
4177 SQLITE_API int sqlite3_collation_needed(
4178   sqlite3*, 
4179   void*, 
4180   void(*)(void*,sqlite3*,int eTextRep,const char*)
4181 );
4182 SQLITE_API int sqlite3_collation_needed16(
4183   sqlite3*, 
4184   void*,
4185   void(*)(void*,sqlite3*,int eTextRep,const void*)
4186 );
4187
4188 /*
4189 ** Specify the key for an encrypted database.  This routine should be
4190 ** called right after sqlite3_open().
4191 **
4192 ** The code to implement this API is not available in the public release
4193 ** of SQLite.
4194 */
4195 SQLITE_API int sqlite3_key(
4196   sqlite3 *db,                   /* Database to be rekeyed */
4197   const void *pKey, int nKey     /* The key */
4198 );
4199
4200 /*
4201 ** Change the key on an open database.  If the current database is not
4202 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4203 ** database is decrypted.
4204 **
4205 ** The code to implement this API is not available in the public release
4206 ** of SQLite.
4207 */
4208 SQLITE_API int sqlite3_rekey(
4209   sqlite3 *db,                   /* Database to be rekeyed */
4210   const void *pKey, int nKey     /* The new key */
4211 );
4212
4213 /*
4214 ** CAPI3REF: Suspend Execution For A Short Time
4215 **
4216 ** ^The sqlite3_sleep() function causes the current thread to suspend execution
4217 ** for at least a number of milliseconds specified in its parameter.
4218 **
4219 ** ^If the operating system does not support sleep requests with
4220 ** millisecond time resolution, then the time will be rounded up to
4221 ** the nearest second. ^The number of milliseconds of sleep actually
4222 ** requested from the operating system is returned.
4223 **
4224 ** ^SQLite implements this interface by calling the xSleep()
4225 ** method of the default [sqlite3_vfs] object.
4226 */
4227 SQLITE_API int sqlite3_sleep(int);
4228
4229 /*
4230 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4231 **
4232 ** ^(If this global variable is made to point to a string which is
4233 ** the name of a folder (a.k.a. directory), then all temporary files
4234 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4235 ** will be placed in that directory.)^  ^If this variable
4236 ** is a NULL pointer, then SQLite performs a search for an appropriate
4237 ** temporary file directory.
4238 **
4239 ** It is not safe to read or modify this variable in more than one
4240 ** thread at a time.  It is not safe to read or modify this variable
4241 ** if a [database connection] is being used at the same time in a separate
4242 ** thread.
4243 ** It is intended that this variable be set once
4244 ** as part of process initialization and before any SQLite interface
4245 ** routines have been called and that this variable remain unchanged
4246 ** thereafter.
4247 **
4248 ** ^The [temp_store_directory pragma] may modify this variable and cause
4249 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4250 ** the [temp_store_directory pragma] always assumes that any string
4251 ** that this variable points to is held in memory obtained from 
4252 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4253 ** using [sqlite3_free].
4254 ** Hence, if this variable is modified directly, either it should be
4255 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4256 ** or else the use of the [temp_store_directory pragma] should be avoided.
4257 */
4258 SQLITE_API char *sqlite3_temp_directory;
4259
4260 /*
4261 ** CAPI3REF: Test For Auto-Commit Mode
4262 ** KEYWORDS: {autocommit mode}
4263 **
4264 ** ^The sqlite3_get_autocommit() interface returns non-zero or
4265 ** zero if the given database connection is or is not in autocommit mode,
4266 ** respectively.  ^Autocommit mode is on by default.
4267 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4268 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4269 **
4270 ** If certain kinds of errors occur on a statement within a multi-statement
4271 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4272 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4273 ** transaction might be rolled back automatically.  The only way to
4274 ** find out whether SQLite automatically rolled back the transaction after
4275 ** an error is to use this function.
4276 **
4277 ** If another thread changes the autocommit status of the database
4278 ** connection while this routine is running, then the return value
4279 ** is undefined.
4280 */
4281 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4282
4283 /*
4284 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4285 **
4286 ** ^The sqlite3_db_handle interface returns the [database connection] handle
4287 ** to which a [prepared statement] belongs.  ^The [database connection]
4288 ** returned by sqlite3_db_handle is the same [database connection]
4289 ** that was the first argument
4290 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4291 ** create the statement in the first place.
4292 */
4293 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4294
4295 /*
4296 ** CAPI3REF: Find the next prepared statement
4297 **
4298 ** ^This interface returns a pointer to the next [prepared statement] after
4299 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4300 ** then this interface returns a pointer to the first prepared statement
4301 ** associated with the database connection pDb.  ^If no prepared statement
4302 ** satisfies the conditions of this routine, it returns NULL.
4303 **
4304 ** The [database connection] pointer D in a call to
4305 ** [sqlite3_next_stmt(D,S)] must refer to an open database
4306 ** connection and in particular must not be a NULL pointer.
4307 */
4308 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4309
4310 /*
4311 ** CAPI3REF: Commit And Rollback Notification Callbacks
4312 **
4313 ** ^The sqlite3_commit_hook() interface registers a callback
4314 ** function to be invoked whenever a transaction is [COMMIT | committed].
4315 ** ^Any callback set by a previous call to sqlite3_commit_hook()
4316 ** for the same database connection is overridden.
4317 ** ^The sqlite3_rollback_hook() interface registers a callback
4318 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4319 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
4320 ** for the same database connection is overridden.
4321 ** ^The pArg argument is passed through to the callback.
4322 ** ^If the callback on a commit hook function returns non-zero,
4323 ** then the commit is converted into a rollback.
4324 **
4325 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4326 ** return the P argument from the previous call of the same function
4327 ** on the same [database connection] D, or NULL for
4328 ** the first call for each function on D.
4329 **
4330 ** The callback implementation must not do anything that will modify
4331 ** the database connection that invoked the callback.  Any actions
4332 ** to modify the database connection must be deferred until after the
4333 ** completion of the [sqlite3_step()] call that triggered the commit
4334 ** or rollback hook in the first place.
4335 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4336 ** database connections for the meaning of "modify" in this paragraph.
4337 **
4338 ** ^Registering a NULL function disables the callback.
4339 **
4340 ** ^When the commit hook callback routine returns zero, the [COMMIT]
4341 ** operation is allowed to continue normally.  ^If the commit hook
4342 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4343 ** ^The rollback hook is invoked on a rollback that results from a commit
4344 ** hook returning non-zero, just as it would be with any other rollback.
4345 **
4346 ** ^For the purposes of this API, a transaction is said to have been
4347 ** rolled back if an explicit "ROLLBACK" statement is executed, or
4348 ** an error or constraint causes an implicit rollback to occur.
4349 ** ^The rollback callback is not invoked if a transaction is
4350 ** automatically rolled back because the database connection is closed.
4351 ** ^The rollback callback is not invoked if a transaction is
4352 ** rolled back because a commit callback returned non-zero.
4353 **
4354 ** See also the [sqlite3_update_hook()] interface.
4355 */
4356 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4357 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4358
4359 /*
4360 ** CAPI3REF: Data Change Notification Callbacks
4361 **
4362 ** ^The sqlite3_update_hook() interface registers a callback function
4363 ** with the [database connection] identified by the first argument
4364 ** to be invoked whenever a row is updated, inserted or deleted.
4365 ** ^Any callback set by a previous call to this function
4366 ** for the same database connection is overridden.
4367 **
4368 ** ^The second argument is a pointer to the function to invoke when a
4369 ** row is updated, inserted or deleted.
4370 ** ^The first argument to the callback is a copy of the third argument
4371 ** to sqlite3_update_hook().
4372 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4373 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
4374 ** to be invoked.
4375 ** ^The third and fourth arguments to the callback contain pointers to the
4376 ** database and table name containing the affected row.
4377 ** ^The final callback parameter is the [rowid] of the row.
4378 ** ^In the case of an update, this is the [rowid] after the update takes place.
4379 **
4380 ** ^(The update hook is not invoked when internal system tables are
4381 ** modified (i.e. sqlite_master and sqlite_sequence).)^
4382 **
4383 ** ^In the current implementation, the update hook
4384 ** is not invoked when duplication rows are deleted because of an
4385 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4386 ** invoked when rows are deleted using the [truncate optimization].
4387 ** The exceptions defined in this paragraph might change in a future
4388 ** release of SQLite.
4389 **
4390 ** The update hook implementation must not do anything that will modify
4391 ** the database connection that invoked the update hook.  Any actions
4392 ** to modify the database connection must be deferred until after the
4393 ** completion of the [sqlite3_step()] call that triggered the update hook.
4394 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4395 ** database connections for the meaning of "modify" in this paragraph.
4396 **
4397 ** ^The sqlite3_update_hook(D,C,P) function
4398 ** returns the P argument from the previous call
4399 ** on the same [database connection] D, or NULL for
4400 ** the first call on D.
4401 **
4402 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4403 ** interfaces.
4404 */
4405 SQLITE_API void *sqlite3_update_hook(
4406   sqlite3*, 
4407   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4408   void*
4409 );
4410
4411 /*
4412 ** CAPI3REF: Enable Or Disable Shared Pager Cache
4413 ** KEYWORDS: {shared cache}
4414 **
4415 ** ^(This routine enables or disables the sharing of the database cache
4416 ** and schema data structures between [database connection | connections]
4417 ** to the same database. Sharing is enabled if the argument is true
4418 ** and disabled if the argument is false.)^
4419 **
4420 ** ^Cache sharing is enabled and disabled for an entire process.
4421 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4422 ** sharing was enabled or disabled for each thread separately.
4423 **
4424 ** ^(The cache sharing mode set by this interface effects all subsequent
4425 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4426 ** Existing database connections continue use the sharing mode
4427 ** that was in effect at the time they were opened.)^
4428 **
4429 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4430 ** successfully.  An [error code] is returned otherwise.)^
4431 **
4432 ** ^Shared cache is disabled by default. But this might change in
4433 ** future releases of SQLite.  Applications that care about shared
4434 ** cache setting should set it explicitly.
4435 **
4436 ** See Also:  [SQLite Shared-Cache Mode]
4437 */
4438 SQLITE_API int sqlite3_enable_shared_cache(int);
4439
4440 /*
4441 ** CAPI3REF: Attempt To Free Heap Memory
4442 **
4443 ** ^The sqlite3_release_memory() interface attempts to free N bytes
4444 ** of heap memory by deallocating non-essential memory allocations
4445 ** held by the database library.   Memory used to cache database
4446 ** pages to improve performance is an example of non-essential memory.
4447 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
4448 ** which might be more or less than the amount requested.
4449 */
4450 SQLITE_API int sqlite3_release_memory(int);
4451
4452 /*
4453 ** CAPI3REF: Impose A Limit On Heap Size
4454 **
4455 ** ^The sqlite3_soft_heap_limit() interface places a "soft" limit
4456 ** on the amount of heap memory that may be allocated by SQLite.
4457 ** ^If an internal allocation is requested that would exceed the
4458 ** soft heap limit, [sqlite3_release_memory()] is invoked one or
4459 ** more times to free up some space before the allocation is performed.
4460 **
4461 ** ^The limit is called "soft" because if [sqlite3_release_memory()]
4462 ** cannot free sufficient memory to prevent the limit from being exceeded,
4463 ** the memory is allocated anyway and the current operation proceeds.
4464 **
4465 ** ^A negative or zero value for N means that there is no soft heap limit and
4466 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
4467 ** ^The default value for the soft heap limit is zero.
4468 **
4469 ** ^(SQLite makes a best effort to honor the soft heap limit.
4470 ** But if the soft heap limit cannot be honored, execution will
4471 ** continue without error or notification.)^  This is why the limit is
4472 ** called a "soft" limit.  It is advisory only.
4473 **
4474 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
4475 ** allocated by a single thread - the same thread in which this routine
4476 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
4477 ** applied to all threads. The value specified for the soft heap limit
4478 ** is an upper bound on the total memory allocation for all threads. In
4479 ** version 3.5.0 there is no mechanism for limiting the heap usage for
4480 ** individual threads.
4481 */
4482 SQLITE_API void sqlite3_soft_heap_limit(int);
4483
4484 /*
4485 ** CAPI3REF: Extract Metadata About A Column Of A Table
4486 **
4487 ** ^This routine returns metadata about a specific column of a specific
4488 ** database table accessible using the [database connection] handle
4489 ** passed as the first function argument.
4490 **
4491 ** ^The column is identified by the second, third and fourth parameters to
4492 ** this function. ^The second parameter is either the name of the database
4493 ** (i.e. "main", "temp", or an attached database) containing the specified
4494 ** table or NULL. ^If it is NULL, then all attached databases are searched
4495 ** for the table using the same algorithm used by the database engine to
4496 ** resolve unqualified table references.
4497 **
4498 ** ^The third and fourth parameters to this function are the table and column
4499 ** name of the desired column, respectively. Neither of these parameters
4500 ** may be NULL.
4501 **
4502 ** ^Metadata is returned by writing to the memory locations passed as the 5th
4503 ** and subsequent parameters to this function. ^Any of these arguments may be
4504 ** NULL, in which case the corresponding element of metadata is omitted.
4505 **
4506 ** ^(<blockquote>
4507 ** <table border="1">
4508 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
4509 **
4510 ** <tr><td> 5th <td> const char* <td> Data type
4511 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
4512 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
4513 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
4514 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
4515 ** </table>
4516 ** </blockquote>)^
4517 **
4518 ** ^The memory pointed to by the character pointers returned for the
4519 ** declaration type and collation sequence is valid only until the next
4520 ** call to any SQLite API function.
4521 **
4522 ** ^If the specified table is actually a view, an [error code] is returned.
4523 **
4524 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
4525 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
4526 ** parameters are set for the explicitly declared column. ^(If there is no
4527 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
4528 ** parameters are set as follows:
4529 **
4530 ** <pre>
4531 **     data type: "INTEGER"
4532 **     collation sequence: "BINARY"
4533 **     not null: 0
4534 **     primary key: 1
4535 **     auto increment: 0
4536 ** </pre>)^
4537 **
4538 ** ^(This function may load one or more schemas from database files. If an
4539 ** error occurs during this process, or if the requested table or column
4540 ** cannot be found, an [error code] is returned and an error message left
4541 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
4542 **
4543 ** ^This API is only available if the library was compiled with the
4544 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
4545 */
4546 SQLITE_API int sqlite3_table_column_metadata(
4547   sqlite3 *db,                /* Connection handle */
4548   const char *zDbName,        /* Database name or NULL */
4549   const char *zTableName,     /* Table name */
4550   const char *zColumnName,    /* Column name */
4551   char const **pzDataType,    /* OUTPUT: Declared data type */
4552   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
4553   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
4554   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
4555   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
4556 );
4557
4558 /*
4559 ** CAPI3REF: Load An Extension
4560 **
4561 ** ^This interface loads an SQLite extension library from the named file.
4562 **
4563 ** ^The sqlite3_load_extension() interface attempts to load an
4564 ** SQLite extension library contained in the file zFile.
4565 **
4566 ** ^The entry point is zProc.
4567 ** ^zProc may be 0, in which case the name of the entry point
4568 ** defaults to "sqlite3_extension_init".
4569 ** ^The sqlite3_load_extension() interface returns
4570 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
4571 ** ^If an error occurs and pzErrMsg is not 0, then the
4572 ** [sqlite3_load_extension()] interface shall attempt to
4573 ** fill *pzErrMsg with error message text stored in memory
4574 ** obtained from [sqlite3_malloc()]. The calling function
4575 ** should free this memory by calling [sqlite3_free()].
4576 **
4577 ** ^Extension loading must be enabled using
4578 ** [sqlite3_enable_load_extension()] prior to calling this API,
4579 ** otherwise an error will be returned.
4580 **
4581 ** See also the [load_extension() SQL function].
4582 */
4583 SQLITE_API int sqlite3_load_extension(
4584   sqlite3 *db,          /* Load the extension into this database connection */
4585   const char *zFile,    /* Name of the shared library containing extension */
4586   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
4587   char **pzErrMsg       /* Put error message here if not 0 */
4588 );
4589
4590 /*
4591 ** CAPI3REF: Enable Or Disable Extension Loading
4592 **
4593 ** ^So as not to open security holes in older applications that are
4594 ** unprepared to deal with extension loading, and as a means of disabling
4595 ** extension loading while evaluating user-entered SQL, the following API
4596 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
4597 **
4598 ** ^Extension loading is off by default. See ticket #1863.
4599 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
4600 ** to turn extension loading on and call it with onoff==0 to turn
4601 ** it back off again.
4602 */
4603 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
4604
4605 /*
4606 ** CAPI3REF: Automatically Load An Extensions
4607 **
4608 ** ^This API can be invoked at program startup in order to register
4609 ** one or more statically linked extensions that will be available
4610 ** to all new [database connections].
4611 **
4612 ** ^(This routine stores a pointer to the extension entry point
4613 ** in an array that is obtained from [sqlite3_malloc()].  That memory
4614 ** is deallocated by [sqlite3_reset_auto_extension()].)^
4615 **
4616 ** ^This function registers an extension entry point that is
4617 ** automatically invoked whenever a new [database connection]
4618 ** is opened using [sqlite3_open()], [sqlite3_open16()],
4619 ** or [sqlite3_open_v2()].
4620 ** ^Duplicate extensions are detected so calling this routine
4621 ** multiple times with the same extension is harmless.
4622 ** ^Automatic extensions apply across all threads.
4623 */
4624 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
4625
4626 /*
4627 ** CAPI3REF: Reset Automatic Extension Loading
4628 **
4629 ** ^(This function disables all previously registered automatic
4630 ** extensions. It undoes the effect of all prior
4631 ** [sqlite3_auto_extension()] calls.)^
4632 **
4633 ** ^This function disables automatic extensions in all threads.
4634 */
4635 SQLITE_API void sqlite3_reset_auto_extension(void);
4636
4637 /*
4638 ****** EXPERIMENTAL - subject to change without notice **************
4639 **
4640 ** The interface to the virtual-table mechanism is currently considered
4641 ** to be experimental.  The interface might change in incompatible ways.
4642 ** If this is a problem for you, do not use the interface at this time.
4643 **
4644 ** When the virtual-table mechanism stabilizes, we will declare the
4645 ** interface fixed, support it indefinitely, and remove this comment.
4646 */
4647
4648 /*
4649 ** Structures used by the virtual table interface
4650 */
4651 typedef struct sqlite3_vtab sqlite3_vtab;
4652 typedef struct sqlite3_index_info sqlite3_index_info;
4653 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
4654 typedef struct sqlite3_module sqlite3_module;
4655
4656 /*
4657 ** CAPI3REF: Virtual Table Object
4658 ** KEYWORDS: sqlite3_module {virtual table module}
4659 ** EXPERIMENTAL
4660 **
4661 ** This structure, sometimes called a a "virtual table module", 
4662 ** defines the implementation of a [virtual tables].  
4663 ** This structure consists mostly of methods for the module.
4664 **
4665 ** ^A virtual table module is created by filling in a persistent
4666 ** instance of this structure and passing a pointer to that instance
4667 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
4668 ** ^The registration remains valid until it is replaced by a different
4669 ** module or until the [database connection] closes.  The content
4670 ** of this structure must not change while it is registered with
4671 ** any database connection.
4672 */
4673 struct sqlite3_module {
4674   int iVersion;
4675   int (*xCreate)(sqlite3*, void *pAux,
4676                int argc, const char *const*argv,
4677                sqlite3_vtab **ppVTab, char**);
4678   int (*xConnect)(sqlite3*, void *pAux,
4679                int argc, const char *const*argv,
4680                sqlite3_vtab **ppVTab, char**);
4681   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
4682   int (*xDisconnect)(sqlite3_vtab *pVTab);
4683   int (*xDestroy)(sqlite3_vtab *pVTab);
4684   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
4685   int (*xClose)(sqlite3_vtab_cursor*);
4686   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
4687                 int argc, sqlite3_value **argv);
4688   int (*xNext)(sqlite3_vtab_cursor*);
4689   int (*xEof)(sqlite3_vtab_cursor*);
4690   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
4691   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
4692   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
4693   int (*xBegin)(sqlite3_vtab *pVTab);
4694   int (*xSync)(sqlite3_vtab *pVTab);
4695   int (*xCommit)(sqlite3_vtab *pVTab);
4696   int (*xRollback)(sqlite3_vtab *pVTab);
4697   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
4698                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
4699                        void **ppArg);
4700   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
4701 };
4702
4703 /*
4704 ** CAPI3REF: Virtual Table Indexing Information
4705 ** KEYWORDS: sqlite3_index_info
4706 ** EXPERIMENTAL
4707 **
4708 ** The sqlite3_index_info structure and its substructures is used to
4709 ** pass information into and receive the reply from the [xBestIndex]
4710 ** method of a [virtual table module].  The fields under **Inputs** are the
4711 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
4712 ** results into the **Outputs** fields.
4713 **
4714 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
4715 **
4716 ** <pre>column OP expr</pre>
4717 **
4718 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
4719 ** stored in aConstraint[].op.)^  ^(The index of the column is stored in
4720 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
4721 ** expr on the right-hand side can be evaluated (and thus the constraint
4722 ** is usable) and false if it cannot.)^
4723 **
4724 ** ^The optimizer automatically inverts terms of the form "expr OP column"
4725 ** and makes other simplifications to the WHERE clause in an attempt to
4726 ** get as many WHERE clause terms into the form shown above as possible.
4727 ** ^The aConstraint[] array only reports WHERE clause terms that are
4728 ** relevant to the particular virtual table being queried.
4729 **
4730 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
4731 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
4732 **
4733 ** The [xBestIndex] method must fill aConstraintUsage[] with information
4734 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
4735 ** the right-hand side of the corresponding aConstraint[] is evaluated
4736 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
4737 ** is true, then the constraint is assumed to be fully handled by the
4738 ** virtual table and is not checked again by SQLite.)^
4739 **
4740 ** ^The idxNum and idxPtr values are recorded and passed into the
4741 ** [xFilter] method.
4742 ** ^[sqlite3_free()] is used to free idxPtr if and only if
4743 ** needToFreeIdxPtr is true.
4744 **
4745 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
4746 ** the correct order to satisfy the ORDER BY clause so that no separate
4747 ** sorting step is required.
4748 **
4749 ** ^The estimatedCost value is an estimate of the cost of doing the
4750 ** particular lookup.  A full scan of a table with N entries should have
4751 ** a cost of N.  A binary search of a table of N entries should have a
4752 ** cost of approximately log(N).
4753 */
4754 struct sqlite3_index_info {
4755   /* Inputs */
4756   int nConstraint;           /* Number of entries in aConstraint */
4757   struct sqlite3_index_constraint {
4758      int iColumn;              /* Column on left-hand side of constraint */
4759      unsigned char op;         /* Constraint operator */
4760      unsigned char usable;     /* True if this constraint is usable */
4761      int iTermOffset;          /* Used internally - xBestIndex should ignore */
4762   } *aConstraint;            /* Table of WHERE clause constraints */
4763   int nOrderBy;              /* Number of terms in the ORDER BY clause */
4764   struct sqlite3_index_orderby {
4765      int iColumn;              /* Column number */
4766      unsigned char desc;       /* True for DESC.  False for ASC. */
4767   } *aOrderBy;               /* The ORDER BY clause */
4768   /* Outputs */
4769   struct sqlite3_index_constraint_usage {
4770     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
4771     unsigned char omit;      /* Do not code a test for this constraint */
4772   } *aConstraintUsage;
4773   int idxNum;                /* Number used to identify the index */
4774   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
4775   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
4776   int orderByConsumed;       /* True if output is already ordered */
4777   double estimatedCost;      /* Estimated cost of using this index */
4778 };
4779 #define SQLITE_INDEX_CONSTRAINT_EQ    2
4780 #define SQLITE_INDEX_CONSTRAINT_GT    4
4781 #define SQLITE_INDEX_CONSTRAINT_LE    8
4782 #define SQLITE_INDEX_CONSTRAINT_LT    16
4783 #define SQLITE_INDEX_CONSTRAINT_GE    32
4784 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
4785
4786 /*
4787 ** CAPI3REF: Register A Virtual Table Implementation
4788 ** EXPERIMENTAL
4789 **
4790 ** ^These routines are used to register a new [virtual table module] name.
4791 ** ^Module names must be registered before
4792 ** creating a new [virtual table] using the module and before using a
4793 ** preexisting [virtual table] for the module.
4794 **
4795 ** ^The module name is registered on the [database connection] specified
4796 ** by the first parameter.  ^The name of the module is given by the 
4797 ** second parameter.  ^The third parameter is a pointer to
4798 ** the implementation of the [virtual table module].   ^The fourth
4799 ** parameter is an arbitrary client data pointer that is passed through
4800 ** into the [xCreate] and [xConnect] methods of the virtual table module
4801 ** when a new virtual table is be being created or reinitialized.
4802 **
4803 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
4804 ** is a pointer to a destructor for the pClientData.  ^SQLite will
4805 ** invoke the destructor function (if it is not NULL) when SQLite
4806 ** no longer needs the pClientData pointer.  ^The sqlite3_create_module()
4807 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
4808 ** destructor.
4809 */
4810 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
4811   sqlite3 *db,               /* SQLite connection to register module with */
4812   const char *zName,         /* Name of the module */
4813   const sqlite3_module *p,   /* Methods for the module */
4814   void *pClientData          /* Client data for xCreate/xConnect */
4815 );
4816 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
4817   sqlite3 *db,               /* SQLite connection to register module with */
4818   const char *zName,         /* Name of the module */
4819   const sqlite3_module *p,   /* Methods for the module */
4820   void *pClientData,         /* Client data for xCreate/xConnect */
4821   void(*xDestroy)(void*)     /* Module destructor function */
4822 );
4823
4824 /*
4825 ** CAPI3REF: Virtual Table Instance Object
4826 ** KEYWORDS: sqlite3_vtab
4827 ** EXPERIMENTAL
4828 **
4829 ** Every [virtual table module] implementation uses a subclass
4830 ** of this object to describe a particular instance
4831 ** of the [virtual table].  Each subclass will
4832 ** be tailored to the specific needs of the module implementation.
4833 ** The purpose of this superclass is to define certain fields that are
4834 ** common to all module implementations.
4835 **
4836 ** ^Virtual tables methods can set an error message by assigning a
4837 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
4838 ** take care that any prior string is freed by a call to [sqlite3_free()]
4839 ** prior to assigning a new string to zErrMsg.  ^After the error message
4840 ** is delivered up to the client application, the string will be automatically
4841 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
4842 */
4843 struct sqlite3_vtab {
4844   const sqlite3_module *pModule;  /* The module for this virtual table */
4845   int nRef;                       /* NO LONGER USED */
4846   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
4847   /* Virtual table implementations will typically add additional fields */
4848 };
4849
4850 /*
4851 ** CAPI3REF: Virtual Table Cursor Object
4852 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
4853 ** EXPERIMENTAL
4854 **
4855 ** Every [virtual table module] implementation uses a subclass of the
4856 ** following structure to describe cursors that point into the
4857 ** [virtual table] and are used
4858 ** to loop through the virtual table.  Cursors are created using the
4859 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
4860 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
4861 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
4862 ** of the module.  Each module implementation will define
4863 ** the content of a cursor structure to suit its own needs.
4864 **
4865 ** This superclass exists in order to define fields of the cursor that
4866 ** are common to all implementations.
4867 */
4868 struct sqlite3_vtab_cursor {
4869   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
4870   /* Virtual table implementations will typically add additional fields */
4871 };
4872
4873 /*
4874 ** CAPI3REF: Declare The Schema Of A Virtual Table
4875 ** EXPERIMENTAL
4876 **
4877 ** ^The [xCreate] and [xConnect] methods of a
4878 ** [virtual table module] call this interface
4879 ** to declare the format (the names and datatypes of the columns) of
4880 ** the virtual tables they implement.
4881 */
4882 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
4883
4884 /*
4885 ** CAPI3REF: Overload A Function For A Virtual Table
4886 ** EXPERIMENTAL
4887 **
4888 ** ^(Virtual tables can provide alternative implementations of functions
4889 ** using the [xFindFunction] method of the [virtual table module].  
4890 ** But global versions of those functions
4891 ** must exist in order to be overloaded.)^
4892 **
4893 ** ^(This API makes sure a global version of a function with a particular
4894 ** name and number of parameters exists.  If no such function exists
4895 ** before this API is called, a new function is created.)^  ^The implementation
4896 ** of the new function always causes an exception to be thrown.  So
4897 ** the new function is not good for anything by itself.  Its only
4898 ** purpose is to be a placeholder function that can be overloaded
4899 ** by a [virtual table].
4900 */
4901 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
4902
4903 /*
4904 ** The interface to the virtual-table mechanism defined above (back up
4905 ** to a comment remarkably similar to this one) is currently considered
4906 ** to be experimental.  The interface might change in incompatible ways.
4907 ** If this is a problem for you, do not use the interface at this time.
4908 **
4909 ** When the virtual-table mechanism stabilizes, we will declare the
4910 ** interface fixed, support it indefinitely, and remove this comment.
4911 **
4912 ****** EXPERIMENTAL - subject to change without notice **************
4913 */
4914
4915 /*
4916 ** CAPI3REF: A Handle To An Open BLOB
4917 ** KEYWORDS: {BLOB handle} {BLOB handles}
4918 **
4919 ** An instance of this object represents an open BLOB on which
4920 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
4921 ** ^Objects of this type are created by [sqlite3_blob_open()]
4922 ** and destroyed by [sqlite3_blob_close()].
4923 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
4924 ** can be used to read or write small subsections of the BLOB.
4925 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
4926 */
4927 typedef struct sqlite3_blob sqlite3_blob;
4928
4929 /*
4930 ** CAPI3REF: Open A BLOB For Incremental I/O
4931 **
4932 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
4933 ** in row iRow, column zColumn, table zTable in database zDb;
4934 ** in other words, the same BLOB that would be selected by:
4935 **
4936 ** <pre>
4937 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
4938 ** </pre>)^
4939 **
4940 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
4941 ** and write access. ^If it is zero, the BLOB is opened for read access.
4942 ** ^It is not possible to open a column that is part of an index or primary 
4943 ** key for writing. ^If [foreign key constraints] are enabled, it is 
4944 ** not possible to open a column that is part of a [child key] for writing.
4945 **
4946 ** ^Note that the database name is not the filename that contains
4947 ** the database but rather the symbolic name of the database that
4948 ** appears after the AS keyword when the database is connected using [ATTACH].
4949 ** ^For the main database file, the database name is "main".
4950 ** ^For TEMP tables, the database name is "temp".
4951 **
4952 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
4953 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
4954 ** to be a null pointer.)^
4955 ** ^This function sets the [database connection] error code and message
4956 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
4957 ** functions. ^Note that the *ppBlob variable is always initialized in a
4958 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
4959 ** regardless of the success or failure of this routine.
4960 **
4961 ** ^(If the row that a BLOB handle points to is modified by an
4962 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
4963 ** then the BLOB handle is marked as "expired".
4964 ** This is true if any column of the row is changed, even a column
4965 ** other than the one the BLOB handle is open on.)^
4966 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
4967 ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
4968 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
4969 ** rolled back by the expiration of the BLOB.  Such changes will eventually
4970 ** commit if the transaction continues to completion.)^
4971 **
4972 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
4973 ** the opened blob.  ^The size of a blob may not be changed by this
4974 ** interface.  Use the [UPDATE] SQL command to change the size of a
4975 ** blob.
4976 **
4977 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
4978 ** and the built-in [zeroblob] SQL function can be used, if desired,
4979 ** to create an empty, zero-filled blob in which to read or write using
4980 ** this interface.
4981 **
4982 ** To avoid a resource leak, every open [BLOB handle] should eventually
4983 ** be released by a call to [sqlite3_blob_close()].
4984 */
4985 SQLITE_API int sqlite3_blob_open(
4986   sqlite3*,
4987   const char *zDb,
4988   const char *zTable,
4989   const char *zColumn,
4990   sqlite3_int64 iRow,
4991   int flags,
4992   sqlite3_blob **ppBlob
4993 );
4994
4995 /*
4996 ** CAPI3REF: Close A BLOB Handle
4997 **
4998 ** ^Closes an open [BLOB handle].
4999 **
5000 ** ^Closing a BLOB shall cause the current transaction to commit
5001 ** if there are no other BLOBs, no pending prepared statements, and the
5002 ** database connection is in [autocommit mode].
5003 ** ^If any writes were made to the BLOB, they might be held in cache
5004 ** until the close operation if they will fit.
5005 **
5006 ** ^(Closing the BLOB often forces the changes
5007 ** out to disk and so if any I/O errors occur, they will likely occur
5008 ** at the time when the BLOB is closed.  Any errors that occur during
5009 ** closing are reported as a non-zero return value.)^
5010 **
5011 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
5012 ** an error code, the BLOB is still closed.)^
5013 **
5014 ** ^Calling this routine with a null pointer (such as would be returned
5015 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5016 */
5017 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5018
5019 /*
5020 ** CAPI3REF: Return The Size Of An Open BLOB
5021 **
5022 ** ^Returns the size in bytes of the BLOB accessible via the 
5023 ** successfully opened [BLOB handle] in its only argument.  ^The
5024 ** incremental blob I/O routines can only read or overwriting existing
5025 ** blob content; they cannot change the size of a blob.
5026 **
5027 ** This routine only works on a [BLOB handle] which has been created
5028 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5029 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5030 ** to this routine results in undefined and probably undesirable behavior.
5031 */
5032 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5033
5034 /*
5035 ** CAPI3REF: Read Data From A BLOB Incrementally
5036 **
5037 ** ^(This function is used to read data from an open [BLOB handle] into a
5038 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5039 ** from the open BLOB, starting at offset iOffset.)^
5040 **
5041 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5042 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5043 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5044 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5045 ** can be determined using the [sqlite3_blob_bytes()] interface.
5046 **
5047 ** ^An attempt to read from an expired [BLOB handle] fails with an
5048 ** error code of [SQLITE_ABORT].
5049 **
5050 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5051 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5052 **
5053 ** This routine only works on a [BLOB handle] which has been created
5054 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5055 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5056 ** to this routine results in undefined and probably undesirable behavior.
5057 **
5058 ** See also: [sqlite3_blob_write()].
5059 */
5060 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5061
5062 /*
5063 ** CAPI3REF: Write Data Into A BLOB Incrementally
5064 **
5065 ** ^This function is used to write data into an open [BLOB handle] from a
5066 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5067 ** into the open BLOB, starting at offset iOffset.
5068 **
5069 ** ^If the [BLOB handle] passed as the first argument was not opened for
5070 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5071 ** this function returns [SQLITE_READONLY].
5072 **
5073 ** ^This function may only modify the contents of the BLOB; it is
5074 ** not possible to increase the size of a BLOB using this API.
5075 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5076 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5077 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5078 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5079 ** can be determined using the [sqlite3_blob_bytes()] interface.
5080 **
5081 ** ^An attempt to write to an expired [BLOB handle] fails with an
5082 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5083 ** before the [BLOB handle] expired are not rolled back by the
5084 ** expiration of the handle, though of course those changes might
5085 ** have been overwritten by the statement that expired the BLOB handle
5086 ** or by other independent statements.
5087 **
5088 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5089 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
5090 **
5091 ** This routine only works on a [BLOB handle] which has been created
5092 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5093 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5094 ** to this routine results in undefined and probably undesirable behavior.
5095 **
5096 ** See also: [sqlite3_blob_read()].
5097 */
5098 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5099
5100 /*
5101 ** CAPI3REF: Virtual File System Objects
5102 **
5103 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5104 ** that SQLite uses to interact
5105 ** with the underlying operating system.  Most SQLite builds come with a
5106 ** single default VFS that is appropriate for the host computer.
5107 ** New VFSes can be registered and existing VFSes can be unregistered.
5108 ** The following interfaces are provided.
5109 **
5110 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5111 ** ^Names are case sensitive.
5112 ** ^Names are zero-terminated UTF-8 strings.
5113 ** ^If there is no match, a NULL pointer is returned.
5114 ** ^If zVfsName is NULL then the default VFS is returned.
5115 **
5116 ** ^New VFSes are registered with sqlite3_vfs_register().
5117 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5118 ** ^The same VFS can be registered multiple times without injury.
5119 ** ^To make an existing VFS into the default VFS, register it again
5120 ** with the makeDflt flag set.  If two different VFSes with the
5121 ** same name are registered, the behavior is undefined.  If a
5122 ** VFS is registered with a name that is NULL or an empty string,
5123 ** then the behavior is undefined.
5124 **
5125 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5126 ** ^(If the default VFS is unregistered, another VFS is chosen as
5127 ** the default.  The choice for the new VFS is arbitrary.)^
5128 */
5129 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5130 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5131 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5132
5133 /*
5134 ** CAPI3REF: Mutexes
5135 **
5136 ** The SQLite core uses these routines for thread
5137 ** synchronization. Though they are intended for internal
5138 ** use by SQLite, code that links against SQLite is
5139 ** permitted to use any of these routines.
5140 **
5141 ** The SQLite source code contains multiple implementations
5142 ** of these mutex routines.  An appropriate implementation
5143 ** is selected automatically at compile-time.  ^(The following
5144 ** implementations are available in the SQLite core:
5145 **
5146 ** <ul>
5147 ** <li>   SQLITE_MUTEX_OS2
5148 ** <li>   SQLITE_MUTEX_PTHREAD
5149 ** <li>   SQLITE_MUTEX_W32
5150 ** <li>   SQLITE_MUTEX_NOOP
5151 ** </ul>)^
5152 **
5153 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5154 ** that does no real locking and is appropriate for use in
5155 ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5156 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5157 ** are appropriate for use on OS/2, Unix, and Windows.
5158 **
5159 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5160 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5161 ** implementation is included with the library. In this case the
5162 ** application must supply a custom mutex implementation using the
5163 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5164 ** before calling sqlite3_initialize() or any other public sqlite3_
5165 ** function that calls sqlite3_initialize().)^
5166 **
5167 ** ^The sqlite3_mutex_alloc() routine allocates a new
5168 ** mutex and returns a pointer to it. ^If it returns NULL
5169 ** that means that a mutex could not be allocated.  ^SQLite
5170 ** will unwind its stack and return an error.  ^(The argument
5171 ** to sqlite3_mutex_alloc() is one of these integer constants:
5172 **
5173 ** <ul>
5174 ** <li>  SQLITE_MUTEX_FAST
5175 ** <li>  SQLITE_MUTEX_RECURSIVE
5176 ** <li>  SQLITE_MUTEX_STATIC_MASTER
5177 ** <li>  SQLITE_MUTEX_STATIC_MEM
5178 ** <li>  SQLITE_MUTEX_STATIC_MEM2
5179 ** <li>  SQLITE_MUTEX_STATIC_PRNG
5180 ** <li>  SQLITE_MUTEX_STATIC_LRU
5181 ** <li>  SQLITE_MUTEX_STATIC_LRU2
5182 ** </ul>)^
5183 **
5184 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5185 ** cause sqlite3_mutex_alloc() to create
5186 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5187 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5188 ** The mutex implementation does not need to make a distinction
5189 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5190 ** not want to.  ^SQLite will only request a recursive mutex in
5191 ** cases where it really needs one.  ^If a faster non-recursive mutex
5192 ** implementation is available on the host platform, the mutex subsystem
5193 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
5194 **
5195 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5196 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5197 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
5198 ** used by the current version of SQLite.  Future versions of SQLite
5199 ** may add additional static mutexes.  Static mutexes are for internal
5200 ** use by SQLite only.  Applications that use SQLite mutexes should
5201 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5202 ** SQLITE_MUTEX_RECURSIVE.
5203 **
5204 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5205 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5206 ** returns a different mutex on every call.  ^But for the static
5207 ** mutex types, the same mutex is returned on every call that has
5208 ** the same type number.
5209 **
5210 ** ^The sqlite3_mutex_free() routine deallocates a previously
5211 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5212 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5213 ** use when they are deallocated.  Attempting to deallocate a static
5214 ** mutex results in undefined behavior.  ^SQLite never deallocates
5215 ** a static mutex.
5216 **
5217 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5218 ** to enter a mutex.  ^If another thread is already within the mutex,
5219 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5220 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5221 ** upon successful entry.  ^(Mutexes created using
5222 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5223 ** In such cases the,
5224 ** mutex must be exited an equal number of times before another thread
5225 ** can enter.)^  ^(If the same thread tries to enter any other
5226 ** kind of mutex more than once, the behavior is undefined.
5227 ** SQLite will never exhibit
5228 ** such behavior in its own use of mutexes.)^
5229 **
5230 ** ^(Some systems (for example, Windows 95) do not support the operation
5231 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5232 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
5233 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5234 **
5235 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
5236 ** previously entered by the same thread.   ^(The behavior
5237 ** is undefined if the mutex is not currently entered by the
5238 ** calling thread or is not currently allocated.  SQLite will
5239 ** never do either.)^
5240 **
5241 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5242 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5243 ** behave as no-ops.
5244 **
5245 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5246 */
5247 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5248 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5249 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5250 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5251 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5252
5253 /*
5254 ** CAPI3REF: Mutex Methods Object
5255 ** EXPERIMENTAL
5256 **
5257 ** An instance of this structure defines the low-level routines
5258 ** used to allocate and use mutexes.
5259 **
5260 ** Usually, the default mutex implementations provided by SQLite are
5261 ** sufficient, however the user has the option of substituting a custom
5262 ** implementation for specialized deployments or systems for which SQLite
5263 ** does not provide a suitable implementation. In this case, the user
5264 ** creates and populates an instance of this structure to pass
5265 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5266 ** Additionally, an instance of this structure can be used as an
5267 ** output variable when querying the system for the current mutex
5268 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5269 **
5270 ** ^The xMutexInit method defined by this structure is invoked as
5271 ** part of system initialization by the sqlite3_initialize() function.
5272 ** ^The xMutexInit routine is calle by SQLite exactly once for each
5273 ** effective call to [sqlite3_initialize()].
5274 **
5275 ** ^The xMutexEnd method defined by this structure is invoked as
5276 ** part of system shutdown by the sqlite3_shutdown() function. The
5277 ** implementation of this method is expected to release all outstanding
5278 ** resources obtained by the mutex methods implementation, especially
5279 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
5280 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5281 **
5282 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5283 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5284 ** xMutexNotheld) implement the following interfaces (respectively):
5285 **
5286 ** <ul>
5287 **   <li>  [sqlite3_mutex_alloc()] </li>
5288 **   <li>  [sqlite3_mutex_free()] </li>
5289 **   <li>  [sqlite3_mutex_enter()] </li>
5290 **   <li>  [sqlite3_mutex_try()] </li>
5291 **   <li>  [sqlite3_mutex_leave()] </li>
5292 **   <li>  [sqlite3_mutex_held()] </li>
5293 **   <li>  [sqlite3_mutex_notheld()] </li>
5294 ** </ul>)^
5295 **
5296 ** The only difference is that the public sqlite3_XXX functions enumerated
5297 ** above silently ignore any invocations that pass a NULL pointer instead
5298 ** of a valid mutex handle. The implementations of the methods defined
5299 ** by this structure are not required to handle this case, the results
5300 ** of passing a NULL pointer instead of a valid mutex handle are undefined
5301 ** (i.e. it is acceptable to provide an implementation that segfaults if
5302 ** it is passed a NULL pointer).
5303 **
5304 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5305 ** invoke xMutexInit() mutiple times within the same process and without
5306 ** intervening calls to xMutexEnd().  Second and subsequent calls to
5307 ** xMutexInit() must be no-ops.
5308 **
5309 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5310 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5311 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5312 ** memory allocation for a fast or recursive mutex.
5313 **
5314 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5315 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5316 ** If xMutexInit fails in any way, it is expected to clean up after itself
5317 ** prior to returning.
5318 */
5319 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5320 struct sqlite3_mutex_methods {
5321   int (*xMutexInit)(void);
5322   int (*xMutexEnd)(void);
5323   sqlite3_mutex *(*xMutexAlloc)(int);
5324   void (*xMutexFree)(sqlite3_mutex *);
5325   void (*xMutexEnter)(sqlite3_mutex *);
5326   int (*xMutexTry)(sqlite3_mutex *);
5327   void (*xMutexLeave)(sqlite3_mutex *);
5328   int (*xMutexHeld)(sqlite3_mutex *);
5329   int (*xMutexNotheld)(sqlite3_mutex *);
5330 };
5331
5332 /*
5333 ** CAPI3REF: Mutex Verification Routines
5334 **
5335 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5336 ** are intended for use inside assert() statements.  ^The SQLite core
5337 ** never uses these routines except inside an assert() and applications
5338 ** are advised to follow the lead of the core.  ^The SQLite core only
5339 ** provides implementations for these routines when it is compiled
5340 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
5341 ** are only required to provide these routines if SQLITE_DEBUG is
5342 ** defined and if NDEBUG is not defined.
5343 **
5344 ** ^These routines should return true if the mutex in their argument
5345 ** is held or not held, respectively, by the calling thread.
5346 **
5347 ** ^The implementation is not required to provided versions of these
5348 ** routines that actually work. If the implementation does not provide working
5349 ** versions of these routines, it should at least provide stubs that always
5350 ** return true so that one does not get spurious assertion failures.
5351 **
5352 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
5353 ** the routine should return 1.   This seems counter-intuitive since
5354 ** clearly the mutex cannot be held if it does not exist.  But the
5355 ** the reason the mutex does not exist is because the build is not
5356 ** using mutexes.  And we do not want the assert() containing the
5357 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
5358 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
5359 ** interface should also return 1 when given a NULL pointer.
5360 */
5361 #ifndef NDEBUG
5362 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5363 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5364 #endif
5365
5366 /*
5367 ** CAPI3REF: Mutex Types
5368 **
5369 ** The [sqlite3_mutex_alloc()] interface takes a single argument
5370 ** which is one of these integer constants.
5371 **
5372 ** The set of static mutexes may change from one SQLite release to the
5373 ** next.  Applications that override the built-in mutex logic must be
5374 ** prepared to accommodate additional static mutexes.
5375 */
5376 #define SQLITE_MUTEX_FAST             0
5377 #define SQLITE_MUTEX_RECURSIVE        1
5378 #define SQLITE_MUTEX_STATIC_MASTER    2
5379 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5380 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
5381 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
5382 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5383 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5384 #define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
5385
5386 /*
5387 ** CAPI3REF: Retrieve the mutex for a database connection
5388 **
5389 ** ^This interface returns a pointer the [sqlite3_mutex] object that 
5390 ** serializes access to the [database connection] given in the argument
5391 ** when the [threading mode] is Serialized.
5392 ** ^If the [threading mode] is Single-thread or Multi-thread then this
5393 ** routine returns a NULL pointer.
5394 */
5395 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
5396
5397 /*
5398 ** CAPI3REF: Low-Level Control Of Database Files
5399 **
5400 ** ^The [sqlite3_file_control()] interface makes a direct call to the
5401 ** xFileControl method for the [sqlite3_io_methods] object associated
5402 ** with a particular database identified by the second argument. ^The
5403 ** name of the database "main" for the main database or "temp" for the
5404 ** TEMP database, or the name that appears after the AS keyword for
5405 ** databases that are added using the [ATTACH] SQL command.
5406 ** ^A NULL pointer can be used in place of "main" to refer to the
5407 ** main database file.
5408 ** ^The third and fourth parameters to this routine
5409 ** are passed directly through to the second and third parameters of
5410 ** the xFileControl method.  ^The return value of the xFileControl
5411 ** method becomes the return value of this routine.
5412 **
5413 ** ^If the second parameter (zDbName) does not match the name of any
5414 ** open database file, then SQLITE_ERROR is returned.  ^This error
5415 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
5416 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
5417 ** also return SQLITE_ERROR.  There is no way to distinguish between
5418 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5419 ** xFileControl method.
5420 **
5421 ** See also: [SQLITE_FCNTL_LOCKSTATE]
5422 */
5423 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5424
5425 /*
5426 ** CAPI3REF: Testing Interface
5427 **
5428 ** ^The sqlite3_test_control() interface is used to read out internal
5429 ** state of SQLite and to inject faults into SQLite for testing
5430 ** purposes.  ^The first parameter is an operation code that determines
5431 ** the number, meaning, and operation of all subsequent parameters.
5432 **
5433 ** This interface is not for use by applications.  It exists solely
5434 ** for verifying the correct operation of the SQLite library.  Depending
5435 ** on how the SQLite library is compiled, this interface might not exist.
5436 **
5437 ** The details of the operation codes, their meanings, the parameters
5438 ** they take, and what they do are all subject to change without notice.
5439 ** Unlike most of the SQLite API, this function is not guaranteed to
5440 ** operate consistently from one release to the next.
5441 */
5442 SQLITE_API int sqlite3_test_control(int op, ...);
5443
5444 /*
5445 ** CAPI3REF: Testing Interface Operation Codes
5446 **
5447 ** These constants are the valid operation code parameters used
5448 ** as the first argument to [sqlite3_test_control()].
5449 **
5450 ** These parameters and their meanings are subject to change
5451 ** without notice.  These values are for testing purposes only.
5452 ** Applications should not use any of these parameters or the
5453 ** [sqlite3_test_control()] interface.
5454 */
5455 #define SQLITE_TESTCTRL_FIRST                    5
5456 #define SQLITE_TESTCTRL_PRNG_SAVE                5
5457 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
5458 #define SQLITE_TESTCTRL_PRNG_RESET               7
5459 #define SQLITE_TESTCTRL_BITVEC_TEST              8
5460 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
5461 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
5462 #define SQLITE_TESTCTRL_PENDING_BYTE            11
5463 #define SQLITE_TESTCTRL_ASSERT                  12
5464 #define SQLITE_TESTCTRL_ALWAYS                  13
5465 #define SQLITE_TESTCTRL_RESERVE                 14
5466 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5467 #define SQLITE_TESTCTRL_ISKEYWORD               16
5468 #define SQLITE_TESTCTRL_LAST                    16
5469
5470 /*
5471 ** CAPI3REF: SQLite Runtime Status
5472 ** EXPERIMENTAL
5473 **
5474 ** ^This interface is used to retrieve runtime status information
5475 ** about the preformance of SQLite, and optionally to reset various
5476 ** highwater marks.  ^The first argument is an integer code for
5477 ** the specific parameter to measure.  ^(Recognized integer codes
5478 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5479 ** ^The current value of the parameter is returned into *pCurrent.
5480 ** ^The highest recorded value is returned in *pHighwater.  ^If the
5481 ** resetFlag is true, then the highest record value is reset after
5482 ** *pHighwater is written.  ^(Some parameters do not record the highest
5483 ** value.  For those parameters
5484 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
5485 ** ^(Other parameters record only the highwater mark and not the current
5486 ** value.  For these latter parameters nothing is written into *pCurrent.)^
5487 **
5488 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5489 ** non-zero [error code] on failure.
5490 **
5491 ** This routine is threadsafe but is not atomic.  This routine can be
5492 ** called while other threads are running the same or different SQLite
5493 ** interfaces.  However the values returned in *pCurrent and
5494 ** *pHighwater reflect the status of SQLite at different points in time
5495 ** and it is possible that another thread might change the parameter
5496 ** in between the times when *pCurrent and *pHighwater are written.
5497 **
5498 ** See also: [sqlite3_db_status()]
5499 */
5500 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5501
5502
5503 /*
5504 ** CAPI3REF: Status Parameters
5505 ** EXPERIMENTAL
5506 **
5507 ** These integer constants designate various run-time status parameters
5508 ** that can be returned by [sqlite3_status()].
5509 **
5510 ** <dl>
5511 ** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
5512 ** <dd>This parameter is the current amount of memory checked out
5513 ** using [sqlite3_malloc()], either directly or indirectly.  The
5514 ** figure includes calls made to [sqlite3_malloc()] by the application
5515 ** and internal memory usage by the SQLite library.  Scratch memory
5516 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
5517 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
5518 ** this parameter.  The amount returned is the sum of the allocation
5519 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
5520 **
5521 ** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
5522 ** <dd>This parameter records the largest memory allocation request
5523 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
5524 ** internal equivalents).  Only the value returned in the
5525 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5526 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5527 **
5528 ** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
5529 ** <dd>This parameter returns the number of pages used out of the
5530 ** [pagecache memory allocator] that was configured using 
5531 ** [SQLITE_CONFIG_PAGECACHE].  The
5532 ** value returned is in pages, not in bytes.</dd>)^
5533 **
5534 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
5535 ** <dd>This parameter returns the number of bytes of page cache
5536 ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
5537 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
5538 ** returned value includes allocations that overflowed because they
5539 ** where too large (they were larger than the "sz" parameter to
5540 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
5541 ** no space was left in the page cache.</dd>)^
5542 **
5543 ** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
5544 ** <dd>This parameter records the largest memory allocation request
5545 ** handed to [pagecache memory allocator].  Only the value returned in the
5546 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5547 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5548 **
5549 ** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
5550 ** <dd>This parameter returns the number of allocations used out of the
5551 ** [scratch memory allocator] configured using
5552 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
5553 ** in bytes.  Since a single thread may only have one scratch allocation
5554 ** outstanding at time, this parameter also reports the number of threads
5555 ** using scratch memory at the same time.</dd>)^
5556 **
5557 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
5558 ** <dd>This parameter returns the number of bytes of scratch memory
5559 ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
5560 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
5561 ** returned include overflows because the requested allocation was too
5562 ** larger (that is, because the requested allocation was larger than the
5563 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
5564 ** slots were available.
5565 ** </dd>)^
5566 **
5567 ** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
5568 ** <dd>This parameter records the largest memory allocation request
5569 ** handed to [scratch memory allocator].  Only the value returned in the
5570 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5571 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5572 **
5573 ** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
5574 ** <dd>This parameter records the deepest parser stack.  It is only
5575 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
5576 ** </dl>
5577 **
5578 ** New status parameters may be added from time to time.
5579 */
5580 #define SQLITE_STATUS_MEMORY_USED          0
5581 #define SQLITE_STATUS_PAGECACHE_USED       1
5582 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
5583 #define SQLITE_STATUS_SCRATCH_USED         3
5584 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
5585 #define SQLITE_STATUS_MALLOC_SIZE          5
5586 #define SQLITE_STATUS_PARSER_STACK         6
5587 #define SQLITE_STATUS_PAGECACHE_SIZE       7
5588 #define SQLITE_STATUS_SCRATCH_SIZE         8
5589
5590 /*
5591 ** CAPI3REF: Database Connection Status
5592 ** EXPERIMENTAL
5593 **
5594 ** ^This interface is used to retrieve runtime status information 
5595 ** about a single [database connection].  ^The first argument is the
5596 ** database connection object to be interrogated.  ^The second argument
5597 ** is the parameter to interrogate.  ^Currently, the only allowed value
5598 ** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
5599 ** Additional options will likely appear in future releases of SQLite.
5600 **
5601 ** ^The current value of the requested parameter is written into *pCur
5602 ** and the highest instantaneous value is written into *pHiwtr.  ^If
5603 ** the resetFlg is true, then the highest instantaneous value is
5604 ** reset back down to the current value.
5605 **
5606 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5607 */
5608 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5609
5610 /*
5611 ** CAPI3REF: Status Parameters for database connections
5612 ** EXPERIMENTAL
5613 **
5614 ** These constants are the available integer "verbs" that can be passed as
5615 ** the second argument to the [sqlite3_db_status()] interface.
5616 **
5617 ** New verbs may be added in future releases of SQLite. Existing verbs
5618 ** might be discontinued. Applications should check the return code from
5619 ** [sqlite3_db_status()] to make sure that the call worked.
5620 ** The [sqlite3_db_status()] interface will return a non-zero error code
5621 ** if a discontinued or unsupported verb is invoked.
5622 **
5623 ** <dl>
5624 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
5625 ** <dd>This parameter returns the number of lookaside memory slots currently
5626 ** checked out.</dd>)^
5627 ** </dl>
5628 */
5629 #define SQLITE_DBSTATUS_LOOKASIDE_USED     0
5630
5631
5632 /*
5633 ** CAPI3REF: Prepared Statement Status
5634 ** EXPERIMENTAL
5635 **
5636 ** ^(Each prepared statement maintains various
5637 ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
5638 ** of times it has performed specific operations.)^  These counters can
5639 ** be used to monitor the performance characteristics of the prepared
5640 ** statements.  For example, if the number of table steps greatly exceeds
5641 ** the number of table searches or result rows, that would tend to indicate
5642 ** that the prepared statement is using a full table scan rather than
5643 ** an index.  
5644 **
5645 ** ^(This interface is used to retrieve and reset counter values from
5646 ** a [prepared statement].  The first argument is the prepared statement
5647 ** object to be interrogated.  The second argument
5648 ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
5649 ** to be interrogated.)^
5650 ** ^The current value of the requested counter is returned.
5651 ** ^If the resetFlg is true, then the counter is reset to zero after this
5652 ** interface call returns.
5653 **
5654 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
5655 */
5656 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
5657
5658 /*
5659 ** CAPI3REF: Status Parameters for prepared statements
5660 ** EXPERIMENTAL
5661 **
5662 ** These preprocessor macros define integer codes that name counter
5663 ** values associated with the [sqlite3_stmt_status()] interface.
5664 ** The meanings of the various counters are as follows:
5665 **
5666 ** <dl>
5667 ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
5668 ** <dd>^This is the number of times that SQLite has stepped forward in
5669 ** a table as part of a full table scan.  Large numbers for this counter
5670 ** may indicate opportunities for performance improvement through 
5671 ** careful use of indices.</dd>
5672 **
5673 ** <dt>SQLITE_STMTSTATUS_SORT</dt>
5674 ** <dd>^This is the number of sort operations that have occurred.
5675 ** A non-zero value in this counter may indicate an opportunity to
5676 ** improvement performance through careful use of indices.</dd>
5677 **
5678 ** </dl>
5679 */
5680 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
5681 #define SQLITE_STMTSTATUS_SORT              2
5682
5683 /*
5684 ** CAPI3REF: Custom Page Cache Object
5685 ** EXPERIMENTAL
5686 **
5687 ** The sqlite3_pcache type is opaque.  It is implemented by
5688 ** the pluggable module.  The SQLite core has no knowledge of
5689 ** its size or internal structure and never deals with the
5690 ** sqlite3_pcache object except by holding and passing pointers
5691 ** to the object.
5692 **
5693 ** See [sqlite3_pcache_methods] for additional information.
5694 */
5695 typedef struct sqlite3_pcache sqlite3_pcache;
5696
5697 /*
5698 ** CAPI3REF: Application Defined Page Cache.
5699 ** KEYWORDS: {page cache}
5700 ** EXPERIMENTAL
5701 **
5702 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
5703 ** register an alternative page cache implementation by passing in an 
5704 ** instance of the sqlite3_pcache_methods structure.)^ The majority of the 
5705 ** heap memory used by SQLite is used by the page cache to cache data read 
5706 ** from, or ready to be written to, the database file. By implementing a 
5707 ** custom page cache using this API, an application can control more 
5708 ** precisely the amount of memory consumed by SQLite, the way in which 
5709 ** that memory is allocated and released, and the policies used to 
5710 ** determine exactly which parts of a database file are cached and for 
5711 ** how long.
5712 **
5713 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
5714 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
5715 ** the application may discard the parameter after the call to
5716 ** [sqlite3_config()] returns.)^
5717 **
5718 ** ^The xInit() method is called once for each call to [sqlite3_initialize()]
5719 ** (usually only once during the lifetime of the process). ^(The xInit()
5720 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
5721 ** ^The xInit() method can set up up global structures and/or any mutexes
5722 ** required by the custom page cache implementation. 
5723 **
5724 ** ^The xShutdown() method is called from within [sqlite3_shutdown()], 
5725 ** if the application invokes this API. It can be used to clean up 
5726 ** any outstanding resources before process shutdown, if required.
5727 **
5728 ** ^SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
5729 ** the xInit method, so the xInit method need not be threadsafe.  ^The
5730 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
5731 ** not need to be threadsafe either.  All other methods must be threadsafe
5732 ** in multithreaded applications.
5733 **
5734 ** ^SQLite will never invoke xInit() more than once without an intervening
5735 ** call to xShutdown().
5736 **
5737 ** ^The xCreate() method is used to construct a new cache instance.  SQLite
5738 ** will typically create one cache instance for each open database file,
5739 ** though this is not guaranteed. ^The
5740 ** first parameter, szPage, is the size in bytes of the pages that must
5741 ** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
5742 ** will the page size of the database file that is to be cached plus an
5743 ** increment (here called "R") of about 100 or 200.  ^SQLite will use the
5744 ** extra R bytes on each page to store metadata about the underlying
5745 ** database page on disk.  The value of R depends
5746 ** on the SQLite version, the target platform, and how SQLite was compiled.
5747 ** ^R is constant for a particular build of SQLite.  ^The second argument to
5748 ** xCreate(), bPurgeable, is true if the cache being created will
5749 ** be used to cache database pages of a file stored on disk, or
5750 ** false if it is used for an in-memory database. ^The cache implementation
5751 ** does not have to do anything special based with the value of bPurgeable;
5752 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
5753 ** never invoke xUnpin() except to deliberately delete a page.
5754 ** ^In other words, a cache created with bPurgeable set to false will
5755 ** never contain any unpinned pages.
5756 **
5757 ** ^(The xCachesize() method may be called at any time by SQLite to set the
5758 ** suggested maximum cache-size (number of pages stored by) the cache
5759 ** instance passed as the first argument. This is the value configured using
5760 ** the SQLite "[PRAGMA cache_size]" command.)^  ^As with the bPurgeable
5761 ** parameter, the implementation is not required to do anything with this
5762 ** value; it is advisory only.
5763 **
5764 ** ^The xPagecount() method should return the number of pages currently
5765 ** stored in the cache.
5766 ** 
5767 ** ^The xFetch() method is used to fetch a page and return a pointer to it. 
5768 ** ^A 'page', in this context, is a buffer of szPage bytes aligned at an
5769 ** 8-byte boundary. ^The page to be fetched is determined by the key. ^The
5770 ** mimimum key value is 1. After it has been retrieved using xFetch, the page 
5771 ** is considered to be "pinned".
5772 **
5773 ** ^If the requested page is already in the page cache, then the page cache
5774 ** implementation must return a pointer to the page buffer with its content
5775 ** intact.  ^(If the requested page is not already in the cache, then the
5776 ** behavior of the cache implementation is determined by the value of the
5777 ** createFlag parameter passed to xFetch, according to the following table:
5778 **
5779 ** <table border=1 width=85% align=center>
5780 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
5781 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
5782 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
5783 **                 Otherwise return NULL.
5784 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
5785 **                 NULL if allocating a new page is effectively impossible.
5786 ** </table>)^
5787 **
5788 ** SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  If
5789 ** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
5790 ** attempt to unpin one or more cache pages by spilling the content of
5791 ** pinned pages to disk and synching the operating system disk cache. After
5792 ** attempting to unpin pages, the xFetch() method will be invoked again with
5793 ** a createFlag of 2.
5794 **
5795 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
5796 ** as its second argument. ^(If the third parameter, discard, is non-zero,
5797 ** then the page should be evicted from the cache. In this case SQLite 
5798 ** assumes that the next time the page is retrieved from the cache using
5799 ** the xFetch() method, it will be zeroed.)^ ^If the discard parameter is
5800 ** zero, then the page is considered to be unpinned. ^The cache implementation
5801 ** may choose to evict unpinned pages at any time.
5802 **
5803 ** ^(The cache is not required to perform any reference counting. A single 
5804 ** call to xUnpin() unpins the page regardless of the number of prior calls 
5805 ** to xFetch().)^
5806 **
5807 ** ^The xRekey() method is used to change the key value associated with the
5808 ** page passed as the second argument from oldKey to newKey. ^If the cache
5809 ** previously contains an entry associated with newKey, it should be
5810 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
5811 ** to be pinned.
5812 **
5813 ** ^When SQLite calls the xTruncate() method, the cache must discard all
5814 ** existing cache entries with page numbers (keys) greater than or equal
5815 ** to the value of the iLimit parameter passed to xTruncate(). ^If any
5816 ** of these pages are pinned, they are implicitly unpinned, meaning that
5817 ** they can be safely discarded.
5818 **
5819 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
5820 ** All resources associated with the specified cache should be freed. ^After
5821 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
5822 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
5823 ** functions.
5824 */
5825 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
5826 struct sqlite3_pcache_methods {
5827   void *pArg;
5828   int (*xInit)(void*);
5829   void (*xShutdown)(void*);
5830   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
5831   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
5832   int (*xPagecount)(sqlite3_pcache*);
5833   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
5834   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
5835   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
5836   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
5837   void (*xDestroy)(sqlite3_pcache*);
5838 };
5839
5840 /*
5841 ** CAPI3REF: Online Backup Object
5842 ** EXPERIMENTAL
5843 **
5844 ** The sqlite3_backup object records state information about an ongoing
5845 ** online backup operation.  ^The sqlite3_backup object is created by
5846 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
5847 ** [sqlite3_backup_finish()].
5848 **
5849 ** See Also: [Using the SQLite Online Backup API]
5850 */
5851 typedef struct sqlite3_backup sqlite3_backup;
5852
5853 /*
5854 ** CAPI3REF: Online Backup API.
5855 ** EXPERIMENTAL
5856 **
5857 ** The backup API copies the content of one database into another.
5858 ** It is useful either for creating backups of databases or
5859 ** for copying in-memory databases to or from persistent files. 
5860 **
5861 ** See Also: [Using the SQLite Online Backup API]
5862 **
5863 ** ^Exclusive access is required to the destination database for the 
5864 ** duration of the operation. ^However the source database is only
5865 ** read-locked while it is actually being read; it is not locked
5866 ** continuously for the entire backup operation. ^Thus, the backup may be
5867 ** performed on a live source database without preventing other users from
5868 ** reading or writing to the source database while the backup is underway.
5869 ** 
5870 ** ^(To perform a backup operation: 
5871 **   <ol>
5872 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
5873 **         backup, 
5874 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
5875 **         the data between the two databases, and finally
5876 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
5877 **         associated with the backup operation. 
5878 **   </ol>)^
5879 ** There should be exactly one call to sqlite3_backup_finish() for each
5880 ** successful call to sqlite3_backup_init().
5881 **
5882 ** <b>sqlite3_backup_init()</b>
5883 **
5884 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
5885 ** [database connection] associated with the destination database 
5886 ** and the database name, respectively.
5887 ** ^The database name is "main" for the main database, "temp" for the
5888 ** temporary database, or the name specified after the AS keyword in
5889 ** an [ATTACH] statement for an attached database.
5890 ** ^The S and M arguments passed to 
5891 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
5892 ** and database name of the source database, respectively.
5893 ** ^The source and destination [database connections] (parameters S and D)
5894 ** must be different or else sqlite3_backup_init(D,N,S,M) will file with
5895 ** an error.
5896 **
5897 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
5898 ** returned and an error code and error message are store3d in the
5899 ** destination [database connection] D.
5900 ** ^The error code and message for the failed call to sqlite3_backup_init()
5901 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
5902 ** [sqlite3_errmsg16()] functions.
5903 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
5904 ** [sqlite3_backup] object.
5905 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
5906 ** sqlite3_backup_finish() functions to perform the specified backup 
5907 ** operation.
5908 **
5909 ** <b>sqlite3_backup_step()</b>
5910 **
5911 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
5912 ** the source and destination databases specified by [sqlite3_backup] object B.
5913 ** ^If N is negative, all remaining source pages are copied. 
5914 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
5915 ** are still more pages to be copied, then the function resturns [SQLITE_OK].
5916 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
5917 ** from source to destination, then it returns [SQLITE_DONE].
5918 ** ^If an error occurs while running sqlite3_backup_step(B,N),
5919 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
5920 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
5921 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
5922 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
5923 **
5924 ** ^The sqlite3_backup_step() might return [SQLITE_READONLY] if the destination
5925 ** database was opened read-only or if
5926 ** the destination is an in-memory database with a different page size
5927 ** from the source database.
5928 **
5929 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
5930 ** the [sqlite3_busy_handler | busy-handler function]
5931 ** is invoked (if one is specified). ^If the 
5932 ** busy-handler returns non-zero before the lock is available, then 
5933 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
5934 ** sqlite3_backup_step() can be retried later. ^If the source
5935 ** [database connection]
5936 ** is being used to write to the source database when sqlite3_backup_step()
5937 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
5938 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
5939 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
5940 ** [SQLITE_READONLY] is returned, then 
5941 ** there is no point in retrying the call to sqlite3_backup_step(). These 
5942 ** errors are considered fatal.)^  The application must accept 
5943 ** that the backup operation has failed and pass the backup operation handle 
5944 ** to the sqlite3_backup_finish() to release associated resources.
5945 **
5946 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
5947 ** on the destination file. ^The exclusive lock is not released until either 
5948 ** sqlite3_backup_finish() is called or the backup operation is complete 
5949 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
5950 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
5951 ** lasts for the duration of the sqlite3_backup_step() call.
5952 ** ^Because the source database is not locked between calls to
5953 ** sqlite3_backup_step(), the source database may be modified mid-way
5954 ** through the backup process.  ^If the source database is modified by an
5955 ** external process or via a database connection other than the one being
5956 ** used by the backup operation, then the backup will be automatically
5957 ** restarted by the next call to sqlite3_backup_step(). ^If the source 
5958 ** database is modified by the using the same database connection as is used
5959 ** by the backup operation, then the backup database is automatically
5960 ** updated at the same time.
5961 **
5962 ** <b>sqlite3_backup_finish()</b>
5963 **
5964 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
5965 ** application wishes to abandon the backup operation, the application
5966 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
5967 ** ^The sqlite3_backup_finish() interfaces releases all
5968 ** resources associated with the [sqlite3_backup] object. 
5969 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
5970 ** active write-transaction on the destination database is rolled back.
5971 ** The [sqlite3_backup] object is invalid
5972 ** and may not be used following a call to sqlite3_backup_finish().
5973 **
5974 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
5975 ** sqlite3_backup_step() errors occurred, regardless or whether or not
5976 ** sqlite3_backup_step() completed.
5977 ** ^If an out-of-memory condition or IO error occurred during any prior
5978 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
5979 ** sqlite3_backup_finish() returns the corresponding [error code].
5980 **
5981 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
5982 ** is not a permanent error and does not affect the return value of
5983 ** sqlite3_backup_finish().
5984 **
5985 ** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
5986 **
5987 ** ^Each call to sqlite3_backup_step() sets two values inside
5988 ** the [sqlite3_backup] object: the number of pages still to be backed
5989 ** up and the total number of pages in the source databae file.
5990 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
5991 ** retrieve these two values, respectively.
5992 **
5993 ** ^The values returned by these functions are only updated by
5994 ** sqlite3_backup_step(). ^If the source database is modified during a backup
5995 ** operation, then the values are not updated to account for any extra
5996 ** pages that need to be updated or the size of the source database file
5997 ** changing.
5998 **
5999 ** <b>Concurrent Usage of Database Handles</b>
6000 **
6001 ** ^The source [database connection] may be used by the application for other
6002 ** purposes while a backup operation is underway or being initialized.
6003 ** ^If SQLite is compiled and configured to support threadsafe database
6004 ** connections, then the source database connection may be used concurrently
6005 ** from within other threads.
6006 **
6007 ** However, the application must guarantee that the destination 
6008 ** [database connection] is not passed to any other API (by any thread) after 
6009 ** sqlite3_backup_init() is called and before the corresponding call to
6010 ** sqlite3_backup_finish().  SQLite does not currently check to see
6011 ** if the application incorrectly accesses the destination [database connection]
6012 ** and so no error code is reported, but the operations may malfunction
6013 ** nevertheless.  Use of the destination database connection while a
6014 ** backup is in progress might also also cause a mutex deadlock.
6015 **
6016 ** If running in [shared cache mode], the application must
6017 ** guarantee that the shared cache used by the destination database
6018 ** is not accessed while the backup is running. In practice this means
6019 ** that the application must guarantee that the disk file being 
6020 ** backed up to is not accessed by any connection within the process,
6021 ** not just the specific connection that was passed to sqlite3_backup_init().
6022 **
6023 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
6024 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6025 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6026 ** APIs are not strictly speaking threadsafe. If they are invoked at the
6027 ** same time as another thread is invoking sqlite3_backup_step() it is
6028 ** possible that they return invalid values.
6029 */
6030 SQLITE_API sqlite3_backup *sqlite3_backup_init(
6031   sqlite3 *pDest,                        /* Destination database handle */
6032   const char *zDestName,                 /* Destination database name */
6033   sqlite3 *pSource,                      /* Source database handle */
6034   const char *zSourceName                /* Source database name */
6035 );
6036 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6037 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6038 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6039 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6040
6041 /*
6042 ** CAPI3REF: Unlock Notification
6043 ** EXPERIMENTAL
6044 **
6045 ** ^When running in shared-cache mode, a database operation may fail with
6046 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6047 ** individual tables within the shared-cache cannot be obtained. See
6048 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
6049 ** ^This API may be used to register a callback that SQLite will invoke 
6050 ** when the connection currently holding the required lock relinquishes it.
6051 ** ^This API is only available if the library was compiled with the
6052 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6053 **
6054 ** See Also: [Using the SQLite Unlock Notification Feature].
6055 **
6056 ** ^Shared-cache locks are released when a database connection concludes
6057 ** its current transaction, either by committing it or rolling it back. 
6058 **
6059 ** ^When a connection (known as the blocked connection) fails to obtain a
6060 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6061 ** identity of the database connection (the blocking connection) that
6062 ** has locked the required resource is stored internally. ^After an 
6063 ** application receives an SQLITE_LOCKED error, it may call the
6064 ** sqlite3_unlock_notify() method with the blocked connection handle as 
6065 ** the first argument to register for a callback that will be invoked
6066 ** when the blocking connections current transaction is concluded. ^The
6067 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6068 ** call that concludes the blocking connections transaction.
6069 **
6070 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6071 ** there is a chance that the blocking connection will have already
6072 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6073 ** If this happens, then the specified callback is invoked immediately,
6074 ** from within the call to sqlite3_unlock_notify().)^
6075 **
6076 ** ^If the blocked connection is attempting to obtain a write-lock on a
6077 ** shared-cache table, and more than one other connection currently holds
6078 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
6079 ** the other connections to use as the blocking connection.
6080 **
6081 ** ^(There may be at most one unlock-notify callback registered by a 
6082 ** blocked connection. If sqlite3_unlock_notify() is called when the
6083 ** blocked connection already has a registered unlock-notify callback,
6084 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6085 ** called with a NULL pointer as its second argument, then any existing
6086 ** unlock-notify callback is cancelled. ^The blocked connections 
6087 ** unlock-notify callback may also be canceled by closing the blocked
6088 ** connection using [sqlite3_close()].
6089 **
6090 ** The unlock-notify callback is not reentrant. If an application invokes
6091 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
6092 ** crash or deadlock may be the result.
6093 **
6094 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6095 ** returns SQLITE_OK.
6096 **
6097 ** <b>Callback Invocation Details</b>
6098 **
6099 ** When an unlock-notify callback is registered, the application provides a 
6100 ** single void* pointer that is passed to the callback when it is invoked.
6101 ** However, the signature of the callback function allows SQLite to pass
6102 ** it an array of void* context pointers. The first argument passed to
6103 ** an unlock-notify callback is a pointer to an array of void* pointers,
6104 ** and the second is the number of entries in the array.
6105 **
6106 ** When a blocking connections transaction is concluded, there may be
6107 ** more than one blocked connection that has registered for an unlock-notify
6108 ** callback. ^If two or more such blocked connections have specified the
6109 ** same callback function, then instead of invoking the callback function
6110 ** multiple times, it is invoked once with the set of void* context pointers
6111 ** specified by the blocked connections bundled together into an array.
6112 ** This gives the application an opportunity to prioritize any actions 
6113 ** related to the set of unblocked database connections.
6114 **
6115 ** <b>Deadlock Detection</b>
6116 **
6117 ** Assuming that after registering for an unlock-notify callback a 
6118 ** database waits for the callback to be issued before taking any further
6119 ** action (a reasonable assumption), then using this API may cause the
6120 ** application to deadlock. For example, if connection X is waiting for
6121 ** connection Y's transaction to be concluded, and similarly connection
6122 ** Y is waiting on connection X's transaction, then neither connection
6123 ** will proceed and the system may remain deadlocked indefinitely.
6124 **
6125 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6126 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
6127 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6128 ** unlock-notify callback is registered. The system is said to be in
6129 ** a deadlocked state if connection A has registered for an unlock-notify
6130 ** callback on the conclusion of connection B's transaction, and connection
6131 ** B has itself registered for an unlock-notify callback when connection
6132 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
6133 ** the system is also considered to be deadlocked if connection B has
6134 ** registered for an unlock-notify callback on the conclusion of connection
6135 ** C's transaction, where connection C is waiting on connection A. ^Any
6136 ** number of levels of indirection are allowed.
6137 **
6138 ** <b>The "DROP TABLE" Exception</b>
6139 **
6140 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
6141 ** always appropriate to call sqlite3_unlock_notify(). There is however,
6142 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6143 ** SQLite checks if there are any currently executing SELECT statements
6144 ** that belong to the same connection. If there are, SQLITE_LOCKED is
6145 ** returned. In this case there is no "blocking connection", so invoking
6146 ** sqlite3_unlock_notify() results in the unlock-notify callback being
6147 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
6148 ** or "DROP INDEX" query, an infinite loop might be the result.
6149 **
6150 ** One way around this problem is to check the extended error code returned
6151 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6152 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6153 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
6154 ** SQLITE_LOCKED.)^
6155 */
6156 SQLITE_API int sqlite3_unlock_notify(
6157   sqlite3 *pBlocked,                          /* Waiting connection */
6158   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6159   void *pNotifyArg                            /* Argument to pass to xNotify */
6160 );
6161
6162
6163 /*
6164 ** CAPI3REF: String Comparison
6165 ** EXPERIMENTAL
6166 **
6167 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6168 ** compare the contents of two buffers containing UTF-8 strings in a
6169 ** case-indendent fashion, using the same definition of case independence 
6170 ** that SQLite uses internally when comparing identifiers.
6171 */
6172 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6173
6174 /*
6175 ** Undo the hack that converts floating point types to integer for
6176 ** builds on processors without floating point support.
6177 */
6178 #ifdef SQLITE_OMIT_FLOATING_POINT
6179 # undef double
6180 #endif
6181
6182 #if 0
6183 }  /* End of the 'extern "C"' block */
6184 #endif
6185 #endif
6186
6187
6188 /************** End of sqlite3.h *********************************************/
6189 /************** Continuing where we left off in sqliteInt.h ******************/
6190 /************** Include hash.h in the middle of sqliteInt.h ******************/
6191 /************** Begin file hash.h ********************************************/
6192 /*
6193 ** 2001 September 22
6194 **
6195 ** The author disclaims copyright to this source code.  In place of
6196 ** a legal notice, here is a blessing:
6197 **
6198 **    May you do good and not evil.
6199 **    May you find forgiveness for yourself and forgive others.
6200 **    May you share freely, never taking more than you give.
6201 **
6202 *************************************************************************
6203 ** This is the header file for the generic hash-table implemenation
6204 ** used in SQLite.
6205 */
6206 #ifndef _SQLITE_HASH_H_
6207 #define _SQLITE_HASH_H_
6208
6209 /* Forward declarations of structures. */
6210 typedef struct Hash Hash;
6211 typedef struct HashElem HashElem;
6212
6213 /* A complete hash table is an instance of the following structure.
6214 ** The internals of this structure are intended to be opaque -- client
6215 ** code should not attempt to access or modify the fields of this structure
6216 ** directly.  Change this structure only by using the routines below.
6217 ** However, some of the "procedures" and "functions" for modifying and
6218 ** accessing this structure are really macros, so we can't really make
6219 ** this structure opaque.
6220 **
6221 ** All elements of the hash table are on a single doubly-linked list.
6222 ** Hash.first points to the head of this list.
6223 **
6224 ** There are Hash.htsize buckets.  Each bucket points to a spot in
6225 ** the global doubly-linked list.  The contents of the bucket are the
6226 ** element pointed to plus the next _ht.count-1 elements in the list.
6227 **
6228 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
6229 ** by a linear search of the global list.  For small tables, the 
6230 ** Hash.ht table is never allocated because if there are few elements
6231 ** in the table, it is faster to do a linear search than to manage
6232 ** the hash table.
6233 */
6234 struct Hash {
6235   unsigned int htsize;      /* Number of buckets in the hash table */
6236   unsigned int count;       /* Number of entries in this table */
6237   HashElem *first;          /* The first element of the array */
6238   struct _ht {              /* the hash table */
6239     int count;                 /* Number of entries with this hash */
6240     HashElem *chain;           /* Pointer to first entry with this hash */
6241   } *ht;
6242 };
6243
6244 /* Each element in the hash table is an instance of the following 
6245 ** structure.  All elements are stored on a single doubly-linked list.
6246 **
6247 ** Again, this structure is intended to be opaque, but it can't really
6248 ** be opaque because it is used by macros.
6249 */
6250 struct HashElem {
6251   HashElem *next, *prev;       /* Next and previous elements in the table */
6252   void *data;                  /* Data associated with this element */
6253   const char *pKey; int nKey;  /* Key associated with this element */
6254 };
6255
6256 /*
6257 ** Access routines.  To delete, insert a NULL pointer.
6258 */
6259 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
6260 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
6261 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
6262 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6263
6264 /*
6265 ** Macros for looping over all elements of a hash table.  The idiom is
6266 ** like this:
6267 **
6268 **   Hash h;
6269 **   HashElem *p;
6270 **   ...
6271 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
6272 **     SomeStructure *pData = sqliteHashData(p);
6273 **     // do something with pData
6274 **   }
6275 */
6276 #define sqliteHashFirst(H)  ((H)->first)
6277 #define sqliteHashNext(E)   ((E)->next)
6278 #define sqliteHashData(E)   ((E)->data)
6279 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
6280 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
6281
6282 /*
6283 ** Number of entries in a hash table
6284 */
6285 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
6286
6287 #endif /* _SQLITE_HASH_H_ */
6288
6289 /************** End of hash.h ************************************************/
6290 /************** Continuing where we left off in sqliteInt.h ******************/
6291 /************** Include parse.h in the middle of sqliteInt.h *****************/
6292 /************** Begin file parse.h *******************************************/
6293 #define TK_SEMI                            1
6294 #define TK_EXPLAIN                         2
6295 #define TK_QUERY                           3
6296 #define TK_PLAN                            4
6297 #define TK_BEGIN                           5
6298 #define TK_TRANSACTION                     6
6299 #define TK_DEFERRED                        7
6300 #define TK_IMMEDIATE                       8
6301 #define TK_EXCLUSIVE                       9
6302 #define TK_COMMIT                         10
6303 #define TK_END                            11
6304 #define TK_ROLLBACK                       12
6305 #define TK_SAVEPOINT                      13
6306 #define TK_RELEASE                        14
6307 #define TK_TO                             15
6308 #define TK_TABLE                          16
6309 #define TK_CREATE                         17
6310 #define TK_IF                             18
6311 #define TK_NOT                            19
6312 #define TK_EXISTS                         20
6313 #define TK_TEMP                           21
6314 #define TK_LP                             22
6315 #define TK_RP                             23
6316 #define TK_AS                             24
6317 #define TK_COMMA                          25
6318 #define TK_ID                             26
6319 #define TK_INDEXED                        27
6320 #define TK_ABORT                          28
6321 #define TK_ACTION                         29
6322 #define TK_AFTER                          30
6323 #define TK_ANALYZE                        31
6324 #define TK_ASC                            32
6325 #define TK_ATTACH                         33
6326 #define TK_BEFORE                         34
6327 #define TK_BY                             35
6328 #define TK_CASCADE                        36
6329 #define TK_CAST                           37
6330 #define TK_COLUMNKW                       38
6331 #define TK_CONFLICT                       39
6332 #define TK_DATABASE                       40
6333 #define TK_DESC                           41
6334 #define TK_DETACH                         42
6335 #define TK_EACH                           43
6336 #define TK_FAIL                           44
6337 #define TK_FOR                            45
6338 #define TK_IGNORE                         46
6339 #define TK_INITIALLY                      47
6340 #define TK_INSTEAD                        48
6341 #define TK_LIKE_KW                        49
6342 #define TK_MATCH                          50
6343 #define TK_NO                             51
6344 #define TK_KEY                            52
6345 #define TK_OF                             53
6346 #define TK_OFFSET                         54
6347 #define TK_PRAGMA                         55
6348 #define TK_RAISE                          56
6349 #define TK_REPLACE                        57
6350 #define TK_RESTRICT                       58
6351 #define TK_ROW                            59
6352 #define TK_TRIGGER                        60
6353 #define TK_VACUUM                         61
6354 #define TK_VIEW                           62
6355 #define TK_VIRTUAL                        63
6356 #define TK_REINDEX                        64
6357 #define TK_RENAME                         65
6358 #define TK_CTIME_KW                       66
6359 #define TK_ANY                            67
6360 #define TK_OR                             68
6361 #define TK_AND                            69
6362 #define TK_IS                             70
6363 #define TK_BETWEEN                        71
6364 #define TK_IN                             72
6365 #define TK_ISNULL                         73
6366 #define TK_NOTNULL                        74
6367 #define TK_NE                             75
6368 #define TK_EQ                             76
6369 #define TK_GT                             77
6370 #define TK_LE                             78
6371 #define TK_LT                             79
6372 #define TK_GE                             80
6373 #define TK_ESCAPE                         81
6374 #define TK_BITAND                         82
6375 #define TK_BITOR                          83
6376 #define TK_LSHIFT                         84
6377 #define TK_RSHIFT                         85
6378 #define TK_PLUS                           86
6379 #define TK_MINUS                          87
6380 #define TK_STAR                           88
6381 #define TK_SLASH                          89
6382 #define TK_REM                            90
6383 #define TK_CONCAT                         91
6384 #define TK_COLLATE                        92
6385 #define TK_BITNOT                         93
6386 #define TK_STRING                         94
6387 #define TK_JOIN_KW                        95
6388 #define TK_CONSTRAINT                     96
6389 #define TK_DEFAULT                        97
6390 #define TK_NULL                           98
6391 #define TK_PRIMARY                        99
6392 #define TK_UNIQUE                         100
6393 #define TK_CHECK                          101
6394 #define TK_REFERENCES                     102
6395 #define TK_AUTOINCR                       103
6396 #define TK_ON                             104
6397 #define TK_INSERT                         105
6398 #define TK_DELETE                         106
6399 #define TK_UPDATE                         107
6400 #define TK_SET                            108
6401 #define TK_DEFERRABLE                     109
6402 #define TK_FOREIGN                        110
6403 #define TK_DROP                           111
6404 #define TK_UNION                          112
6405 #define TK_ALL                            113
6406 #define TK_EXCEPT                         114
6407 #define TK_INTERSECT                      115
6408 #define TK_SELECT                         116
6409 #define TK_DISTINCT                       117
6410 #define TK_DOT                            118
6411 #define TK_FROM                           119
6412 #define TK_JOIN                           120
6413 #define TK_USING                          121
6414 #define TK_ORDER                          122
6415 #define TK_GROUP                          123
6416 #define TK_HAVING                         124
6417 #define TK_LIMIT                          125
6418 #define TK_WHERE                          126
6419 #define TK_INTO                           127
6420 #define TK_VALUES                         128
6421 #define TK_INTEGER                        129
6422 #define TK_FLOAT                          130
6423 #define TK_BLOB                           131
6424 #define TK_REGISTER                       132
6425 #define TK_VARIABLE                       133
6426 #define TK_CASE                           134
6427 #define TK_WHEN                           135
6428 #define TK_THEN                           136
6429 #define TK_ELSE                           137
6430 #define TK_INDEX                          138
6431 #define TK_ALTER                          139
6432 #define TK_ADD                            140
6433 #define TK_TO_TEXT                        141
6434 #define TK_TO_BLOB                        142
6435 #define TK_TO_NUMERIC                     143
6436 #define TK_TO_INT                         144
6437 #define TK_TO_REAL                        145
6438 #define TK_ISNOT                          146
6439 #define TK_END_OF_FILE                    147
6440 #define TK_ILLEGAL                        148
6441 #define TK_SPACE                          149
6442 #define TK_UNCLOSED_STRING                150
6443 #define TK_FUNCTION                       151
6444 #define TK_COLUMN                         152
6445 #define TK_AGG_FUNCTION                   153
6446 #define TK_AGG_COLUMN                     154
6447 #define TK_CONST_FUNC                     155
6448 #define TK_UMINUS                         156
6449 #define TK_UPLUS                          157
6450
6451 /************** End of parse.h ***********************************************/
6452 /************** Continuing where we left off in sqliteInt.h ******************/
6453 #include <stdio.h>
6454 #include <stdlib.h>
6455 #include <string.h>
6456 #include <assert.h>
6457 #include <stddef.h>
6458
6459 /*
6460 ** If compiling for a processor that lacks floating point support,
6461 ** substitute integer for floating-point
6462 */
6463 #ifdef SQLITE_OMIT_FLOATING_POINT
6464 # define double sqlite_int64
6465 # define LONGDOUBLE_TYPE sqlite_int64
6466 # ifndef SQLITE_BIG_DBL
6467 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
6468 # endif
6469 # define SQLITE_OMIT_DATETIME_FUNCS 1
6470 # define SQLITE_OMIT_TRACE 1
6471 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
6472 # undef SQLITE_HAVE_ISNAN
6473 #endif
6474 #ifndef SQLITE_BIG_DBL
6475 # define SQLITE_BIG_DBL (1e99)
6476 #endif
6477
6478 /*
6479 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
6480 ** afterward. Having this macro allows us to cause the C compiler 
6481 ** to omit code used by TEMP tables without messy #ifndef statements.
6482 */
6483 #ifdef SQLITE_OMIT_TEMPDB
6484 #define OMIT_TEMPDB 1
6485 #else
6486 #define OMIT_TEMPDB 0
6487 #endif
6488
6489 /*
6490 ** If the following macro is set to 1, then NULL values are considered
6491 ** distinct when determining whether or not two entries are the same
6492 ** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
6493 ** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
6494 ** is the way things are suppose to work.
6495 **
6496 ** If the following macro is set to 0, the NULLs are indistinct for
6497 ** a UNIQUE index.  In this mode, you can only have a single NULL entry
6498 ** for a column declared UNIQUE.  This is the way Informix and SQL Server
6499 ** work.
6500 */
6501 #define NULL_DISTINCT_FOR_UNIQUE 1
6502
6503 /*
6504 ** The "file format" number is an integer that is incremented whenever
6505 ** the VDBE-level file format changes.  The following macros define the
6506 ** the default file format for new databases and the maximum file format
6507 ** that the library can read.
6508 */
6509 #define SQLITE_MAX_FILE_FORMAT 4
6510 #ifndef SQLITE_DEFAULT_FILE_FORMAT
6511 # define SQLITE_DEFAULT_FILE_FORMAT 1
6512 #endif
6513
6514 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
6515 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
6516 #endif
6517
6518 /*
6519 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
6520 ** on the command-line
6521 */
6522 #ifndef SQLITE_TEMP_STORE
6523 # define SQLITE_TEMP_STORE 1
6524 #endif
6525
6526 /*
6527 ** GCC does not define the offsetof() macro so we'll have to do it
6528 ** ourselves.
6529 */
6530 #ifndef offsetof
6531 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
6532 #endif
6533
6534 /*
6535 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
6536 ** not, there are still machines out there that use EBCDIC.)
6537 */
6538 #if 'A' == '\301'
6539 # define SQLITE_EBCDIC 1
6540 #else
6541 # define SQLITE_ASCII 1
6542 #endif
6543
6544 /*
6545 ** Integers of known sizes.  These typedefs might change for architectures
6546 ** where the sizes very.  Preprocessor macros are available so that the
6547 ** types can be conveniently redefined at compile-type.  Like this:
6548 **
6549 **         cc '-DUINTPTR_TYPE=long long int' ...
6550 */
6551 #ifndef UINT32_TYPE
6552 # ifdef HAVE_UINT32_T
6553 #  define UINT32_TYPE uint32_t
6554 # else
6555 #  define UINT32_TYPE unsigned int
6556 # endif
6557 #endif
6558 #ifndef UINT16_TYPE
6559 # ifdef HAVE_UINT16_T
6560 #  define UINT16_TYPE uint16_t
6561 # else
6562 #  define UINT16_TYPE unsigned short int
6563 # endif
6564 #endif
6565 #ifndef INT16_TYPE
6566 # ifdef HAVE_INT16_T
6567 #  define INT16_TYPE int16_t
6568 # else
6569 #  define INT16_TYPE short int
6570 # endif
6571 #endif
6572 #ifndef UINT8_TYPE
6573 # ifdef HAVE_UINT8_T
6574 #  define UINT8_TYPE uint8_t
6575 # else
6576 #  define UINT8_TYPE unsigned char
6577 # endif
6578 #endif
6579 #ifndef INT8_TYPE
6580 # ifdef HAVE_INT8_T
6581 #  define INT8_TYPE int8_t
6582 # else
6583 #  define INT8_TYPE signed char
6584 # endif
6585 #endif
6586 #ifndef LONGDOUBLE_TYPE
6587 # define LONGDOUBLE_TYPE long double
6588 #endif
6589 typedef sqlite_int64 i64;          /* 8-byte signed integer */
6590 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
6591 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
6592 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
6593 typedef INT16_TYPE i16;            /* 2-byte signed integer */
6594 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
6595 typedef INT8_TYPE i8;              /* 1-byte signed integer */
6596
6597 /*
6598 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
6599 ** that can be stored in a u32 without loss of data.  The value
6600 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
6601 ** have to specify the value in the less intuitive manner shown:
6602 */
6603 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
6604
6605 /*
6606 ** Macros to determine whether the machine is big or little endian,
6607 ** evaluated at runtime.
6608 */
6609 #ifdef SQLITE_AMALGAMATION
6610 SQLITE_PRIVATE const int sqlite3one = 1;
6611 #else
6612 SQLITE_PRIVATE const int sqlite3one;
6613 #endif
6614 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
6615                              || defined(__x86_64) || defined(__x86_64__)
6616 # define SQLITE_BIGENDIAN    0
6617 # define SQLITE_LITTLEENDIAN 1
6618 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
6619 #else
6620 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
6621 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
6622 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
6623 #endif
6624
6625 /*
6626 ** Constants for the largest and smallest possible 64-bit signed integers.
6627 ** These macros are designed to work correctly on both 32-bit and 64-bit
6628 ** compilers.
6629 */
6630 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
6631 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
6632
6633 /* 
6634 ** Round up a number to the next larger multiple of 8.  This is used
6635 ** to force 8-byte alignment on 64-bit architectures.
6636 */
6637 #define ROUND8(x)     (((x)+7)&~7)
6638
6639 /*
6640 ** Round down to the nearest multiple of 8
6641 */
6642 #define ROUNDDOWN8(x) ((x)&~7)
6643
6644 /*
6645 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
6646 ** macro is used only within assert() to verify that the code gets
6647 ** all alignment restrictions correct.
6648 **
6649 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
6650 ** underlying malloc() implemention might return us 4-byte aligned
6651 ** pointers.  In that case, only verify 4-byte alignment.
6652 */
6653 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
6654 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
6655 #else
6656 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
6657 #endif
6658
6659
6660 /*
6661 ** An instance of the following structure is used to store the busy-handler
6662 ** callback for a given sqlite handle. 
6663 **
6664 ** The sqlite.busyHandler member of the sqlite struct contains the busy
6665 ** callback for the database handle. Each pager opened via the sqlite
6666 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
6667 ** callback is currently invoked only from within pager.c.
6668 */
6669 typedef struct BusyHandler BusyHandler;
6670 struct BusyHandler {
6671   int (*xFunc)(void *,int);  /* The busy callback */
6672   void *pArg;                /* First arg to busy callback */
6673   int nBusy;                 /* Incremented with each busy call */
6674 };
6675
6676 /*
6677 ** Name of the master database table.  The master database table
6678 ** is a special table that holds the names and attributes of all
6679 ** user tables and indices.
6680 */
6681 #define MASTER_NAME       "sqlite_master"
6682 #define TEMP_MASTER_NAME  "sqlite_temp_master"
6683
6684 /*
6685 ** The root-page of the master database table.
6686 */
6687 #define MASTER_ROOT       1
6688
6689 /*
6690 ** The name of the schema table.
6691 */
6692 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
6693
6694 /*
6695 ** A convenience macro that returns the number of elements in
6696 ** an array.
6697 */
6698 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
6699
6700 /*
6701 ** The following value as a destructor means to use sqlite3DbFree().
6702 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
6703 */
6704 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
6705
6706 /*
6707 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
6708 ** not support Writable Static Data (WSD) such as global and static variables.
6709 ** All variables must either be on the stack or dynamically allocated from
6710 ** the heap.  When WSD is unsupported, the variable declarations scattered
6711 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
6712 ** macro is used for this purpose.  And instead of referencing the variable
6713 ** directly, we use its constant as a key to lookup the run-time allocated
6714 ** buffer that holds real variable.  The constant is also the initializer
6715 ** for the run-time allocated buffer.
6716 **
6717 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
6718 ** macros become no-ops and have zero performance impact.
6719 */
6720 #ifdef SQLITE_OMIT_WSD
6721   #define SQLITE_WSD const
6722   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
6723   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
6724 SQLITE_API   int sqlite3_wsd_init(int N, int J);
6725 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
6726 #else
6727   #define SQLITE_WSD 
6728   #define GLOBAL(t,v) v
6729   #define sqlite3GlobalConfig sqlite3Config
6730 #endif
6731
6732 /*
6733 ** The following macros are used to suppress compiler warnings and to
6734 ** make it clear to human readers when a function parameter is deliberately 
6735 ** left unused within the body of a function. This usually happens when
6736 ** a function is called via a function pointer. For example the 
6737 ** implementation of an SQL aggregate step callback may not use the
6738 ** parameter indicating the number of arguments passed to the aggregate,
6739 ** if it knows that this is enforced elsewhere.
6740 **
6741 ** When a function parameter is not used at all within the body of a function,
6742 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
6743 ** However, these macros may also be used to suppress warnings related to
6744 ** parameters that may or may not be used depending on compilation options.
6745 ** For example those parameters only used in assert() statements. In these
6746 ** cases the parameters are named as per the usual conventions.
6747 */
6748 #define UNUSED_PARAMETER(x) (void)(x)
6749 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
6750
6751 /*
6752 ** Forward references to structures
6753 */
6754 typedef struct AggInfo AggInfo;
6755 typedef struct AuthContext AuthContext;
6756 typedef struct AutoincInfo AutoincInfo;
6757 typedef struct Bitvec Bitvec;
6758 typedef struct RowSet RowSet;
6759 typedef struct CollSeq CollSeq;
6760 typedef struct Column Column;
6761 typedef struct Db Db;
6762 typedef struct Schema Schema;
6763 typedef struct Expr Expr;
6764 typedef struct ExprList ExprList;
6765 typedef struct ExprSpan ExprSpan;
6766 typedef struct FKey FKey;
6767 typedef struct FuncDef FuncDef;
6768 typedef struct FuncDefHash FuncDefHash;
6769 typedef struct IdList IdList;
6770 typedef struct Index Index;
6771 typedef struct IndexSample IndexSample;
6772 typedef struct KeyClass KeyClass;
6773 typedef struct KeyInfo KeyInfo;
6774 typedef struct Lookaside Lookaside;
6775 typedef struct LookasideSlot LookasideSlot;
6776 typedef struct Module Module;
6777 typedef struct NameContext NameContext;
6778 typedef struct Parse Parse;
6779 typedef struct Savepoint Savepoint;
6780 typedef struct Select Select;
6781 typedef struct SrcList SrcList;
6782 typedef struct StrAccum StrAccum;
6783 typedef struct Table Table;
6784 typedef struct TableLock TableLock;
6785 typedef struct Token Token;
6786 typedef struct TriggerPrg TriggerPrg;
6787 typedef struct TriggerStep TriggerStep;
6788 typedef struct Trigger Trigger;
6789 typedef struct UnpackedRecord UnpackedRecord;
6790 typedef struct VTable VTable;
6791 typedef struct Walker Walker;
6792 typedef struct WherePlan WherePlan;
6793 typedef struct WhereInfo WhereInfo;
6794 typedef struct WhereLevel WhereLevel;
6795
6796 /*
6797 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
6798 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
6799 ** pointer types (i.e. FuncDef) defined above.
6800 */
6801 /************** Include btree.h in the middle of sqliteInt.h *****************/
6802 /************** Begin file btree.h *******************************************/
6803 /*
6804 ** 2001 September 15
6805 **
6806 ** The author disclaims copyright to this source code.  In place of
6807 ** a legal notice, here is a blessing:
6808 **
6809 **    May you do good and not evil.
6810 **    May you find forgiveness for yourself and forgive others.
6811 **    May you share freely, never taking more than you give.
6812 **
6813 *************************************************************************
6814 ** This header file defines the interface that the sqlite B-Tree file
6815 ** subsystem.  See comments in the source code for a detailed description
6816 ** of what each interface routine does.
6817 */
6818 #ifndef _BTREE_H_
6819 #define _BTREE_H_
6820
6821 /* TODO: This definition is just included so other modules compile. It
6822 ** needs to be revisited.
6823 */
6824 #define SQLITE_N_BTREE_META 10
6825
6826 /*
6827 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
6828 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
6829 */
6830 #ifndef SQLITE_DEFAULT_AUTOVACUUM
6831   #define SQLITE_DEFAULT_AUTOVACUUM 0
6832 #endif
6833
6834 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
6835 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
6836 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
6837
6838 /*
6839 ** Forward declarations of structure
6840 */
6841 typedef struct Btree Btree;
6842 typedef struct BtCursor BtCursor;
6843 typedef struct BtShared BtShared;
6844 typedef struct BtreeMutexArray BtreeMutexArray;
6845
6846 /*
6847 ** This structure records all of the Btrees that need to hold
6848 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
6849 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
6850 ** we can always lock and unlock them all quickly.
6851 */
6852 struct BtreeMutexArray {
6853   int nMutex;
6854   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
6855 };
6856
6857
6858 SQLITE_PRIVATE int sqlite3BtreeOpen(
6859   const char *zFilename,   /* Name of database file to open */
6860   sqlite3 *db,             /* Associated database connection */
6861   Btree **ppBtree,         /* Return open Btree* here */
6862   int flags,               /* Flags */
6863   int vfsFlags             /* Flags passed through to VFS open */
6864 );
6865
6866 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
6867 ** following values.
6868 **
6869 ** NOTE:  These values must match the corresponding PAGER_ values in
6870 ** pager.h.
6871 */
6872 #define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
6873 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
6874 #define BTREE_MEMORY        4  /* In-memory DB.  No argument */
6875 #define BTREE_READONLY      8  /* Open the database in read-only mode */
6876 #define BTREE_READWRITE    16  /* Open for both reading and writing */
6877 #define BTREE_CREATE       32  /* Create the database if it does not exist */
6878
6879 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
6880 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
6881 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
6882 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
6883 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
6884 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
6885 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
6886 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
6887 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
6888 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
6889 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
6890 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
6891 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
6892 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
6893 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
6894 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
6895 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
6896 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
6897 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
6898 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
6899 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
6900 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
6901 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
6902 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
6903
6904 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
6905 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
6906 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
6907
6908 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
6909
6910 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
6911 ** of the following flags:
6912 */
6913 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
6914 #define BTREE_ZERODATA   2    /* Table has keys only - no data */
6915 #define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
6916
6917 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
6918 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
6919 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
6920
6921 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
6922 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
6923
6924 /*
6925 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
6926 ** should be one of the following values. The integer values are assigned 
6927 ** to constants so that the offset of the corresponding field in an
6928 ** SQLite database header may be found using the following formula:
6929 **
6930 **   offset = 36 + (idx * 4)
6931 **
6932 ** For example, the free-page-count field is located at byte offset 36 of
6933 ** the database file header. The incr-vacuum-flag field is located at
6934 ** byte offset 64 (== 36+4*7).
6935 */
6936 #define BTREE_FREE_PAGE_COUNT     0
6937 #define BTREE_SCHEMA_VERSION      1
6938 #define BTREE_FILE_FORMAT         2
6939 #define BTREE_DEFAULT_CACHE_SIZE  3
6940 #define BTREE_LARGEST_ROOT_PAGE   4
6941 #define BTREE_TEXT_ENCODING       5
6942 #define BTREE_USER_VERSION        6
6943 #define BTREE_INCR_VACUUM         7
6944
6945 SQLITE_PRIVATE int sqlite3BtreeCursor(
6946   Btree*,                              /* BTree containing table to open */
6947   int iTable,                          /* Index of root page */
6948   int wrFlag,                          /* 1 for writing.  0 for read-only */
6949   struct KeyInfo*,                     /* First argument to compare function */
6950   BtCursor *pCursor                    /* Space to write cursor structure */
6951 );
6952 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
6953 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
6954
6955 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
6956 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
6957   BtCursor*,
6958   UnpackedRecord *pUnKey,
6959   i64 intKey,
6960   int bias,
6961   int *pRes
6962 );
6963 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
6964 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
6965 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
6966                                   const void *pData, int nData,
6967                                   int nZero, int bias, int seekResult);
6968 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
6969 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
6970 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
6971 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
6972 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
6973 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
6974 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
6975 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
6976 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
6977 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
6978 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
6979 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
6980 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
6981
6982 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
6983 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
6984
6985 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
6986 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
6987 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
6988
6989 #ifndef NDEBUG
6990 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
6991 #endif
6992
6993 #ifndef SQLITE_OMIT_BTREECOUNT
6994 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
6995 #endif
6996
6997 #ifdef SQLITE_TEST
6998 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
6999 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7000 #endif
7001
7002 /*
7003 ** If we are not using shared cache, then there is no need to
7004 ** use mutexes to access the BtShared structures.  So make the
7005 ** Enter and Leave procedures no-ops.
7006 */
7007 #ifndef SQLITE_OMIT_SHARED_CACHE
7008 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7009 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7010 #else
7011 # define sqlite3BtreeEnter(X) 
7012 # define sqlite3BtreeEnterAll(X)
7013 #endif
7014
7015 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7016 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7017 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7018 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7019 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7020 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7021 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7022 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7023 #ifndef NDEBUG
7024   /* These routines are used inside assert() statements only. */
7025 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7026 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7027 #endif
7028 #else
7029
7030 # define sqlite3BtreeLeave(X)
7031 # define sqlite3BtreeEnterCursor(X)
7032 # define sqlite3BtreeLeaveCursor(X)
7033 # define sqlite3BtreeLeaveAll(X)
7034 # define sqlite3BtreeMutexArrayEnter(X)
7035 # define sqlite3BtreeMutexArrayLeave(X)
7036 # define sqlite3BtreeMutexArrayInsert(X,Y)
7037
7038 # define sqlite3BtreeHoldsMutex(X) 1
7039 # define sqlite3BtreeHoldsAllMutexes(X) 1
7040 #endif
7041
7042
7043 #endif /* _BTREE_H_ */
7044
7045 /************** End of btree.h ***********************************************/
7046 /************** Continuing where we left off in sqliteInt.h ******************/
7047 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
7048 /************** Begin file vdbe.h ********************************************/
7049 /*
7050 ** 2001 September 15
7051 **
7052 ** The author disclaims copyright to this source code.  In place of
7053 ** a legal notice, here is a blessing:
7054 **
7055 **    May you do good and not evil.
7056 **    May you find forgiveness for yourself and forgive others.
7057 **    May you share freely, never taking more than you give.
7058 **
7059 *************************************************************************
7060 ** Header file for the Virtual DataBase Engine (VDBE)
7061 **
7062 ** This header defines the interface to the virtual database engine
7063 ** or VDBE.  The VDBE implements an abstract machine that runs a
7064 ** simple program to access and modify the underlying database.
7065 */
7066 #ifndef _SQLITE_VDBE_H_
7067 #define _SQLITE_VDBE_H_
7068
7069 /*
7070 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
7071 ** in the source file sqliteVdbe.c are allowed to see the insides
7072 ** of this structure.
7073 */
7074 typedef struct Vdbe Vdbe;
7075
7076 /*
7077 ** The names of the following types declared in vdbeInt.h are required
7078 ** for the VdbeOp definition.
7079 */
7080 typedef struct VdbeFunc VdbeFunc;
7081 typedef struct Mem Mem;
7082 typedef struct SubProgram SubProgram;
7083
7084 /*
7085 ** A single instruction of the virtual machine has an opcode
7086 ** and as many as three operands.  The instruction is recorded
7087 ** as an instance of the following structure:
7088 */
7089 struct VdbeOp {
7090   u8 opcode;          /* What operation to perform */
7091   signed char p4type; /* One of the P4_xxx constants for p4 */
7092   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
7093   u8 p5;              /* Fifth parameter is an unsigned character */
7094   int p1;             /* First operand */
7095   int p2;             /* Second parameter (often the jump destination) */
7096   int p3;             /* The third parameter */
7097   union {             /* fourth parameter */
7098     int i;                 /* Integer value if p4type==P4_INT32 */
7099     void *p;               /* Generic pointer */
7100     char *z;               /* Pointer to data for string (char array) types */
7101     i64 *pI64;             /* Used when p4type is P4_INT64 */
7102     double *pReal;         /* Used when p4type is P4_REAL */
7103     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7104     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7105     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7106     Mem *pMem;             /* Used when p4type is P4_MEM */
7107     VTable *pVtab;         /* Used when p4type is P4_VTAB */
7108     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7109     int *ai;               /* Used when p4type is P4_INTARRAY */
7110     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
7111   } p4;
7112 #ifdef SQLITE_DEBUG
7113   char *zComment;          /* Comment to improve readability */
7114 #endif
7115 #ifdef VDBE_PROFILE
7116   int cnt;                 /* Number of times this instruction was executed */
7117   u64 cycles;              /* Total time spent executing this instruction */
7118 #endif
7119 };
7120 typedef struct VdbeOp VdbeOp;
7121
7122
7123 /*
7124 ** A sub-routine used to implement a trigger program.
7125 */
7126 struct SubProgram {
7127   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
7128   int nOp;                      /* Elements in aOp[] */
7129   int nMem;                     /* Number of memory cells required */
7130   int nCsr;                     /* Number of cursors required */
7131   int nRef;                     /* Number of pointers to this structure */
7132   void *token;                  /* id that may be used to recursive triggers */
7133 };
7134
7135 /*
7136 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7137 ** it takes up less space.
7138 */
7139 struct VdbeOpList {
7140   u8 opcode;          /* What operation to perform */
7141   signed char p1;     /* First operand */
7142   signed char p2;     /* Second parameter (often the jump destination) */
7143   signed char p3;     /* Third parameter */
7144 };
7145 typedef struct VdbeOpList VdbeOpList;
7146
7147 /*
7148 ** Allowed values of VdbeOp.p4type
7149 */
7150 #define P4_NOTUSED    0   /* The P4 parameter is not used */
7151 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7152 #define P4_STATIC   (-2)  /* Pointer to a static string */
7153 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7154 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7155 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7156 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7157 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7158 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
7159 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7160 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7161 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7162 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7163 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7164 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7165 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
7166
7167 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7168 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
7169 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7170 ** gets freed when the Vdbe is finalized so it still should be obtained
7171 ** from a single sqliteMalloc().  But no copy is made and the calling
7172 ** function should *not* try to free the KeyInfo.
7173 */
7174 #define P4_KEYINFO_HANDOFF (-16)
7175 #define P4_KEYINFO_STATIC  (-17)
7176
7177 /*
7178 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
7179 ** number of columns of data returned by the statement.
7180 */
7181 #define COLNAME_NAME     0
7182 #define COLNAME_DECLTYPE 1
7183 #define COLNAME_DATABASE 2
7184 #define COLNAME_TABLE    3
7185 #define COLNAME_COLUMN   4
7186 #ifdef SQLITE_ENABLE_COLUMN_METADATA
7187 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
7188 #else
7189 # ifdef SQLITE_OMIT_DECLTYPE
7190 #   define COLNAME_N      1      /* Store only the name */
7191 # else
7192 #   define COLNAME_N      2      /* Store the name and decltype */
7193 # endif
7194 #endif
7195
7196 /*
7197 ** The following macro converts a relative address in the p2 field
7198 ** of a VdbeOp structure into a negative number so that 
7199 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
7200 ** the macro again restores the address.
7201 */
7202 #define ADDR(X)  (-1-(X))
7203
7204 /*
7205 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
7206 ** header file that defines a number for each opcode used by the VDBE.
7207 */
7208 /************** Include opcodes.h in the middle of vdbe.h ********************/
7209 /************** Begin file opcodes.h *****************************************/
7210 /* Automatically generated.  Do not edit */
7211 /* See the mkopcodeh.awk script for details */
7212 #define OP_Goto                                 1
7213 #define OP_Gosub                                2
7214 #define OP_Return                               3
7215 #define OP_Yield                                4
7216 #define OP_HaltIfNull                           5
7217 #define OP_Halt                                 6
7218 #define OP_Integer                              7
7219 #define OP_Int64                                8
7220 #define OP_Real                               130   /* same as TK_FLOAT    */
7221 #define OP_String8                             94   /* same as TK_STRING   */
7222 #define OP_String                               9
7223 #define OP_Null                                10
7224 #define OP_Blob                                11
7225 #define OP_Variable                            12
7226 #define OP_Move                                13
7227 #define OP_Copy                                14
7228 #define OP_SCopy                               15
7229 #define OP_ResultRow                           16
7230 #define OP_Concat                              91   /* same as TK_CONCAT   */
7231 #define OP_Add                                 86   /* same as TK_PLUS     */
7232 #define OP_Subtract                            87   /* same as TK_MINUS    */
7233 #define OP_Multiply                            88   /* same as TK_STAR     */
7234 #define OP_Divide                              89   /* same as TK_SLASH    */
7235 #define OP_Remainder                           90   /* same as TK_REM      */
7236 #define OP_CollSeq                             17
7237 #define OP_Function                            18
7238 #define OP_BitAnd                              82   /* same as TK_BITAND   */
7239 #define OP_BitOr                               83   /* same as TK_BITOR    */
7240 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
7241 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
7242 #define OP_AddImm                              20
7243 #define OP_MustBeInt                           21
7244 #define OP_RealAffinity                        22
7245 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
7246 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
7247 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
7248 #define OP_ToInt                              144   /* same as TK_TO_INT   */
7249 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
7250 #define OP_Eq                                  76   /* same as TK_EQ       */
7251 #define OP_Ne                                  75   /* same as TK_NE       */
7252 #define OP_Lt                                  79   /* same as TK_LT       */
7253 #define OP_Le                                  78   /* same as TK_LE       */
7254 #define OP_Gt                                  77   /* same as TK_GT       */
7255 #define OP_Ge                                  80   /* same as TK_GE       */
7256 #define OP_Permutation                         23
7257 #define OP_Compare                             24
7258 #define OP_Jump                                25
7259 #define OP_And                                 69   /* same as TK_AND      */
7260 #define OP_Or                                  68   /* same as TK_OR       */
7261 #define OP_Not                                 19   /* same as TK_NOT      */
7262 #define OP_BitNot                              93   /* same as TK_BITNOT   */
7263 #define OP_If                                  26
7264 #define OP_IfNot                               27
7265 #define OP_IsNull                              73   /* same as TK_ISNULL   */
7266 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
7267 #define OP_Column                              28
7268 #define OP_Affinity                            29
7269 #define OP_MakeRecord                          30
7270 #define OP_Count                               31
7271 #define OP_Savepoint                           32
7272 #define OP_AutoCommit                          33
7273 #define OP_Transaction                         34
7274 #define OP_ReadCookie                          35
7275 #define OP_SetCookie                           36
7276 #define OP_VerifyCookie                        37
7277 #define OP_OpenRead                            38
7278 #define OP_OpenWrite                           39
7279 #define OP_OpenEphemeral                       40
7280 #define OP_OpenPseudo                          41
7281 #define OP_Close                               42
7282 #define OP_SeekLt                              43
7283 #define OP_SeekLe                              44
7284 #define OP_SeekGe                              45
7285 #define OP_SeekGt                              46
7286 #define OP_Seek                                47
7287 #define OP_NotFound                            48
7288 #define OP_Found                               49
7289 #define OP_IsUnique                            50
7290 #define OP_NotExists                           51
7291 #define OP_Sequence                            52
7292 #define OP_NewRowid                            53
7293 #define OP_Insert                              54
7294 #define OP_InsertInt                           55
7295 #define OP_Delete                              56
7296 #define OP_ResetCount                          57
7297 #define OP_RowKey                              58
7298 #define OP_RowData                             59
7299 #define OP_Rowid                               60
7300 #define OP_NullRow                             61
7301 #define OP_Last                                62
7302 #define OP_Sort                                63
7303 #define OP_Rewind                              64
7304 #define OP_Prev                                65
7305 #define OP_Next                                66
7306 #define OP_IdxInsert                           67
7307 #define OP_IdxDelete                           70
7308 #define OP_IdxRowid                            71
7309 #define OP_IdxLT                               72
7310 #define OP_IdxGE                               81
7311 #define OP_Destroy                             92
7312 #define OP_Clear                               95
7313 #define OP_CreateIndex                         96
7314 #define OP_CreateTable                         97
7315 #define OP_ParseSchema                         98
7316 #define OP_LoadAnalysis                        99
7317 #define OP_DropTable                          100
7318 #define OP_DropIndex                          101
7319 #define OP_DropTrigger                        102
7320 #define OP_IntegrityCk                        103
7321 #define OP_RowSetAdd                          104
7322 #define OP_RowSetRead                         105
7323 #define OP_RowSetTest                         106
7324 #define OP_Program                            107
7325 #define OP_Param                              108
7326 #define OP_FkCounter                          109
7327 #define OP_FkIfZero                           110
7328 #define OP_MemMax                             111
7329 #define OP_IfPos                              112
7330 #define OP_IfNeg                              113
7331 #define OP_IfZero                             114
7332 #define OP_AggStep                            115
7333 #define OP_AggFinal                           116
7334 #define OP_Vacuum                             117
7335 #define OP_IncrVacuum                         118
7336 #define OP_Expire                             119
7337 #define OP_TableLock                          120
7338 #define OP_VBegin                             121
7339 #define OP_VCreate                            122
7340 #define OP_VDestroy                           123
7341 #define OP_VOpen                              124
7342 #define OP_VFilter                            125
7343 #define OP_VColumn                            126
7344 #define OP_VNext                              127
7345 #define OP_VRename                            128
7346 #define OP_VUpdate                            129
7347 #define OP_Pagecount                          131
7348 #define OP_Trace                              132
7349 #define OP_Noop                               133
7350 #define OP_Explain                            134
7351
7352 /* The following opcode values are never used */
7353 #define OP_NotUsed_135                        135
7354 #define OP_NotUsed_136                        136
7355 #define OP_NotUsed_137                        137
7356 #define OP_NotUsed_138                        138
7357 #define OP_NotUsed_139                        139
7358 #define OP_NotUsed_140                        140
7359
7360
7361 /* Properties such as "out2" or "jump" that are specified in
7362 ** comments following the "case" for each opcode in the vdbe.c
7363 ** are encoded into bitvectors as follows:
7364 */
7365 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
7366 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
7367 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
7368 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
7369 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
7370 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
7371 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
7372 #define OPFLG_INITIALIZER {\
7373 /*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
7374 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x24,\
7375 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
7376 /*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7377 /*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
7378 /*  40 */ 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x08,\
7379 /*  48 */ 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00, 0x00,\
7380 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x01,\
7381 /*  64 */ 0x01, 0x01, 0x01, 0x08, 0x4c, 0x4c, 0x00, 0x02,\
7382 /*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
7383 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
7384 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x02, 0x24, 0x02, 0x00,\
7385 /*  96 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7386 /* 104 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
7387 /* 112 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00,\
7388 /* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01,\
7389 /* 128 */ 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00,\
7390 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
7391 /* 144 */ 0x04, 0x04,}
7392
7393 /************** End of opcodes.h *********************************************/
7394 /************** Continuing where we left off in vdbe.h ***********************/
7395
7396 /*
7397 ** Prototypes for the VDBE interface.  See comments on the implementation
7398 ** for a description of what each of these routines does.
7399 */
7400 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
7401 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
7402 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
7403 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
7404 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
7405 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
7406 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
7407 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
7408 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
7409 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
7410 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
7411 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
7412 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
7413 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
7414 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
7415 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
7416 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
7417 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
7418 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
7419 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
7420 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
7421 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
7422 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
7423 #ifdef SQLITE_DEBUG
7424 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
7425 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
7426 #endif
7427 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
7428 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
7429 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
7430 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
7431 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
7432 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
7433 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
7434 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
7435 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
7436 SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *, SubProgram *, int);
7437 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
7438 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
7439 #ifndef SQLITE_OMIT_TRACE
7440 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
7441 #endif
7442
7443 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
7444 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
7445 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
7446
7447
7448 #ifndef NDEBUG
7449 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
7450 # define VdbeComment(X)  sqlite3VdbeComment X
7451 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
7452 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
7453 #else
7454 # define VdbeComment(X)
7455 # define VdbeNoopComment(X)
7456 #endif
7457
7458 #endif
7459
7460 /************** End of vdbe.h ************************************************/
7461 /************** Continuing where we left off in sqliteInt.h ******************/
7462 /************** Include pager.h in the middle of sqliteInt.h *****************/
7463 /************** Begin file pager.h *******************************************/
7464 /*
7465 ** 2001 September 15
7466 **
7467 ** The author disclaims copyright to this source code.  In place of
7468 ** a legal notice, here is a blessing:
7469 **
7470 **    May you do good and not evil.
7471 **    May you find forgiveness for yourself and forgive others.
7472 **    May you share freely, never taking more than you give.
7473 **
7474 *************************************************************************
7475 ** This header file defines the interface that the sqlite page cache
7476 ** subsystem.  The page cache subsystem reads and writes a file a page
7477 ** at a time and provides a journal for rollback.
7478 */
7479
7480 #ifndef _PAGER_H_
7481 #define _PAGER_H_
7482
7483 /*
7484 ** Default maximum size for persistent journal files. A negative 
7485 ** value means no limit. This value may be overridden using the 
7486 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
7487 */
7488 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
7489   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
7490 #endif
7491
7492 /*
7493 ** The type used to represent a page number.  The first page in a file
7494 ** is called page 1.  0 is used to represent "not a page".
7495 */
7496 typedef u32 Pgno;
7497
7498 /*
7499 ** Each open file is managed by a separate instance of the "Pager" structure.
7500 */
7501 typedef struct Pager Pager;
7502
7503 /*
7504 ** Handle type for pages.
7505 */
7506 typedef struct PgHdr DbPage;
7507
7508 /*
7509 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
7510 ** reserved for working around a windows/posix incompatibility). It is
7511 ** used in the journal to signify that the remainder of the journal file 
7512 ** is devoted to storing a master journal name - there are no more pages to
7513 ** roll back. See comments for function writeMasterJournal() in pager.c 
7514 ** for details.
7515 */
7516 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
7517
7518 /*
7519 ** Allowed values for the flags parameter to sqlite3PagerOpen().
7520 **
7521 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
7522 */
7523 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
7524 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
7525
7526 /*
7527 ** Valid values for the second argument to sqlite3PagerLockingMode().
7528 */
7529 #define PAGER_LOCKINGMODE_QUERY      -1
7530 #define PAGER_LOCKINGMODE_NORMAL      0
7531 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
7532
7533 /*
7534 ** Valid values for the second argument to sqlite3PagerJournalMode().
7535 */
7536 #define PAGER_JOURNALMODE_QUERY      -1
7537 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
7538 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
7539 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
7540 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
7541 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
7542
7543 /*
7544 ** The remainder of this file contains the declarations of the functions
7545 ** that make up the Pager sub-system API. See source code comments for 
7546 ** a detailed description of each routine.
7547 */
7548
7549 /* Open and close a Pager connection. */ 
7550 SQLITE_PRIVATE int sqlite3PagerOpen(
7551   sqlite3_vfs*,
7552   Pager **ppPager,
7553   const char*,
7554   int,
7555   int,
7556   int,
7557   void(*)(DbPage*)
7558 );
7559 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
7560 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
7561
7562 /* Functions used to configure a Pager object. */
7563 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
7564 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*, int);
7565 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
7566 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
7567 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
7568 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
7569 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
7570 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
7571 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
7572
7573 /* Functions used to obtain and release page references. */ 
7574 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
7575 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
7576 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
7577 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
7578 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
7579
7580 /* Operations on page references. */
7581 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
7582 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
7583 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
7584 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
7585 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
7586 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
7587
7588 /* Functions used to manage pager transactions and savepoints. */
7589 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
7590 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
7591 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
7592 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
7593 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7594 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
7595 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
7596 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
7597 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
7598
7599 /* Functions used to query pager state and configuration. */
7600 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
7601 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
7602 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
7603 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
7604 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
7605 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
7606 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
7607 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
7608 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
7609
7610 /* Functions used to truncate the database file. */
7611 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
7612
7613 /* Functions to support testing and debugging. */
7614 #if !defined(NDEBUG) || defined(SQLITE_TEST)
7615 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
7616 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
7617 #endif
7618 #ifdef SQLITE_TEST
7619 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
7620 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
7621   void disable_simulated_io_errors(void);
7622   void enable_simulated_io_errors(void);
7623 #else
7624 # define disable_simulated_io_errors()
7625 # define enable_simulated_io_errors()
7626 #endif
7627
7628 #endif /* _PAGER_H_ */
7629
7630 /************** End of pager.h ***********************************************/
7631 /************** Continuing where we left off in sqliteInt.h ******************/
7632 /************** Include pcache.h in the middle of sqliteInt.h ****************/
7633 /************** Begin file pcache.h ******************************************/
7634 /*
7635 ** 2008 August 05
7636 **
7637 ** The author disclaims copyright to this source code.  In place of
7638 ** a legal notice, here is a blessing:
7639 **
7640 **    May you do good and not evil.
7641 **    May you find forgiveness for yourself and forgive others.
7642 **    May you share freely, never taking more than you give.
7643 **
7644 *************************************************************************
7645 ** This header file defines the interface that the sqlite page cache
7646 ** subsystem. 
7647 */
7648
7649 #ifndef _PCACHE_H_
7650
7651 typedef struct PgHdr PgHdr;
7652 typedef struct PCache PCache;
7653
7654 /*
7655 ** Every page in the cache is controlled by an instance of the following
7656 ** structure.
7657 */
7658 struct PgHdr {
7659   void *pData;                   /* Content of this page */
7660   void *pExtra;                  /* Extra content */
7661   PgHdr *pDirty;                 /* Transient list of dirty pages */
7662   Pgno pgno;                     /* Page number for this page */
7663   Pager *pPager;                 /* The pager this page is part of */
7664 #ifdef SQLITE_CHECK_PAGES
7665   u32 pageHash;                  /* Hash of page content */
7666 #endif
7667   u16 flags;                     /* PGHDR flags defined below */
7668
7669   /**********************************************************************
7670   ** Elements above are public.  All that follows is private to pcache.c
7671   ** and should not be accessed by other modules.
7672   */
7673   i16 nRef;                      /* Number of users of this page */
7674   PCache *pCache;                /* Cache that owns this page */
7675
7676   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
7677   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
7678 };
7679
7680 /* Bit values for PgHdr.flags */
7681 #define PGHDR_DIRTY             0x002  /* Page has changed */
7682 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
7683                                        ** writing this page to the database */
7684 #define PGHDR_NEED_READ         0x008  /* Content is unread */
7685 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
7686 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
7687
7688 /* Initialize and shutdown the page cache subsystem */
7689 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
7690 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
7691
7692 /* Page cache buffer management:
7693 ** These routines implement SQLITE_CONFIG_PAGECACHE.
7694 */
7695 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
7696
7697 /* Create a new pager cache.
7698 ** Under memory stress, invoke xStress to try to make pages clean.
7699 ** Only clean and unpinned pages can be reclaimed.
7700 */
7701 SQLITE_PRIVATE void sqlite3PcacheOpen(
7702   int szPage,                    /* Size of every page */
7703   int szExtra,                   /* Extra space associated with each page */
7704   int bPurgeable,                /* True if pages are on backing store */
7705   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
7706   void *pStress,                 /* Argument to xStress */
7707   PCache *pToInit                /* Preallocated space for the PCache */
7708 );
7709
7710 /* Modify the page-size after the cache has been created. */
7711 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
7712
7713 /* Return the size in bytes of a PCache object.  Used to preallocate
7714 ** storage space.
7715 */
7716 SQLITE_PRIVATE int sqlite3PcacheSize(void);
7717
7718 /* One release per successful fetch.  Page is pinned until released.
7719 ** Reference counted. 
7720 */
7721 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
7722 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
7723
7724 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
7725 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
7726 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
7727 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
7728
7729 /* Change a page number.  Used by incr-vacuum. */
7730 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
7731
7732 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
7733 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
7734
7735 /* Get a list of all dirty pages in the cache, sorted by page number */
7736 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
7737
7738 /* Reset and close the cache object */
7739 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
7740
7741 /* Clear flags from pages of the page cache */
7742 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
7743
7744 /* Discard the contents of the cache */
7745 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
7746
7747 /* Return the total number of outstanding page references */
7748 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
7749
7750 /* Increment the reference count of an existing page */
7751 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
7752
7753 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
7754
7755 /* Return the total number of pages stored in the cache */
7756 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
7757
7758 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
7759 /* Iterate through all dirty pages currently stored in the cache. This
7760 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
7761 ** library is built.
7762 */
7763 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
7764 #endif
7765
7766 /* Set and get the suggested cache-size for the specified pager-cache.
7767 **
7768 ** If no global maximum is configured, then the system attempts to limit
7769 ** the total number of pages cached by purgeable pager-caches to the sum
7770 ** of the suggested cache-sizes.
7771 */
7772 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
7773 #ifdef SQLITE_TEST
7774 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
7775 #endif
7776
7777 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
7778 /* Try to return memory used by the pcache module to the main memory heap */
7779 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
7780 #endif
7781
7782 #ifdef SQLITE_TEST
7783 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
7784 #endif
7785
7786 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
7787
7788 #endif /* _PCACHE_H_ */
7789
7790 /************** End of pcache.h **********************************************/
7791 /************** Continuing where we left off in sqliteInt.h ******************/
7792
7793 /************** Include os.h in the middle of sqliteInt.h ********************/
7794 /************** Begin file os.h **********************************************/
7795 /*
7796 ** 2001 September 16
7797 **
7798 ** The author disclaims copyright to this source code.  In place of
7799 ** a legal notice, here is a blessing:
7800 **
7801 **    May you do good and not evil.
7802 **    May you find forgiveness for yourself and forgive others.
7803 **    May you share freely, never taking more than you give.
7804 **
7805 ******************************************************************************
7806 **
7807 ** This header file (together with is companion C source-code file
7808 ** "os.c") attempt to abstract the underlying operating system so that
7809 ** the SQLite library will work on both POSIX and windows systems.
7810 **
7811 ** This header file is #include-ed by sqliteInt.h and thus ends up
7812 ** being included by every source file.
7813 */
7814 #ifndef _SQLITE_OS_H_
7815 #define _SQLITE_OS_H_
7816
7817 /*
7818 ** Figure out if we are dealing with Unix, Windows, or some other
7819 ** operating system.  After the following block of preprocess macros,
7820 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
7821 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
7822 ** three will be 0.
7823 */
7824 #if defined(SQLITE_OS_OTHER)
7825 # if SQLITE_OS_OTHER==1
7826 #   undef SQLITE_OS_UNIX
7827 #   define SQLITE_OS_UNIX 0
7828 #   undef SQLITE_OS_WIN
7829 #   define SQLITE_OS_WIN 0
7830 #   undef SQLITE_OS_OS2
7831 #   define SQLITE_OS_OS2 0
7832 # else
7833 #   undef SQLITE_OS_OTHER
7834 # endif
7835 #endif
7836 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
7837 # define SQLITE_OS_OTHER 0
7838 # ifndef SQLITE_OS_WIN
7839 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
7840 #     define SQLITE_OS_WIN 1
7841 #     define SQLITE_OS_UNIX 0
7842 #     define SQLITE_OS_OS2 0
7843 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
7844 #     define SQLITE_OS_WIN 0
7845 #     define SQLITE_OS_UNIX 0
7846 #     define SQLITE_OS_OS2 1
7847 #   else
7848 #     define SQLITE_OS_WIN 0
7849 #     define SQLITE_OS_UNIX 1
7850 #     define SQLITE_OS_OS2 0
7851 #  endif
7852 # else
7853 #  define SQLITE_OS_UNIX 0
7854 #  define SQLITE_OS_OS2 0
7855 # endif
7856 #else
7857 # ifndef SQLITE_OS_WIN
7858 #  define SQLITE_OS_WIN 0
7859 # endif
7860 #endif
7861
7862 /*
7863 ** Determine if we are dealing with WindowsCE - which has a much
7864 ** reduced API.
7865 */
7866 #if defined(_WIN32_WCE)
7867 # define SQLITE_OS_WINCE 1
7868 #else
7869 # define SQLITE_OS_WINCE 0
7870 #endif
7871
7872
7873 /*
7874 ** Define the maximum size of a temporary filename
7875 */
7876 #if SQLITE_OS_WIN
7877 # include <windows.h>
7878 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
7879 #elif SQLITE_OS_OS2
7880 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
7881 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
7882 # endif
7883 # define INCL_DOSDATETIME
7884 # define INCL_DOSFILEMGR
7885 # define INCL_DOSERRORS
7886 # define INCL_DOSMISC
7887 # define INCL_DOSPROCESS
7888 # define INCL_DOSMODULEMGR
7889 # define INCL_DOSSEMAPHORES
7890 # include <os2.h>
7891 # include <uconv.h>
7892 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
7893 #else
7894 # define SQLITE_TEMPNAME_SIZE 200
7895 #endif
7896
7897 /* If the SET_FULLSYNC macro is not defined above, then make it
7898 ** a no-op
7899 */
7900 #ifndef SET_FULLSYNC
7901 # define SET_FULLSYNC(x,y)
7902 #endif
7903
7904 /*
7905 ** The default size of a disk sector
7906 */
7907 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
7908 # define SQLITE_DEFAULT_SECTOR_SIZE 512
7909 #endif
7910
7911 /*
7912 ** Temporary files are named starting with this prefix followed by 16 random
7913 ** alphanumeric characters, and no file extension. They are stored in the
7914 ** OS's standard temporary file directory, and are deleted prior to exit.
7915 ** If sqlite is being embedded in another program, you may wish to change the
7916 ** prefix to reflect your program's name, so that if your program exits
7917 ** prematurely, old temporary files can be easily identified. This can be done
7918 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
7919 **
7920 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
7921 ** Mcafee started using SQLite in their anti-virus product and it
7922 ** started putting files with the "sqlite" name in the c:/temp folder.
7923 ** This annoyed many windows users.  Those users would then do a 
7924 ** Google search for "sqlite", find the telephone numbers of the
7925 ** developers and call to wake them up at night and complain.
7926 ** For this reason, the default name prefix is changed to be "sqlite" 
7927 ** spelled backwards.  So the temp files are still identified, but
7928 ** anybody smart enough to figure out the code is also likely smart
7929 ** enough to know that calling the developer will not help get rid
7930 ** of the file.
7931 */
7932 #ifndef SQLITE_TEMP_FILE_PREFIX
7933 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
7934 #endif
7935
7936 /*
7937 ** The following values may be passed as the second argument to
7938 ** sqlite3OsLock(). The various locks exhibit the following semantics:
7939 **
7940 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
7941 ** RESERVED:  A single process may hold a RESERVED lock on a file at
7942 **            any time. Other processes may hold and obtain new SHARED locks.
7943 ** PENDING:   A single process may hold a PENDING lock on a file at
7944 **            any one time. Existing SHARED locks may persist, but no new
7945 **            SHARED locks may be obtained by other processes.
7946 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
7947 **
7948 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
7949 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
7950 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
7951 ** sqlite3OsLock().
7952 */
7953 #define NO_LOCK         0
7954 #define SHARED_LOCK     1
7955 #define RESERVED_LOCK   2
7956 #define PENDING_LOCK    3
7957 #define EXCLUSIVE_LOCK  4
7958
7959 /*
7960 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
7961 **
7962 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
7963 ** those functions are not available.  So we use only LockFile() and
7964 ** UnlockFile().
7965 **
7966 ** LockFile() prevents not just writing but also reading by other processes.
7967 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
7968 ** byte out of a specific range of bytes. The lock byte is obtained at 
7969 ** random so two separate readers can probably access the file at the 
7970 ** same time, unless they are unlucky and choose the same lock byte.
7971 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
7972 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
7973 ** a single byte of the file that is designated as the reserved lock byte.
7974 ** A PENDING_LOCK is obtained by locking a designated byte different from
7975 ** the RESERVED_LOCK byte.
7976 **
7977 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
7978 ** which means we can use reader/writer locks.  When reader/writer locks
7979 ** are used, the lock is placed on the same range of bytes that is used
7980 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
7981 ** will support two or more Win95 readers or two or more WinNT readers.
7982 ** But a single Win95 reader will lock out all WinNT readers and a single
7983 ** WinNT reader will lock out all other Win95 readers.
7984 **
7985 ** The following #defines specify the range of bytes used for locking.
7986 ** SHARED_SIZE is the number of bytes available in the pool from which
7987 ** a random byte is selected for a shared lock.  The pool of bytes for
7988 ** shared locks begins at SHARED_FIRST. 
7989 **
7990 ** The same locking strategy and
7991 ** byte ranges are used for Unix.  This leaves open the possiblity of having
7992 ** clients on win95, winNT, and unix all talking to the same shared file
7993 ** and all locking correctly.  To do so would require that samba (or whatever
7994 ** tool is being used for file sharing) implements locks correctly between
7995 ** windows and unix.  I'm guessing that isn't likely to happen, but by
7996 ** using the same locking range we are at least open to the possibility.
7997 **
7998 ** Locking in windows is manditory.  For this reason, we cannot store
7999 ** actual data in the bytes used for locking.  The pager never allocates
8000 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
8001 ** that all locks will fit on a single page even at the minimum page size.
8002 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8003 ** is set high so that we don't have to allocate an unused page except
8004 ** for very large databases.  But one should test the page skipping logic 
8005 ** by setting PENDING_BYTE low and running the entire regression suite.
8006 **
8007 ** Changing the value of PENDING_BYTE results in a subtly incompatible
8008 ** file format.  Depending on how it is changed, you might not notice
8009 ** the incompatibility right away, even running a full regression test.
8010 ** The default location of PENDING_BYTE is the first byte past the
8011 ** 1GB boundary.
8012 **
8013 */
8014 #define PENDING_BYTE      sqlite3PendingByte
8015 #define RESERVED_BYTE     (PENDING_BYTE+1)
8016 #define SHARED_FIRST      (PENDING_BYTE+2)
8017 #define SHARED_SIZE       510
8018
8019 /*
8020 ** Wrapper around OS specific sqlite3_os_init() function.
8021 */
8022 SQLITE_PRIVATE int sqlite3OsInit(void);
8023
8024 /* 
8025 ** Functions for accessing sqlite3_file methods 
8026 */
8027 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8028 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8029 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8030 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8031 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8032 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8033 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8034 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8035 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8036 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8037 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8038 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8039 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8040
8041 /* 
8042 ** Functions for accessing sqlite3_vfs methods 
8043 */
8044 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8045 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8046 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8047 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8048 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8049 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8050 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8051 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8052 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8053 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
8054 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8055 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8056 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
8057
8058 /*
8059 ** Convenience functions for opening and closing files using 
8060 ** sqlite3_malloc() to obtain space for the file-handle structure.
8061 */
8062 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8063 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8064
8065 #endif /* _SQLITE_OS_H_ */
8066
8067 /************** End of os.h **************************************************/
8068 /************** Continuing where we left off in sqliteInt.h ******************/
8069 /************** Include mutex.h in the middle of sqliteInt.h *****************/
8070 /************** Begin file mutex.h *******************************************/
8071 /*
8072 ** 2007 August 28
8073 **
8074 ** The author disclaims copyright to this source code.  In place of
8075 ** a legal notice, here is a blessing:
8076 **
8077 **    May you do good and not evil.
8078 **    May you find forgiveness for yourself and forgive others.
8079 **    May you share freely, never taking more than you give.
8080 **
8081 *************************************************************************
8082 **
8083 ** This file contains the common header for all mutex implementations.
8084 ** The sqliteInt.h header #includes this file so that it is available
8085 ** to all source files.  We break it out in an effort to keep the code
8086 ** better organized.
8087 **
8088 ** NOTE:  source files should *not* #include this header file directly.
8089 ** Source files should #include the sqliteInt.h file and let that file
8090 ** include this one indirectly.
8091 */
8092
8093
8094 /*
8095 ** Figure out what version of the code to use.  The choices are
8096 **
8097 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8098 **                             mutexes implemention cannot be overridden
8099 **                             at start-time.
8100 **
8101 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8102 **                             mutual exclusion is provided.  But this
8103 **                             implementation can be overridden at
8104 **                             start-time.
8105 **
8106 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8107 **
8108 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8109 **
8110 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8111 */
8112 #if !SQLITE_THREADSAFE
8113 # define SQLITE_MUTEX_OMIT
8114 #endif
8115 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8116 #  if SQLITE_OS_UNIX
8117 #    define SQLITE_MUTEX_PTHREADS
8118 #  elif SQLITE_OS_WIN
8119 #    define SQLITE_MUTEX_W32
8120 #  elif SQLITE_OS_OS2
8121 #    define SQLITE_MUTEX_OS2
8122 #  else
8123 #    define SQLITE_MUTEX_NOOP
8124 #  endif
8125 #endif
8126
8127 #ifdef SQLITE_MUTEX_OMIT
8128 /*
8129 ** If this is a no-op implementation, implement everything as macros.
8130 */
8131 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8132 #define sqlite3_mutex_free(X)
8133 #define sqlite3_mutex_enter(X)
8134 #define sqlite3_mutex_try(X)      SQLITE_OK
8135 #define sqlite3_mutex_leave(X)
8136 #define sqlite3_mutex_held(X)     1
8137 #define sqlite3_mutex_notheld(X)  1
8138 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8139 #define sqlite3MutexInit()        SQLITE_OK
8140 #define sqlite3MutexEnd()
8141 #endif /* defined(SQLITE_MUTEX_OMIT) */
8142
8143 /************** End of mutex.h ***********************************************/
8144 /************** Continuing where we left off in sqliteInt.h ******************/
8145
8146
8147 /*
8148 ** Each database file to be accessed by the system is an instance
8149 ** of the following structure.  There are normally two of these structures
8150 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8151 ** aDb[1] is the database file used to hold temporary tables.  Additional
8152 ** databases may be attached.
8153 */
8154 struct Db {
8155   char *zName;         /* Name of this database */
8156   Btree *pBt;          /* The B*Tree structure for this database file */
8157   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8158   u8 safety_level;     /* How aggressive at syncing data to disk */
8159   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
8160 };
8161
8162 /*
8163 ** An instance of the following structure stores a database schema.
8164 **
8165 ** If there are no virtual tables configured in this schema, the
8166 ** Schema.db variable is set to NULL. After the first virtual table
8167 ** has been added, it is set to point to the database connection 
8168 ** used to create the connection. Once a virtual table has been
8169 ** added to the Schema structure and the Schema.db variable populated, 
8170 ** only that database connection may use the Schema to prepare 
8171 ** statements.
8172 */
8173 struct Schema {
8174   int schema_cookie;   /* Database schema version number for this file */
8175   Hash tblHash;        /* All tables indexed by name */
8176   Hash idxHash;        /* All (named) indices indexed by name */
8177   Hash trigHash;       /* All triggers indexed by name */
8178   Hash fkeyHash;       /* All foreign keys by referenced table name */
8179   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
8180   u8 file_format;      /* Schema format version for this file */
8181   u8 enc;              /* Text encoding used by this database */
8182   u16 flags;           /* Flags associated with this schema */
8183   int cache_size;      /* Number of pages to use in the cache */
8184 #ifndef SQLITE_OMIT_VIRTUALTABLE
8185   sqlite3 *db;         /* "Owner" connection. See comment above */
8186 #endif
8187 };
8188
8189 /*
8190 ** These macros can be used to test, set, or clear bits in the 
8191 ** Db.flags field.
8192 */
8193 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
8194 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
8195 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
8196 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
8197
8198 /*
8199 ** Allowed values for the DB.flags field.
8200 **
8201 ** The DB_SchemaLoaded flag is set after the database schema has been
8202 ** read into internal hash tables.
8203 **
8204 ** DB_UnresetViews means that one or more views have column names that
8205 ** have been filled out.  If the schema changes, these column names might
8206 ** changes and so the view will need to be reset.
8207 */
8208 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
8209 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
8210 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
8211
8212 /*
8213 ** The number of different kinds of things that can be limited
8214 ** using the sqlite3_limit() interface.
8215 */
8216 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
8217
8218 /*
8219 ** Lookaside malloc is a set of fixed-size buffers that can be used
8220 ** to satisfy small transient memory allocation requests for objects
8221 ** associated with a particular database connection.  The use of
8222 ** lookaside malloc provides a significant performance enhancement
8223 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
8224 ** SQL statements.
8225 **
8226 ** The Lookaside structure holds configuration information about the
8227 ** lookaside malloc subsystem.  Each available memory allocation in
8228 ** the lookaside subsystem is stored on a linked list of LookasideSlot
8229 ** objects.
8230 **
8231 ** Lookaside allocations are only allowed for objects that are associated
8232 ** with a particular database connection.  Hence, schema information cannot
8233 ** be stored in lookaside because in shared cache mode the schema information
8234 ** is shared by multiple database connections.  Therefore, while parsing
8235 ** schema information, the Lookaside.bEnabled flag is cleared so that
8236 ** lookaside allocations are not used to construct the schema objects.
8237 */
8238 struct Lookaside {
8239   u16 sz;                 /* Size of each buffer in bytes */
8240   u8 bEnabled;            /* False to disable new lookaside allocations */
8241   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
8242   int nOut;               /* Number of buffers currently checked out */
8243   int mxOut;              /* Highwater mark for nOut */
8244   LookasideSlot *pFree;   /* List of available buffers */
8245   void *pStart;           /* First byte of available memory space */
8246   void *pEnd;             /* First byte past end of available space */
8247 };
8248 struct LookasideSlot {
8249   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
8250 };
8251
8252 /*
8253 ** A hash table for function definitions.
8254 **
8255 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
8256 ** Collisions are on the FuncDef.pHash chain.
8257 */
8258 struct FuncDefHash {
8259   FuncDef *a[23];       /* Hash table for functions */
8260 };
8261
8262 /*
8263 ** Each database is an instance of the following structure.
8264 **
8265 ** The sqlite.lastRowid records the last insert rowid generated by an
8266 ** insert statement.  Inserts on views do not affect its value.  Each
8267 ** trigger has its own context, so that lastRowid can be updated inside
8268 ** triggers as usual.  The previous value will be restored once the trigger
8269 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
8270 ** longer (since after version 2.8.12) reset to -1.
8271 **
8272 ** The sqlite.nChange does not count changes within triggers and keeps no
8273 ** context.  It is reset at start of sqlite3_exec.
8274 ** The sqlite.lsChange represents the number of changes made by the last
8275 ** insert, update, or delete statement.  It remains constant throughout the
8276 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
8277 ** context stack just like lastRowid so that the count of changes
8278 ** within a trigger is not seen outside the trigger.  Changes to views do not
8279 ** affect the value of lsChange.
8280 ** The sqlite.csChange keeps track of the number of current changes (since
8281 ** the last statement) and is used to update sqlite_lsChange.
8282 **
8283 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
8284 ** store the most recent error code and, if applicable, string. The
8285 ** internal function sqlite3Error() is used to set these variables
8286 ** consistently.
8287 */
8288 struct sqlite3 {
8289   sqlite3_vfs *pVfs;            /* OS Interface */
8290   int nDb;                      /* Number of backends currently in use */
8291   Db *aDb;                      /* All backends */
8292   int flags;                    /* Miscellaneous flags. See below */
8293   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
8294   int errCode;                  /* Most recent error code (SQLITE_*) */
8295   int errMask;                  /* & result codes with this before returning */
8296   u8 autoCommit;                /* The auto-commit flag. */
8297   u8 temp_store;                /* 1: file 2: memory 0: default */
8298   u8 mallocFailed;              /* True if we have seen a malloc failure */
8299   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8300   u8 dfltJournalMode;           /* Default journal mode for attached dbs */
8301   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8302   int nextPagesize;             /* Pagesize after VACUUM if >0 */
8303   int nTable;                   /* Number of tables in the database */
8304   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
8305   i64 lastRowid;                /* ROWID of most recent insert (see above) */
8306   u32 magic;                    /* Magic number for detect library misuse */
8307   int nChange;                  /* Value returned by sqlite3_changes() */
8308   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
8309   sqlite3_mutex *mutex;         /* Connection mutex */
8310   int aLimit[SQLITE_N_LIMIT];   /* Limits */
8311   struct sqlite3InitInfo {      /* Information used during initialization */
8312     int iDb;                    /* When back is being initialized */
8313     int newTnum;                /* Rootpage of table being initialized */
8314     u8 busy;                    /* TRUE if currently initializing */
8315     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
8316   } init;
8317   int nExtension;               /* Number of loaded extensions */
8318   void **aExtension;            /* Array of shared library handles */
8319   struct Vdbe *pVdbe;           /* List of active virtual machines */
8320   int activeVdbeCnt;            /* Number of VDBEs currently executing */
8321   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
8322   void (*xTrace)(void*,const char*);        /* Trace function */
8323   void *pTraceArg;                          /* Argument to the trace function */
8324   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
8325   void *pProfileArg;                        /* Argument to profile function */
8326   void *pCommitArg;                 /* Argument to xCommitCallback() */   
8327   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
8328   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
8329   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
8330   void *pUpdateArg;
8331   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
8332   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
8333   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
8334   void *pCollNeededArg;
8335   sqlite3_value *pErr;          /* Most recent error message */
8336   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
8337   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
8338   union {
8339     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
8340     double notUsed1;            /* Spacer */
8341   } u1;
8342   Lookaside lookaside;          /* Lookaside malloc configuration */
8343 #ifndef SQLITE_OMIT_AUTHORIZATION
8344   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
8345                                 /* Access authorization function */
8346   void *pAuthArg;               /* 1st argument to the access auth function */
8347 #endif
8348 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8349   int (*xProgress)(void *);     /* The progress callback */
8350   void *pProgressArg;           /* Argument to the progress callback */
8351   int nProgressOps;             /* Number of opcodes for progress callback */
8352 #endif
8353 #ifndef SQLITE_OMIT_VIRTUALTABLE
8354   Hash aModule;                 /* populated by sqlite3_create_module() */
8355   Table *pVTab;                 /* vtab with active Connect/Create method */
8356   VTable **aVTrans;             /* Virtual tables with open transactions */
8357   int nVTrans;                  /* Allocated size of aVTrans */
8358   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
8359 #endif
8360   FuncDefHash aFunc;            /* Hash table of connection functions */
8361   Hash aCollSeq;                /* All collating sequences */
8362   BusyHandler busyHandler;      /* Busy callback */
8363   int busyTimeout;              /* Busy handler timeout, in msec */
8364   Db aDbStatic[2];              /* Static space for the 2 default backends */
8365   Savepoint *pSavepoint;        /* List of active savepoints */
8366   int nSavepoint;               /* Number of non-transaction savepoints */
8367   int nStatement;               /* Number of nested statement-transactions  */
8368   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
8369   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
8370
8371 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
8372   /* The following variables are all protected by the STATIC_MASTER 
8373   ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
8374   **
8375   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
8376   ** unlock so that it can proceed.
8377   **
8378   ** When X.pBlockingConnection==Y, that means that something that X tried
8379   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
8380   ** held by Y.
8381   */
8382   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
8383   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
8384   void *pUnlockArg;                     /* Argument to xUnlockNotify */
8385   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
8386   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
8387 #endif
8388 };
8389
8390 /*
8391 ** A macro to discover the encoding of a database.
8392 */
8393 #define ENC(db) ((db)->aDb[0].pSchema->enc)
8394
8395 /*
8396 ** Possible values for the sqlite3.flags.
8397 */
8398 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
8399 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
8400 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
8401 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
8402 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
8403                                           /*   DELETE, or UPDATE and return */
8404                                           /*   the count using a callback. */
8405 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
8406                                           /*   result set is empty */
8407 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
8408 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
8409 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
8410 #define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when 
8411                                           ** accessing read-only databases */
8412 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
8413 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
8414 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
8415 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
8416 #define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
8417 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
8418 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
8419 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
8420 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
8421
8422 /*
8423 ** Bits of the sqlite3.flags field that are used by the
8424 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
8425 ** These must be the low-order bits of the flags field.
8426 */
8427 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
8428 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
8429 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
8430 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
8431 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
8432 #define SQLITE_OptMask        0x1f        /* Mask of all disablable opts */
8433
8434 /*
8435 ** Possible values for the sqlite.magic field.
8436 ** The numbers are obtained at random and have no special meaning, other
8437 ** than being distinct from one another.
8438 */
8439 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
8440 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
8441 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
8442 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
8443 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
8444
8445 /*
8446 ** Each SQL function is defined by an instance of the following
8447 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
8448 ** hash table.  When multiple functions have the same name, the hash table
8449 ** points to a linked list of these structures.
8450 */
8451 struct FuncDef {
8452   i16 nArg;            /* Number of arguments.  -1 means unlimited */
8453   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
8454   u8 flags;            /* Some combination of SQLITE_FUNC_* */
8455   void *pUserData;     /* User data parameter */
8456   FuncDef *pNext;      /* Next function with same name */
8457   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
8458   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
8459   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
8460   char *zName;         /* SQL name of the function. */
8461   FuncDef *pHash;      /* Next with a different name but the same hash */
8462 };
8463
8464 /*
8465 ** Possible values for FuncDef.flags
8466 */
8467 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
8468 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
8469 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
8470 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
8471 #define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
8472 #define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
8473 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
8474
8475 /*
8476 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
8477 ** used to create the initializers for the FuncDef structures.
8478 **
8479 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
8480 **     Used to create a scalar function definition of a function zName 
8481 **     implemented by C function xFunc that accepts nArg arguments. The
8482 **     value passed as iArg is cast to a (void*) and made available
8483 **     as the user-data (sqlite3_user_data()) for the function. If 
8484 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
8485 **
8486 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
8487 **     Used to create an aggregate function definition implemented by
8488 **     the C functions xStep and xFinal. The first four parameters
8489 **     are interpreted in the same way as the first 4 parameters to
8490 **     FUNCTION().
8491 **
8492 **   LIKEFUNC(zName, nArg, pArg, flags)
8493 **     Used to create a scalar function definition of a function zName 
8494 **     that accepts nArg arguments and is implemented by a call to C 
8495 **     function likeFunc. Argument pArg is cast to a (void *) and made
8496 **     available as the function user-data (sqlite3_user_data()). The
8497 **     FuncDef.flags variable is set to the value passed as the flags
8498 **     parameter.
8499 */
8500 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
8501   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8502    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
8503 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
8504   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8505    pArg, 0, xFunc, 0, 0, #zName, 0}
8506 #define LIKEFUNC(zName, nArg, arg, flags) \
8507   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
8508 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
8509   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
8510    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
8511
8512 /*
8513 ** All current savepoints are stored in a linked list starting at
8514 ** sqlite3.pSavepoint. The first element in the list is the most recently
8515 ** opened savepoint. Savepoints are added to the list by the vdbe
8516 ** OP_Savepoint instruction.
8517 */
8518 struct Savepoint {
8519   char *zName;                        /* Savepoint name (nul-terminated) */
8520   i64 nDeferredCons;                  /* Number of deferred fk violations */
8521   Savepoint *pNext;                   /* Parent savepoint (if any) */
8522 };
8523
8524 /*
8525 ** The following are used as the second parameter to sqlite3Savepoint(),
8526 ** and as the P1 argument to the OP_Savepoint instruction.
8527 */
8528 #define SAVEPOINT_BEGIN      0
8529 #define SAVEPOINT_RELEASE    1
8530 #define SAVEPOINT_ROLLBACK   2
8531
8532
8533 /*
8534 ** Each SQLite module (virtual table definition) is defined by an
8535 ** instance of the following structure, stored in the sqlite3.aModule
8536 ** hash table.
8537 */
8538 struct Module {
8539   const sqlite3_module *pModule;       /* Callback pointers */
8540   const char *zName;                   /* Name passed to create_module() */
8541   void *pAux;                          /* pAux passed to create_module() */
8542   void (*xDestroy)(void *);            /* Module destructor function */
8543 };
8544
8545 /*
8546 ** information about each column of an SQL table is held in an instance
8547 ** of this structure.
8548 */
8549 struct Column {
8550   char *zName;     /* Name of this column */
8551   Expr *pDflt;     /* Default value of this column */
8552   char *zDflt;     /* Original text of the default value */
8553   char *zType;     /* Data type for this column */
8554   char *zColl;     /* Collating sequence.  If NULL, use the default */
8555   u8 notNull;      /* True if there is a NOT NULL constraint */
8556   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
8557   char affinity;   /* One of the SQLITE_AFF_... values */
8558 #ifndef SQLITE_OMIT_VIRTUALTABLE
8559   u8 isHidden;     /* True if this column is 'hidden' */
8560 #endif
8561 };
8562
8563 /*
8564 ** A "Collating Sequence" is defined by an instance of the following
8565 ** structure. Conceptually, a collating sequence consists of a name and
8566 ** a comparison routine that defines the order of that sequence.
8567 **
8568 ** There may two separate implementations of the collation function, one
8569 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
8570 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
8571 ** native byte order. When a collation sequence is invoked, SQLite selects
8572 ** the version that will require the least expensive encoding
8573 ** translations, if any.
8574 **
8575 ** The CollSeq.pUser member variable is an extra parameter that passed in
8576 ** as the first argument to the UTF-8 comparison function, xCmp.
8577 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
8578 ** xCmp16.
8579 **
8580 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
8581 ** collating sequence is undefined.  Indices built on an undefined
8582 ** collating sequence may not be read or written.
8583 */
8584 struct CollSeq {
8585   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
8586   u8 enc;               /* Text encoding handled by xCmp() */
8587   u8 type;              /* One of the SQLITE_COLL_... values below */
8588   void *pUser;          /* First argument to xCmp() */
8589   int (*xCmp)(void*,int, const void*, int, const void*);
8590   void (*xDel)(void*);  /* Destructor for pUser */
8591 };
8592
8593 /*
8594 ** Allowed values of CollSeq.type:
8595 */
8596 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
8597 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
8598 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
8599 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
8600
8601 /*
8602 ** A sort order can be either ASC or DESC.
8603 */
8604 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
8605 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
8606
8607 /*
8608 ** Column affinity types.
8609 **
8610 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
8611 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
8612 ** the speed a little by numbering the values consecutively.  
8613 **
8614 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
8615 ** when multiple affinity types are concatenated into a string and
8616 ** used as the P4 operand, they will be more readable.
8617 **
8618 ** Note also that the numeric types are grouped together so that testing
8619 ** for a numeric type is a single comparison.
8620 */
8621 #define SQLITE_AFF_TEXT     'a'
8622 #define SQLITE_AFF_NONE     'b'
8623 #define SQLITE_AFF_NUMERIC  'c'
8624 #define SQLITE_AFF_INTEGER  'd'
8625 #define SQLITE_AFF_REAL     'e'
8626
8627 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
8628
8629 /*
8630 ** The SQLITE_AFF_MASK values masks off the significant bits of an
8631 ** affinity value. 
8632 */
8633 #define SQLITE_AFF_MASK     0x67
8634
8635 /*
8636 ** Additional bit values that can be ORed with an affinity without
8637 ** changing the affinity.
8638 */
8639 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
8640 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
8641 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
8642
8643 /*
8644 ** An object of this type is created for each virtual table present in
8645 ** the database schema. 
8646 **
8647 ** If the database schema is shared, then there is one instance of this
8648 ** structure for each database connection (sqlite3*) that uses the shared
8649 ** schema. This is because each database connection requires its own unique
8650 ** instance of the sqlite3_vtab* handle used to access the virtual table 
8651 ** implementation. sqlite3_vtab* handles can not be shared between 
8652 ** database connections, even when the rest of the in-memory database 
8653 ** schema is shared, as the implementation often stores the database
8654 ** connection handle passed to it via the xConnect() or xCreate() method
8655 ** during initialization internally. This database connection handle may
8656 ** then used by the virtual table implementation to access real tables 
8657 ** within the database. So that they appear as part of the callers 
8658 ** transaction, these accesses need to be made via the same database 
8659 ** connection as that used to execute SQL operations on the virtual table.
8660 **
8661 ** All VTable objects that correspond to a single table in a shared
8662 ** database schema are initially stored in a linked-list pointed to by
8663 ** the Table.pVTable member variable of the corresponding Table object.
8664 ** When an sqlite3_prepare() operation is required to access the virtual
8665 ** table, it searches the list for the VTable that corresponds to the
8666 ** database connection doing the preparing so as to use the correct
8667 ** sqlite3_vtab* handle in the compiled query.
8668 **
8669 ** When an in-memory Table object is deleted (for example when the
8670 ** schema is being reloaded for some reason), the VTable objects are not 
8671 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
8672 ** immediately. Instead, they are moved from the Table.pVTable list to
8673 ** another linked list headed by the sqlite3.pDisconnect member of the
8674 ** corresponding sqlite3 structure. They are then deleted/xDisconnected 
8675 ** next time a statement is prepared using said sqlite3*. This is done
8676 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
8677 ** Refer to comments above function sqlite3VtabUnlockList() for an
8678 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
8679 ** list without holding the corresponding sqlite3.mutex mutex.
8680 **
8681 ** The memory for objects of this type is always allocated by 
8682 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
8683 ** the first argument.
8684 */
8685 struct VTable {
8686   sqlite3 *db;              /* Database connection associated with this table */
8687   Module *pMod;             /* Pointer to module implementation */
8688   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
8689   int nRef;                 /* Number of pointers to this structure */
8690   VTable *pNext;            /* Next in linked list (see above) */
8691 };
8692
8693 /*
8694 ** Each SQL table is represented in memory by an instance of the
8695 ** following structure.
8696 **
8697 ** Table.zName is the name of the table.  The case of the original
8698 ** CREATE TABLE statement is stored, but case is not significant for
8699 ** comparisons.
8700 **
8701 ** Table.nCol is the number of columns in this table.  Table.aCol is a
8702 ** pointer to an array of Column structures, one for each column.
8703 **
8704 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
8705 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
8706 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
8707 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
8708 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
8709 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
8710 ** the table has any PRIMARY KEY, INTEGER or otherwise.
8711 **
8712 ** Table.tnum is the page number for the root BTree page of the table in the
8713 ** database file.  If Table.iDb is the index of the database table backend
8714 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
8715 ** holds temporary tables and indices.  If TF_Ephemeral is set
8716 ** then the table is stored in a file that is automatically deleted
8717 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
8718 ** refers VDBE cursor number that holds the table open, not to the root
8719 ** page number.  Transient tables are used to hold the results of a
8720 ** sub-query that appears instead of a real table name in the FROM clause 
8721 ** of a SELECT statement.
8722 */
8723 struct Table {
8724   sqlite3 *dbMem;      /* DB connection used for lookaside allocations. */
8725   char *zName;         /* Name of the table or view */
8726   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
8727   int nCol;            /* Number of columns in this table */
8728   Column *aCol;        /* Information about each column */
8729   Index *pIndex;       /* List of SQL indexes on this table. */
8730   int tnum;            /* Root BTree node for this table (see note above) */
8731   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
8732   u16 nRef;            /* Number of pointers to this Table */
8733   u8 tabFlags;         /* Mask of TF_* values */
8734   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
8735   FKey *pFKey;         /* Linked list of all foreign keys in this table */
8736   char *zColAff;       /* String defining the affinity of each column */
8737 #ifndef SQLITE_OMIT_CHECK
8738   Expr *pCheck;        /* The AND of all CHECK constraints */
8739 #endif
8740 #ifndef SQLITE_OMIT_ALTERTABLE
8741   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
8742 #endif
8743 #ifndef SQLITE_OMIT_VIRTUALTABLE
8744   VTable *pVTable;     /* List of VTable objects. */
8745   int nModuleArg;      /* Number of arguments to the module */
8746   char **azModuleArg;  /* Text of all module args. [0] is module name */
8747 #endif
8748   Trigger *pTrigger;   /* List of triggers stored in pSchema */
8749   Schema *pSchema;     /* Schema that contains this table */
8750   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
8751 };
8752
8753 /*
8754 ** Allowed values for Tabe.tabFlags.
8755 */
8756 #define TF_Readonly        0x01    /* Read-only system table */
8757 #define TF_Ephemeral       0x02    /* An ephemeral table */
8758 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
8759 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
8760 #define TF_Virtual         0x10    /* Is a virtual table */
8761 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
8762
8763
8764
8765 /*
8766 ** Test to see whether or not a table is a virtual table.  This is
8767 ** done as a macro so that it will be optimized out when virtual
8768 ** table support is omitted from the build.
8769 */
8770 #ifndef SQLITE_OMIT_VIRTUALTABLE
8771 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
8772 #  define IsHiddenColumn(X) ((X)->isHidden)
8773 #else
8774 #  define IsVirtual(X)      0
8775 #  define IsHiddenColumn(X) 0
8776 #endif
8777
8778 /*
8779 ** Each foreign key constraint is an instance of the following structure.
8780 **
8781 ** A foreign key is associated with two tables.  The "from" table is
8782 ** the table that contains the REFERENCES clause that creates the foreign
8783 ** key.  The "to" table is the table that is named in the REFERENCES clause.
8784 ** Consider this example:
8785 **
8786 **     CREATE TABLE ex1(
8787 **       a INTEGER PRIMARY KEY,
8788 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
8789 **     );
8790 **
8791 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
8792 **
8793 ** Each REFERENCES clause generates an instance of the following structure
8794 ** which is attached to the from-table.  The to-table need not exist when
8795 ** the from-table is created.  The existence of the to-table is not checked.
8796 */
8797 struct FKey {
8798   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
8799   FKey *pNextFrom;  /* Next foreign key in pFrom */
8800   char *zTo;        /* Name of table that the key points to (aka: Parent) */
8801   FKey *pNextTo;    /* Next foreign key on table named zTo */
8802   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
8803   int nCol;         /* Number of columns in this key */
8804   /* EV: R-30323-21917 */
8805   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
8806   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
8807   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
8808   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
8809     int iFrom;         /* Index of column in pFrom */
8810     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
8811   } aCol[1];        /* One entry for each of nCol column s */
8812 };
8813
8814 /*
8815 ** SQLite supports many different ways to resolve a constraint
8816 ** error.  ROLLBACK processing means that a constraint violation
8817 ** causes the operation in process to fail and for the current transaction
8818 ** to be rolled back.  ABORT processing means the operation in process
8819 ** fails and any prior changes from that one operation are backed out,
8820 ** but the transaction is not rolled back.  FAIL processing means that
8821 ** the operation in progress stops and returns an error code.  But prior
8822 ** changes due to the same operation are not backed out and no rollback
8823 ** occurs.  IGNORE means that the particular row that caused the constraint
8824 ** error is not inserted or updated.  Processing continues and no error
8825 ** is returned.  REPLACE means that preexisting database rows that caused
8826 ** a UNIQUE constraint violation are removed so that the new insert or
8827 ** update can proceed.  Processing continues and no error is reported.
8828 **
8829 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
8830 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
8831 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
8832 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
8833 ** referenced table row is propagated into the row that holds the
8834 ** foreign key.
8835 ** 
8836 ** The following symbolic values are used to record which type
8837 ** of action to take.
8838 */
8839 #define OE_None     0   /* There is no constraint to check */
8840 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
8841 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
8842 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
8843 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
8844 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
8845
8846 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
8847 #define OE_SetNull  7   /* Set the foreign key value to NULL */
8848 #define OE_SetDflt  8   /* Set the foreign key value to its default */
8849 #define OE_Cascade  9   /* Cascade the changes */
8850
8851 #define OE_Default  99  /* Do whatever the default action is */
8852
8853
8854 /*
8855 ** An instance of the following structure is passed as the first
8856 ** argument to sqlite3VdbeKeyCompare and is used to control the 
8857 ** comparison of the two index keys.
8858 */
8859 struct KeyInfo {
8860   sqlite3 *db;        /* The database connection */
8861   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
8862   u16 nField;         /* Number of entries in aColl[] */
8863   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
8864   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
8865 };
8866
8867 /*
8868 ** An instance of the following structure holds information about a
8869 ** single index record that has already been parsed out into individual
8870 ** values.
8871 **
8872 ** A record is an object that contains one or more fields of data.
8873 ** Records are used to store the content of a table row and to store
8874 ** the key of an index.  A blob encoding of a record is created by
8875 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
8876 ** OP_Column opcode.
8877 **
8878 ** This structure holds a record that has already been disassembled
8879 ** into its constituent fields.
8880 */
8881 struct UnpackedRecord {
8882   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
8883   u16 nField;         /* Number of entries in apMem[] */
8884   u16 flags;          /* Boolean settings.  UNPACKED_... below */
8885   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
8886   Mem *aMem;          /* Values */
8887 };
8888
8889 /*
8890 ** Allowed values of UnpackedRecord.flags
8891 */
8892 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
8893 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
8894 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
8895 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
8896 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
8897 #define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
8898
8899 /*
8900 ** Each SQL index is represented in memory by an
8901 ** instance of the following structure.
8902 **
8903 ** The columns of the table that are to be indexed are described
8904 ** by the aiColumn[] field of this structure.  For example, suppose
8905 ** we have the following table and index:
8906 **
8907 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
8908 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
8909 **
8910 ** In the Table structure describing Ex1, nCol==3 because there are
8911 ** three columns in the table.  In the Index structure describing
8912 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
8913 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
8914 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
8915 ** The second column to be indexed (c1) has an index of 0 in
8916 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
8917 **
8918 ** The Index.onError field determines whether or not the indexed columns
8919 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
8920 ** it means this is not a unique index.  Otherwise it is a unique index
8921 ** and the value of Index.onError indicate the which conflict resolution 
8922 ** algorithm to employ whenever an attempt is made to insert a non-unique
8923 ** element.
8924 */
8925 struct Index {
8926   char *zName;     /* Name of this index */
8927   int nColumn;     /* Number of columns in the table used by this index */
8928   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
8929   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
8930   Table *pTable;   /* The SQL table being indexed */
8931   int tnum;        /* Page containing root of this index in database file */
8932   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
8933   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
8934   char *zColAff;   /* String defining the affinity of each column */
8935   Index *pNext;    /* The next index associated with the same table */
8936   Schema *pSchema; /* Schema containing this index */
8937   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
8938   char **azColl;   /* Array of collation sequence names for index */
8939   IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
8940 };
8941
8942 /*
8943 ** Each sample stored in the sqlite_stat2 table is represented in memory 
8944 ** using a structure of this type.
8945 */
8946 struct IndexSample {
8947   union {
8948     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
8949     double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
8950   } u;
8951   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
8952   u8 nByte;         /* Size in byte of text or blob. */
8953 };
8954
8955 /*
8956 ** Each token coming out of the lexer is an instance of
8957 ** this structure.  Tokens are also used as part of an expression.
8958 **
8959 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
8960 ** may contain random values.  Do not make any assumptions about Token.dyn
8961 ** and Token.n when Token.z==0.
8962 */
8963 struct Token {
8964   const char *z;     /* Text of the token.  Not NULL-terminated! */
8965   unsigned int n;    /* Number of characters in this token */
8966 };
8967
8968 /*
8969 ** An instance of this structure contains information needed to generate
8970 ** code for a SELECT that contains aggregate functions.
8971 **
8972 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
8973 ** pointer to this structure.  The Expr.iColumn field is the index in
8974 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
8975 ** code for that node.
8976 **
8977 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
8978 ** original Select structure that describes the SELECT statement.  These
8979 ** fields do not need to be freed when deallocating the AggInfo structure.
8980 */
8981 struct AggInfo {
8982   u8 directMode;          /* Direct rendering mode means take data directly
8983                           ** from source tables rather than from accumulators */
8984   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
8985                           ** than the source table */
8986   int sortingIdx;         /* Cursor number of the sorting index */
8987   ExprList *pGroupBy;     /* The group by clause */
8988   int nSortingColumn;     /* Number of columns in the sorting index */
8989   struct AggInfo_col {    /* For each column used in source tables */
8990     Table *pTab;             /* Source table */
8991     int iTable;              /* Cursor number of the source table */
8992     int iColumn;             /* Column number within the source table */
8993     int iSorterColumn;       /* Column number in the sorting index */
8994     int iMem;                /* Memory location that acts as accumulator */
8995     Expr *pExpr;             /* The original expression */
8996   } *aCol;
8997   int nColumn;            /* Number of used entries in aCol[] */
8998   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
8999   int nAccumulator;       /* Number of columns that show through to the output.
9000                           ** Additional columns are used only as parameters to
9001                           ** aggregate functions */
9002   struct AggInfo_func {   /* For each aggregate function */
9003     Expr *pExpr;             /* Expression encoding the function */
9004     FuncDef *pFunc;          /* The aggregate function implementation */
9005     int iMem;                /* Memory location that acts as accumulator */
9006     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
9007   } *aFunc;
9008   int nFunc;              /* Number of entries in aFunc[] */
9009   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9010 };
9011
9012 /*
9013 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9014 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
9015 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
9016 ** it uses less memory in the Expr object, which is a big memory user
9017 ** in systems with lots of prepared statements.  And few applications
9018 ** need more than about 10 or 20 variables.  But some extreme users want
9019 ** to have prepared statements with over 32767 variables, and for them
9020 ** the option is available (at compile-time).
9021 */
9022 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
9023 typedef i16 ynVar;
9024 #else
9025 typedef int ynVar;
9026 #endif
9027
9028 /*
9029 ** Each node of an expression in the parse tree is an instance
9030 ** of this structure.
9031 **
9032 ** Expr.op is the opcode. The integer parser token codes are reused
9033 ** as opcodes here. For example, the parser defines TK_GE to be an integer
9034 ** code representing the ">=" operator. This same integer code is reused
9035 ** to represent the greater-than-or-equal-to operator in the expression
9036 ** tree.
9037 **
9038 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
9039 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9040 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
9041 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9042 ** then Expr.token contains the name of the function.
9043 **
9044 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9045 ** binary operator. Either or both may be NULL.
9046 **
9047 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
9048 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9049 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9050 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9051 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
9052 ** valid.
9053 **
9054 ** An expression of the form ID or ID.ID refers to a column in a table.
9055 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9056 ** the integer cursor number of a VDBE cursor pointing to that table and
9057 ** Expr.iColumn is the column number for the specific column.  If the
9058 ** expression is used as a result in an aggregate SELECT, then the
9059 ** value is also stored in the Expr.iAgg column in the aggregate so that
9060 ** it can be accessed after all aggregates are computed.
9061 **
9062 ** If the expression is an unbound variable marker (a question mark 
9063 ** character '?' in the original SQL) then the Expr.iTable holds the index 
9064 ** number for that variable.
9065 **
9066 ** If the expression is a subquery then Expr.iColumn holds an integer
9067 ** register number containing the result of the subquery.  If the
9068 ** subquery gives a constant result, then iTable is -1.  If the subquery
9069 ** gives a different answer at different times during statement processing
9070 ** then iTable is the address of a subroutine that computes the subquery.
9071 **
9072 ** If the Expr is of type OP_Column, and the table it is selecting from
9073 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
9074 ** corresponding table definition.
9075 **
9076 ** ALLOCATION NOTES:
9077 **
9078 ** Expr objects can use a lot of memory space in database schema.  To
9079 ** help reduce memory requirements, sometimes an Expr object will be
9080 ** truncated.  And to reduce the number of memory allocations, sometimes
9081 ** two or more Expr objects will be stored in a single memory allocation,
9082 ** together with Expr.zToken strings.
9083 **
9084 ** If the EP_Reduced and EP_TokenOnly flags are set when
9085 ** an Expr object is truncated.  When EP_Reduced is set, then all
9086 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9087 ** are contained within the same memory allocation.  Note, however, that
9088 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9089 ** allocated, regardless of whether or not EP_Reduced is set.
9090 */
9091 struct Expr {
9092   u8 op;                 /* Operation performed by this node */
9093   char affinity;         /* The affinity of the column or 0 if not a column */
9094   u16 flags;             /* Various flags.  EP_* See below */
9095   union {
9096     char *zToken;          /* Token value. Zero terminated and dequoted */
9097     int iValue;            /* Integer value if EP_IntValue */
9098   } u;
9099
9100   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9101   ** space is allocated for the fields below this point. An attempt to
9102   ** access them will result in a segfault or malfunction. 
9103   *********************************************************************/
9104
9105   Expr *pLeft;           /* Left subnode */
9106   Expr *pRight;          /* Right subnode */
9107   union {
9108     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
9109     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
9110   } x;
9111   CollSeq *pColl;        /* The collation type of the column or 0 */
9112
9113   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
9114   ** space is allocated for the fields below this point. An attempt to
9115   ** access them will result in a segfault or malfunction.
9116   *********************************************************************/
9117
9118   int iTable;            /* TK_COLUMN: cursor number of table holding column
9119                          ** TK_REGISTER: register number
9120                          ** TK_TRIGGER: 1 -> new, 0 -> old */
9121   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
9122                          ** TK_VARIABLE: variable number (always >= 1). */
9123   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9124   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9125   u8 flags2;             /* Second set of flags.  EP2_... */
9126   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
9127   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9128   Table *pTab;           /* Table for TK_COLUMN expressions. */
9129 #if SQLITE_MAX_EXPR_DEPTH>0
9130   int nHeight;           /* Height of the tree headed by this node */
9131 #endif
9132 };
9133
9134 /*
9135 ** The following are the meanings of bits in the Expr.flags field.
9136 */
9137 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9138 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9139 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9140 #define EP_Error      0x0008  /* Expression contains one or more errors */
9141 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9142 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9143 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
9144 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9145 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9146 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
9147 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
9148 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
9149
9150 #define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
9151 #define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
9152 #define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
9153
9154 /*
9155 ** The following are the meanings of bits in the Expr.flags2 field.
9156 */
9157 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
9158 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
9159
9160 /*
9161 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
9162 ** flag on an expression structure.  This flag is used for VV&A only.  The
9163 ** routine is implemented as a macro that only works when in debugging mode,
9164 ** so as not to burden production code.
9165 */
9166 #ifdef SQLITE_DEBUG
9167 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
9168 #else
9169 # define ExprSetIrreducible(X)
9170 #endif
9171
9172 /*
9173 ** These macros can be used to test, set, or clear bits in the 
9174 ** Expr.flags field.
9175 */
9176 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9177 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9178 #define ExprSetProperty(E,P)     (E)->flags|=(P)
9179 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
9180
9181 /*
9182 ** Macros to determine the number of bytes required by a normal Expr 
9183 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
9184 ** and an Expr struct with the EP_TokenOnly flag set.
9185 */
9186 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
9187 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
9188 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
9189
9190 /*
9191 ** Flags passed to the sqlite3ExprDup() function. See the header comment 
9192 ** above sqlite3ExprDup() for details.
9193 */
9194 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
9195
9196 /*
9197 ** A list of expressions.  Each expression may optionally have a
9198 ** name.  An expr/name combination can be used in several ways, such
9199 ** as the list of "expr AS ID" fields following a "SELECT" or in the
9200 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
9201 ** also be used as the argument to a function, in which case the a.zName
9202 ** field is not used.
9203 */
9204 struct ExprList {
9205   int nExpr;             /* Number of expressions on the list */
9206   int nAlloc;            /* Number of entries allocated below */
9207   int iECursor;          /* VDBE Cursor associated with this ExprList */
9208   struct ExprList_item {
9209     Expr *pExpr;           /* The list of expressions */
9210     char *zName;           /* Token associated with this expression */
9211     char *zSpan;           /* Original text of the expression */
9212     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9213     u8 done;               /* A flag to indicate when processing is finished */
9214     u16 iCol;              /* For ORDER BY, column number in result set */
9215     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
9216   } *a;                  /* One entry for each expression */
9217 };
9218
9219 /*
9220 ** An instance of this structure is used by the parser to record both
9221 ** the parse tree for an expression and the span of input text for an
9222 ** expression.
9223 */
9224 struct ExprSpan {
9225   Expr *pExpr;          /* The expression parse tree */
9226   const char *zStart;   /* First character of input text */
9227   const char *zEnd;     /* One character past the end of input text */
9228 };
9229
9230 /*
9231 ** An instance of this structure can hold a simple list of identifiers,
9232 ** such as the list "a,b,c" in the following statements:
9233 **
9234 **      INSERT INTO t(a,b,c) VALUES ...;
9235 **      CREATE INDEX idx ON t(a,b,c);
9236 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9237 **
9238 ** The IdList.a.idx field is used when the IdList represents the list of
9239 ** column names after a table name in an INSERT statement.  In the statement
9240 **
9241 **     INSERT INTO t(a,b,c) ...
9242 **
9243 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9244 */
9245 struct IdList {
9246   struct IdList_item {
9247     char *zName;      /* Name of the identifier */
9248     int idx;          /* Index in some Table.aCol[] of a column named zName */
9249   } *a;
9250   int nId;         /* Number of identifiers on the list */
9251   int nAlloc;      /* Number of entries allocated for a[] below */
9252 };
9253
9254 /*
9255 ** The bitmask datatype defined below is used for various optimizations.
9256 **
9257 ** Changing this from a 64-bit to a 32-bit type limits the number of
9258 ** tables in a join to 32 instead of 64.  But it also reduces the size
9259 ** of the library by 738 bytes on ix86.
9260 */
9261 typedef u64 Bitmask;
9262
9263 /*
9264 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
9265 */
9266 #define BMS  ((int)(sizeof(Bitmask)*8))
9267
9268 /*
9269 ** The following structure describes the FROM clause of a SELECT statement.
9270 ** Each table or subquery in the FROM clause is a separate element of
9271 ** the SrcList.a[] array.
9272 **
9273 ** With the addition of multiple database support, the following structure
9274 ** can also be used to describe a particular table such as the table that
9275 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
9276 ** such a table must be a simple name: ID.  But in SQLite, the table can
9277 ** now be identified by a database name, a dot, then the table name: ID.ID.
9278 **
9279 ** The jointype starts out showing the join type between the current table
9280 ** and the next table on the list.  The parser builds the list this way.
9281 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9282 ** jointype expresses the join between the table and the previous table.
9283 */
9284 struct SrcList {
9285   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9286   i16 nAlloc;      /* Number of entries allocated in a[] below */
9287   struct SrcList_item {
9288     char *zDatabase;  /* Name of database holding this table */
9289     char *zName;      /* Name of the table */
9290     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
9291     Table *pTab;      /* An SQL table corresponding to zName */
9292     Select *pSelect;  /* A SELECT statement used in place of a table name */
9293     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
9294     u8 jointype;      /* Type of join between this able and the previous */
9295     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
9296     int iCursor;      /* The VDBE cursor number used to access this table */
9297     Expr *pOn;        /* The ON clause of a join */
9298     IdList *pUsing;   /* The USING clause of a join */
9299     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
9300     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
9301     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
9302   } a[1];             /* One entry for each identifier on the list */
9303 };
9304
9305 /*
9306 ** Permitted values of the SrcList.a.jointype field
9307 */
9308 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
9309 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
9310 #define JT_NATURAL   0x0004    /* True for a "natural" join */
9311 #define JT_LEFT      0x0008    /* Left outer join */
9312 #define JT_RIGHT     0x0010    /* Right outer join */
9313 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
9314 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
9315
9316
9317 /*
9318 ** A WherePlan object holds information that describes a lookup
9319 ** strategy.
9320 **
9321 ** This object is intended to be opaque outside of the where.c module.
9322 ** It is included here only so that that compiler will know how big it
9323 ** is.  None of the fields in this object should be used outside of
9324 ** the where.c module.
9325 **
9326 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
9327 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
9328 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
9329 ** case that more than one of these conditions is true.
9330 */
9331 struct WherePlan {
9332   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
9333   u32 nEq;                       /* Number of == constraints */
9334   union {
9335     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
9336     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
9337     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
9338   } u;
9339 };
9340
9341 /*
9342 ** For each nested loop in a WHERE clause implementation, the WhereInfo
9343 ** structure contains a single instance of this structure.  This structure
9344 ** is intended to be private the the where.c module and should not be
9345 ** access or modified by other modules.
9346 **
9347 ** The pIdxInfo field is used to help pick the best index on a
9348 ** virtual table.  The pIdxInfo pointer contains indexing
9349 ** information for the i-th table in the FROM clause before reordering.
9350 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
9351 ** All other information in the i-th WhereLevel object for the i-th table
9352 ** after FROM clause ordering.
9353 */
9354 struct WhereLevel {
9355   WherePlan plan;       /* query plan for this element of the FROM clause */
9356   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
9357   int iTabCur;          /* The VDBE cursor used to access the table */
9358   int iIdxCur;          /* The VDBE cursor used to access pIdx */
9359   int addrBrk;          /* Jump here to break out of the loop */
9360   int addrNxt;          /* Jump here to start the next IN combination */
9361   int addrCont;         /* Jump here to continue with the next loop cycle */
9362   int addrFirst;        /* First instruction of interior of the loop */
9363   u8 iFrom;             /* Which entry in the FROM clause */
9364   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
9365   int p1, p2;           /* Operands of the opcode used to ends the loop */
9366   union {               /* Information that depends on plan.wsFlags */
9367     struct {
9368       int nIn;              /* Number of entries in aInLoop[] */
9369       struct InLoop {
9370         int iCur;              /* The VDBE cursor used by this IN operator */
9371         int addrInTop;         /* Top of the IN loop */
9372       } *aInLoop;           /* Information about each nested IN operator */
9373     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
9374   } u;
9375
9376   /* The following field is really not part of the current level.  But
9377   ** we need a place to cache virtual table index information for each
9378   ** virtual table in the FROM clause and the WhereLevel structure is
9379   ** a convenient place since there is one WhereLevel for each FROM clause
9380   ** element.
9381   */
9382   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
9383 };
9384
9385 /*
9386 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
9387 ** and the WhereInfo.wctrlFlags member.
9388 */
9389 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
9390 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
9391 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
9392 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
9393 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
9394 #define WHERE_OMIT_OPEN        0x0010 /* Table cursor are already open */
9395 #define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
9396 #define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
9397 #define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
9398
9399 /*
9400 ** The WHERE clause processing routine has two halves.  The
9401 ** first part does the start of the WHERE loop and the second
9402 ** half does the tail of the WHERE loop.  An instance of
9403 ** this structure is returned by the first half and passed
9404 ** into the second half to give some continuity.
9405 */
9406 struct WhereInfo {
9407   Parse *pParse;       /* Parsing and code generating context */
9408   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
9409   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
9410   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
9411   SrcList *pTabList;             /* List of tables in the join */
9412   int iTop;                      /* The very beginning of the WHERE loop */
9413   int iContinue;                 /* Jump here to continue with next record */
9414   int iBreak;                    /* Jump here to break out of the loop */
9415   int nLevel;                    /* Number of nested loop */
9416   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
9417   WhereLevel a[1];               /* Information about each nest loop in WHERE */
9418 };
9419
9420 /*
9421 ** A NameContext defines a context in which to resolve table and column
9422 ** names.  The context consists of a list of tables (the pSrcList) field and
9423 ** a list of named expression (pEList).  The named expression list may
9424 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
9425 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
9426 ** pEList corresponds to the result set of a SELECT and is NULL for
9427 ** other statements.
9428 **
9429 ** NameContexts can be nested.  When resolving names, the inner-most 
9430 ** context is searched first.  If no match is found, the next outer
9431 ** context is checked.  If there is still no match, the next context
9432 ** is checked.  This process continues until either a match is found
9433 ** or all contexts are check.  When a match is found, the nRef member of
9434 ** the context containing the match is incremented. 
9435 **
9436 ** Each subquery gets a new NameContext.  The pNext field points to the
9437 ** NameContext in the parent query.  Thus the process of scanning the
9438 ** NameContext list corresponds to searching through successively outer
9439 ** subqueries looking for a match.
9440 */
9441 struct NameContext {
9442   Parse *pParse;       /* The parser */
9443   SrcList *pSrcList;   /* One or more tables used to resolve names */
9444   ExprList *pEList;    /* Optional list of named expressions */
9445   int nRef;            /* Number of names resolved by this context */
9446   int nErr;            /* Number of errors encountered while resolving names */
9447   u8 allowAgg;         /* Aggregate functions allowed here */
9448   u8 hasAgg;           /* True if aggregates are seen */
9449   u8 isCheck;          /* True if resolving names in a CHECK constraint */
9450   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
9451   AggInfo *pAggInfo;   /* Information about aggregates at this level */
9452   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
9453 };
9454
9455 /*
9456 ** An instance of the following structure contains all information
9457 ** needed to generate code for a single SELECT statement.
9458 **
9459 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
9460 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
9461 ** limit and nOffset to the value of the offset (or 0 if there is not
9462 ** offset).  But later on, nLimit and nOffset become the memory locations
9463 ** in the VDBE that record the limit and offset counters.
9464 **
9465 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
9466 ** These addresses must be stored so that we can go back and fill in
9467 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
9468 ** the number of columns in P2 can be computed at the same time
9469 ** as the OP_OpenEphm instruction is coded because not
9470 ** enough information about the compound query is known at that point.
9471 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
9472 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
9473 ** sequences for the ORDER BY clause.
9474 */
9475 struct Select {
9476   ExprList *pEList;      /* The fields of the result */
9477   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
9478   char affinity;         /* MakeRecord with this affinity for SRT_Set */
9479   u16 selFlags;          /* Various SF_* values */
9480   SrcList *pSrc;         /* The FROM clause */
9481   Expr *pWhere;          /* The WHERE clause */
9482   ExprList *pGroupBy;    /* The GROUP BY clause */
9483   Expr *pHaving;         /* The HAVING clause */
9484   ExprList *pOrderBy;    /* The ORDER BY clause */
9485   Select *pPrior;        /* Prior select in a compound select statement */
9486   Select *pNext;         /* Next select to the left in a compound */
9487   Select *pRightmost;    /* Right-most select in a compound select statement */
9488   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
9489   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
9490   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
9491   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
9492 };
9493
9494 /*
9495 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
9496 ** "Select Flag".
9497 */
9498 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
9499 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
9500 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
9501 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
9502 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
9503 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
9504
9505
9506 /*
9507 ** The results of a select can be distributed in several ways.  The
9508 ** "SRT" prefix means "SELECT Result Type".
9509 */
9510 #define SRT_Union        1  /* Store result as keys in an index */
9511 #define SRT_Except       2  /* Remove result from a UNION index */
9512 #define SRT_Exists       3  /* Store 1 if the result is not empty */
9513 #define SRT_Discard      4  /* Do not save the results anywhere */
9514
9515 /* The ORDER BY clause is ignored for all of the above */
9516 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
9517
9518 #define SRT_Output       5  /* Output each row of result */
9519 #define SRT_Mem          6  /* Store result in a memory cell */
9520 #define SRT_Set          7  /* Store results as keys in an index */
9521 #define SRT_Table        8  /* Store result as data with an automatic rowid */
9522 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
9523 #define SRT_Coroutine   10  /* Generate a single row of result */
9524
9525 /*
9526 ** A structure used to customize the behavior of sqlite3Select(). See
9527 ** comments above sqlite3Select() for details.
9528 */
9529 typedef struct SelectDest SelectDest;
9530 struct SelectDest {
9531   u8 eDest;         /* How to dispose of the results */
9532   u8 affinity;      /* Affinity used when eDest==SRT_Set */
9533   int iParm;        /* A parameter used by the eDest disposal method */
9534   int iMem;         /* Base register where results are written */
9535   int nMem;         /* Number of registers allocated */
9536 };
9537
9538 /*
9539 ** During code generation of statements that do inserts into AUTOINCREMENT 
9540 ** tables, the following information is attached to the Table.u.autoInc.p
9541 ** pointer of each autoincrement table to record some side information that
9542 ** the code generator needs.  We have to keep per-table autoincrement
9543 ** information in case inserts are down within triggers.  Triggers do not
9544 ** normally coordinate their activities, but we do need to coordinate the
9545 ** loading and saving of autoincrement information.
9546 */
9547 struct AutoincInfo {
9548   AutoincInfo *pNext;   /* Next info block in a list of them all */
9549   Table *pTab;          /* Table this info block refers to */
9550   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
9551   int regCtr;           /* Memory register holding the rowid counter */
9552 };
9553
9554 /*
9555 ** Size of the column cache
9556 */
9557 #ifndef SQLITE_N_COLCACHE
9558 # define SQLITE_N_COLCACHE 10
9559 #endif
9560
9561 /*
9562 ** At least one instance of the following structure is created for each 
9563 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
9564 ** statement. All such objects are stored in the linked list headed at
9565 ** Parse.pTriggerPrg and deleted once statement compilation has been
9566 ** completed.
9567 **
9568 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
9569 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
9570 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
9571 ** The Parse.pTriggerPrg list never contains two entries with the same
9572 ** values for both pTrigger and orconf.
9573 **
9574 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
9575 ** accessed (or set to 0 for triggers fired as a result of INSERT 
9576 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
9577 ** a mask of new.* columns used by the program.
9578 */
9579 struct TriggerPrg {
9580   Trigger *pTrigger;      /* Trigger this program was coded from */
9581   int orconf;             /* Default ON CONFLICT policy */
9582   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
9583   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
9584   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
9585 };
9586
9587 /*
9588 ** An SQL parser context.  A copy of this structure is passed through
9589 ** the parser and down into all the parser action routine in order to
9590 ** carry around information that is global to the entire parse.
9591 **
9592 ** The structure is divided into two parts.  When the parser and code
9593 ** generate call themselves recursively, the first part of the structure
9594 ** is constant but the second part is reset at the beginning and end of
9595 ** each recursion.
9596 **
9597 ** The nTableLock and aTableLock variables are only used if the shared-cache 
9598 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
9599 ** used to store the set of table-locks required by the statement being
9600 ** compiled. Function sqlite3TableLock() is used to add entries to the
9601 ** list.
9602 */
9603 struct Parse {
9604   sqlite3 *db;         /* The main database structure */
9605   int rc;              /* Return code from execution */
9606   char *zErrMsg;       /* An error message */
9607   Vdbe *pVdbe;         /* An engine for executing database bytecode */
9608   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
9609   u8 nameClash;        /* A permanent table name clashes with temp table name */
9610   u8 checkSchema;      /* Causes schema cookie check after an error */
9611   u8 nested;           /* Number of nested calls to the parser/code generator */
9612   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
9613   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
9614   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
9615   int aTempReg[8];     /* Holding area for temporary registers */
9616   int nRangeReg;       /* Size of the temporary register block */
9617   int iRangeReg;       /* First register in temporary register block */
9618   int nErr;            /* Number of errors seen */
9619   int nTab;            /* Number of previously allocated VDBE cursors */
9620   int nMem;            /* Number of memory cells used so far */
9621   int nSet;            /* Number of sets used so far */
9622   int ckBase;          /* Base register of data during check constraints */
9623   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
9624   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
9625   u8 nColCache;        /* Number of entries in the column cache */
9626   u8 iColCache;        /* Next entry of the cache to replace */
9627   struct yColCache {
9628     int iTable;           /* Table cursor number */
9629     int iColumn;          /* Table column number */
9630     u8 tempReg;           /* iReg is a temp register that needs to be freed */
9631     int iLevel;           /* Nesting level */
9632     int iReg;             /* Reg with value of this column. 0 means none. */
9633     int lru;              /* Least recently used entry has the smallest value */
9634   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
9635   u32 writeMask;       /* Start a write transaction on these databases */
9636   u32 cookieMask;      /* Bitmask of schema verified databases */
9637   u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
9638   u8 mayAbort;         /* True if statement may throw an ABORT exception */
9639   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
9640   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
9641 #ifndef SQLITE_OMIT_SHARED_CACHE
9642   int nTableLock;        /* Number of locks in aTableLock */
9643   TableLock *aTableLock; /* Required table locks for shared-cache mode */
9644 #endif
9645   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
9646   int regRoot;         /* Register holding root page number for new objects */
9647   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
9648   int nMaxArg;         /* Max args passed to user function by sub-program */
9649
9650   /* Information used while coding trigger programs. */
9651   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
9652   Table *pTriggerTab;  /* Table triggers are being coded for */
9653   u32 oldmask;         /* Mask of old.* columns referenced */
9654   u32 newmask;         /* Mask of new.* columns referenced */
9655   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
9656   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
9657   u8 disableTriggers;  /* True to disable triggers */
9658
9659   /* Above is constant between recursions.  Below is reset before and after
9660   ** each recursion */
9661
9662   int nVar;            /* Number of '?' variables seen in the SQL so far */
9663   int nVarExpr;        /* Number of used slots in apVarExpr[] */
9664   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
9665   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
9666   Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
9667   int nAlias;          /* Number of aliased result set columns */
9668   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
9669   int *aAlias;         /* Register used to hold aliased result */
9670   u8 explain;          /* True if the EXPLAIN flag is found on the query */
9671   Token sNameToken;    /* Token with unqualified schema object name */
9672   Token sLastToken;    /* The last token parsed */
9673   const char *zTail;   /* All SQL text past the last semicolon parsed */
9674   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
9675   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
9676   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
9677 #ifndef SQLITE_OMIT_VIRTUALTABLE
9678   Token sArg;                /* Complete text of a module argument */
9679   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
9680   int nVtabLock;             /* Number of virtual tables to lock */
9681   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
9682 #endif
9683   int nHeight;            /* Expression tree height of current sub-select */
9684   Table *pZombieTab;      /* List of Table objects to delete after code gen */
9685   TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
9686 };
9687
9688 #ifdef SQLITE_OMIT_VIRTUALTABLE
9689   #define IN_DECLARE_VTAB 0
9690 #else
9691   #define IN_DECLARE_VTAB (pParse->declareVtab)
9692 #endif
9693
9694 /*
9695 ** An instance of the following structure can be declared on a stack and used
9696 ** to save the Parse.zAuthContext value so that it can be restored later.
9697 */
9698 struct AuthContext {
9699   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
9700   Parse *pParse;              /* The Parse structure */
9701 };
9702
9703 /*
9704 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
9705 */
9706 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
9707 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
9708 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
9709 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
9710 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
9711 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
9712
9713 /*
9714  * Each trigger present in the database schema is stored as an instance of
9715  * struct Trigger. 
9716  *
9717  * Pointers to instances of struct Trigger are stored in two ways.
9718  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
9719  *    database). This allows Trigger structures to be retrieved by name.
9720  * 2. All triggers associated with a single table form a linked list, using the
9721  *    pNext member of struct Trigger. A pointer to the first element of the
9722  *    linked list is stored as the "pTrigger" member of the associated
9723  *    struct Table.
9724  *
9725  * The "step_list" member points to the first element of a linked list
9726  * containing the SQL statements specified as the trigger program.
9727  */
9728 struct Trigger {
9729   char *zName;            /* The name of the trigger                        */
9730   char *table;            /* The table or view to which the trigger applies */
9731   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
9732   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
9733   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
9734   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
9735                              the <column-list> is stored here */
9736   Schema *pSchema;        /* Schema containing the trigger */
9737   Schema *pTabSchema;     /* Schema containing the table */
9738   TriggerStep *step_list; /* Link list of trigger program steps             */
9739   Trigger *pNext;         /* Next trigger associated with the table */
9740 };
9741
9742 /*
9743 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
9744 ** determine which. 
9745 **
9746 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
9747 ** In that cases, the constants below can be ORed together.
9748 */
9749 #define TRIGGER_BEFORE  1
9750 #define TRIGGER_AFTER   2
9751
9752 /*
9753  * An instance of struct TriggerStep is used to store a single SQL statement
9754  * that is a part of a trigger-program. 
9755  *
9756  * Instances of struct TriggerStep are stored in a singly linked list (linked
9757  * using the "pNext" member) referenced by the "step_list" member of the 
9758  * associated struct Trigger instance. The first element of the linked list is
9759  * the first step of the trigger-program.
9760  * 
9761  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
9762  * "SELECT" statement. The meanings of the other members is determined by the 
9763  * value of "op" as follows:
9764  *
9765  * (op == TK_INSERT)
9766  * orconf    -> stores the ON CONFLICT algorithm
9767  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
9768  *              this stores a pointer to the SELECT statement. Otherwise NULL.
9769  * target    -> A token holding the quoted name of the table to insert into.
9770  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
9771  *              this stores values to be inserted. Otherwise NULL.
9772  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
9773  *              statement, then this stores the column-names to be
9774  *              inserted into.
9775  *
9776  * (op == TK_DELETE)
9777  * target    -> A token holding the quoted name of the table to delete from.
9778  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
9779  *              Otherwise NULL.
9780  * 
9781  * (op == TK_UPDATE)
9782  * target    -> A token holding the quoted name of the table to update rows of.
9783  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
9784  *              Otherwise NULL.
9785  * pExprList -> A list of the columns to update and the expressions to update
9786  *              them to. See sqlite3Update() documentation of "pChanges"
9787  *              argument.
9788  * 
9789  */
9790 struct TriggerStep {
9791   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
9792   u8 orconf;           /* OE_Rollback etc. */
9793   Trigger *pTrig;      /* The trigger that this step is a part of */
9794   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
9795   Token target;        /* Target table for DELETE, UPDATE, INSERT */
9796   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
9797   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
9798   IdList *pIdList;     /* Column names for INSERT */
9799   TriggerStep *pNext;  /* Next in the link-list */
9800   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
9801 };
9802
9803 /*
9804 ** The following structure contains information used by the sqliteFix...
9805 ** routines as they walk the parse tree to make database references
9806 ** explicit.  
9807 */
9808 typedef struct DbFixer DbFixer;
9809 struct DbFixer {
9810   Parse *pParse;      /* The parsing context.  Error messages written here */
9811   const char *zDb;    /* Make sure all objects are contained in this database */
9812   const char *zType;  /* Type of the container - used for error messages */
9813   const Token *pName; /* Name of the container - used for error messages */
9814 };
9815
9816 /*
9817 ** An objected used to accumulate the text of a string where we
9818 ** do not necessarily know how big the string will be in the end.
9819 */
9820 struct StrAccum {
9821   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
9822   char *zBase;         /* A base allocation.  Not from malloc. */
9823   char *zText;         /* The string collected so far */
9824   int  nChar;          /* Length of the string so far */
9825   int  nAlloc;         /* Amount of space allocated in zText */
9826   int  mxAlloc;        /* Maximum allowed string length */
9827   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
9828   u8   useMalloc;      /* True if zText is enlargeable using realloc */
9829   u8   tooBig;         /* Becomes true if string size exceeds limits */
9830 };
9831
9832 /*
9833 ** A pointer to this structure is used to communicate information
9834 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
9835 */
9836 typedef struct {
9837   sqlite3 *db;        /* The database being initialized */
9838   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
9839   char **pzErrMsg;    /* Error message stored here */
9840   int rc;             /* Result code stored here */
9841 } InitData;
9842
9843 /*
9844 ** Structure containing global configuration data for the SQLite library.
9845 **
9846 ** This structure also contains some state information.
9847 */
9848 struct Sqlite3Config {
9849   int bMemstat;                     /* True to enable memory status */
9850   int bCoreMutex;                   /* True to enable core mutexing */
9851   int bFullMutex;                   /* True to enable full mutexing */
9852   int mxStrlen;                     /* Maximum string length */
9853   int szLookaside;                  /* Default lookaside buffer size */
9854   int nLookaside;                   /* Default lookaside buffer count */
9855   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
9856   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
9857   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
9858   void *pHeap;                      /* Heap storage space */
9859   int nHeap;                        /* Size of pHeap[] */
9860   int mnReq, mxReq;                 /* Min and max heap requests sizes */
9861   void *pScratch;                   /* Scratch memory */
9862   int szScratch;                    /* Size of each scratch buffer */
9863   int nScratch;                     /* Number of scratch buffers */
9864   void *pPage;                      /* Page cache memory */
9865   int szPage;                       /* Size of each page in pPage[] */
9866   int nPage;                        /* Number of pages in pPage[] */
9867   int mxParserStack;                /* maximum depth of the parser stack */
9868   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
9869   /* The above might be initialized to non-zero.  The following need to always
9870   ** initially be zero, however. */
9871   int isInit;                       /* True after initialization has finished */
9872   int inProgress;                   /* True while initialization in progress */
9873   int isMutexInit;                  /* True after mutexes are initialized */
9874   int isMallocInit;                 /* True after malloc is initialized */
9875   int isPCacheInit;                 /* True after malloc is initialized */
9876   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
9877   int nRefInitMutex;                /* Number of users of pInitMutex */
9878 };
9879
9880 /*
9881 ** Context pointer passed down through the tree-walk.
9882 */
9883 struct Walker {
9884   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
9885   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
9886   Parse *pParse;                            /* Parser context.  */
9887   union {                                   /* Extra data for callback */
9888     NameContext *pNC;                          /* Naming context */
9889     int i;                                     /* Integer value */
9890   } u;
9891 };
9892
9893 /* Forward declarations */
9894 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
9895 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
9896 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
9897 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
9898 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
9899
9900 /*
9901 ** Return code from the parse-tree walking primitives and their
9902 ** callbacks.
9903 */
9904 #define WRC_Continue    0   /* Continue down into children */
9905 #define WRC_Prune       1   /* Omit children but continue walking siblings */
9906 #define WRC_Abort       2   /* Abandon the tree walk */
9907
9908 /*
9909 ** Assuming zIn points to the first byte of a UTF-8 character,
9910 ** advance zIn to point to the first byte of the next UTF-8 character.
9911 */
9912 #define SQLITE_SKIP_UTF8(zIn) {                        \
9913   if( (*(zIn++))>=0xc0 ){                              \
9914     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
9915   }                                                    \
9916 }
9917
9918 /*
9919 ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
9920 ** builds) or a function call (for debugging).  If it is a function call,
9921 ** it allows the operator to set a breakpoint at the spot where database
9922 ** corruption is first detected.
9923 */
9924 #ifdef SQLITE_DEBUG
9925 SQLITE_PRIVATE   int sqlite3Corrupt(void);
9926 # define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
9927 #else
9928 # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
9929 #endif
9930
9931 /*
9932 ** The ctype.h header is needed for non-ASCII systems.  It is also
9933 ** needed by FTS3 when FTS3 is included in the amalgamation.
9934 */
9935 #if !defined(SQLITE_ASCII) || \
9936     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
9937 # include <ctype.h>
9938 #endif
9939
9940 /*
9941 ** The following macros mimic the standard library functions toupper(),
9942 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
9943 ** sqlite versions only work for ASCII characters, regardless of locale.
9944 */
9945 #ifdef SQLITE_ASCII
9946 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
9947 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
9948 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
9949 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
9950 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
9951 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
9952 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
9953 #else
9954 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
9955 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
9956 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
9957 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
9958 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
9959 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
9960 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
9961 #endif
9962
9963 /*
9964 ** Internal function prototypes
9965 */
9966 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
9967 SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
9968 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
9969 #define sqlite3StrNICmp sqlite3_strnicmp
9970
9971 SQLITE_PRIVATE int sqlite3MallocInit(void);
9972 SQLITE_PRIVATE void sqlite3MallocEnd(void);
9973 SQLITE_PRIVATE void *sqlite3Malloc(int);
9974 SQLITE_PRIVATE void *sqlite3MallocZero(int);
9975 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
9976 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
9977 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
9978 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
9979 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
9980 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
9981 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
9982 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
9983 SQLITE_PRIVATE int sqlite3MallocSize(void*);
9984 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
9985 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
9986 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
9987 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
9988 SQLITE_PRIVATE void sqlite3PageFree(void*);
9989 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
9990 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
9991 SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
9992
9993 /*
9994 ** On systems with ample stack space and that support alloca(), make
9995 ** use of alloca() to obtain space for large automatic objects.  By default,
9996 ** obtain space from malloc().
9997 **
9998 ** The alloca() routine never returns NULL.  This will cause code paths
9999 ** that deal with sqlite3StackAlloc() failures to be unreachable.
10000 */
10001 #ifdef SQLITE_USE_ALLOCA
10002 # define sqlite3StackAllocRaw(D,N)   alloca(N)
10003 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
10004 # define sqlite3StackFree(D,P)       
10005 #else
10006 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
10007 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
10008 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
10009 #endif
10010
10011 #ifdef SQLITE_ENABLE_MEMSYS3
10012 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10013 #endif
10014 #ifdef SQLITE_ENABLE_MEMSYS5
10015 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10016 #endif
10017
10018
10019 #ifndef SQLITE_MUTEX_OMIT
10020 SQLITE_PRIVATE   sqlite3_mutex_methods *sqlite3DefaultMutex(void);
10021 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10022 SQLITE_PRIVATE   int sqlite3MutexInit(void);
10023 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10024 #endif
10025
10026 SQLITE_PRIVATE int sqlite3StatusValue(int);
10027 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10028 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10029
10030 SQLITE_PRIVATE int sqlite3IsNaN(double);
10031
10032 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10033 #ifndef SQLITE_OMIT_TRACE
10034 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10035 #endif
10036 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10037 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10038 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10039 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10040 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10041 #endif
10042 #if defined(SQLITE_TEST)
10043 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10044 #endif
10045 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10046 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10047 SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
10048 SQLITE_PRIVATE int sqlite3Dequote(char*);
10049 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10050 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10051 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10052 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10053 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10054 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10055 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10056 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
10057 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
10058 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
10059 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10060 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10061 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10062 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10063 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10064 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
10065 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
10066 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
10067 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10068 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10069 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10070 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10071 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10072 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10073 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10074 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10075 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10076 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10077 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10078 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10079 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10080 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10081 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10082 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
10083 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10084 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10085
10086 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10087 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10088 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10089 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
10090 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10091 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
10092 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
10093
10094 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
10095 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
10096 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
10097 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
10098 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
10099
10100 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
10101
10102 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
10103 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
10104 #else
10105 # define sqlite3ViewGetColumnNames(A,B) 0
10106 #endif
10107
10108 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10109 SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
10110 #ifndef SQLITE_OMIT_AUTOINCREMENT
10111 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
10112 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
10113 #else
10114 # define sqlite3AutoincrementBegin(X)
10115 # define sqlite3AutoincrementEnd(X)
10116 #endif
10117 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
10118 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
10119 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
10120 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
10121 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
10122 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
10123 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
10124                                       Token*, Select*, Expr*, IdList*);
10125 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
10126 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
10127 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
10128 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
10129 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
10130 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
10131 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
10132                         Token*, int, int);
10133 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
10134 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
10135 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
10136                          Expr*,ExprList*,int,Expr*,Expr*);
10137 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
10138 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
10139 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
10140 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
10141 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
10142 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
10143 #endif
10144 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
10145 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
10146 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
10147 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10148 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
10149 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10150 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10151 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
10152 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
10153 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
10154 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
10155 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
10156 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10157 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
10158 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10159 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10160 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10161 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10162 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
10163 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
10164 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
10165 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
10166 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
10167 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
10168 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
10169 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
10170 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
10171 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
10172 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10173 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10174 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10175 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10176 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10177 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10178 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
10179 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
10180 SQLITE_PRIVATE void sqlite3PrngResetState(void);
10181 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
10182 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
10183 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
10184 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
10185 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
10186 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
10187 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
10188 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
10189 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
10190 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
10191 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
10192 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
10193 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
10194 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
10195 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
10196 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
10197 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
10198 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
10199 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
10200                                      int*,int,int,int,int,int*);
10201 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
10202 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
10203 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
10204 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
10205 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
10206 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
10207 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
10208 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
10209 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
10210 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
10211 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
10212 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
10213 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
10214 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
10215 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
10216 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
10217 #ifdef SQLITE_DEBUG
10218 SQLITE_PRIVATE   int sqlite3SafetyOn(sqlite3*);
10219 SQLITE_PRIVATE   int sqlite3SafetyOff(sqlite3*);
10220 #else
10221 # define sqlite3SafetyOn(A) 0
10222 # define sqlite3SafetyOff(A) 0
10223 #endif
10224 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
10225 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
10226 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
10227
10228 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
10229 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
10230 #endif
10231
10232 #ifndef SQLITE_OMIT_TRIGGER
10233 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
10234                            Expr*,int, int);
10235 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
10236 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
10237 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
10238 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
10239 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
10240 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
10241                             int, int, int);
10242 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
10243   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
10244 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
10245 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
10246 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
10247                                         ExprList*,Select*,u8);
10248 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
10249 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
10250 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
10251 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
10252 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
10253 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
10254 #else
10255 # define sqlite3TriggersExist(B,C,D,E,F) 0
10256 # define sqlite3DeleteTrigger(A,B)
10257 # define sqlite3DropTriggerPtr(A,B)
10258 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
10259 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
10260 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
10261 # define sqlite3TriggerList(X, Y) 0
10262 # define sqlite3ParseToplevel(p) p
10263 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
10264 #endif
10265
10266 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
10267 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
10268 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
10269 #ifndef SQLITE_OMIT_AUTHORIZATION
10270 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
10271 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
10272 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
10273 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
10274 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
10275 #else
10276 # define sqlite3AuthRead(a,b,c,d)
10277 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
10278 # define sqlite3AuthContextPush(a,b,c)
10279 # define sqlite3AuthContextPop(a)  ((void)(a))
10280 #endif
10281 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10282 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10283 SQLITE_PRIVATE int sqlite3BtreeFactory(sqlite3 *db, const char *zFilename,
10284                        int omitJournal, int nCache, int flags, Btree **ppBtree);
10285 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10286 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10287 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10288 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10289 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
10290 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
10291 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
10292 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
10293 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
10294 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
10295 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
10296 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
10297
10298 /*
10299 ** Routines to read and write variable-length integers.  These used to
10300 ** be defined locally, but now we use the varint routines in the util.c
10301 ** file.  Code should use the MACRO forms below, as the Varint32 versions
10302 ** are coded to assume the single byte case is already handled (which 
10303 ** the MACRO form does).
10304 */
10305 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
10306 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
10307 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
10308 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
10309 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
10310
10311 /*
10312 ** The header of a record consists of a sequence variable-length integers.
10313 ** These integers are almost always small and are encoded as a single byte.
10314 ** The following macros take advantage this fact to provide a fast encode
10315 ** and decode of the integers in a record header.  It is faster for the common
10316 ** case where the integer is a single byte.  It is a little slower when the
10317 ** integer is two or more bytes.  But overall it is faster.
10318 **
10319 ** The following expressions are equivalent:
10320 **
10321 **     x = sqlite3GetVarint32( A, &B );
10322 **     x = sqlite3PutVarint32( A, B );
10323 **
10324 **     x = getVarint32( A, B );
10325 **     x = putVarint32( A, B );
10326 **
10327 */
10328 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
10329 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
10330 #define getVarint    sqlite3GetVarint
10331 #define putVarint    sqlite3PutVarint
10332
10333
10334 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
10335 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
10336 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
10337 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
10338 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
10339 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
10340 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
10341 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
10342 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
10343 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
10344 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
10345 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
10346 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
10347 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10348 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
10349 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10350 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10351 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
10352
10353 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
10354 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
10355 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
10356                         void(*)(void*));
10357 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
10358 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
10359 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
10360 #ifdef SQLITE_ENABLE_STAT2
10361 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
10362 #endif
10363 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
10364 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
10365 #ifndef SQLITE_AMALGAMATION
10366 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
10367 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10368 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
10369 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
10370 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10371 SQLITE_PRIVATE int sqlite3PendingByte;
10372 #endif
10373 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10374 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10375 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
10376 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10377 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10378 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
10379 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
10380 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
10381 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
10382 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
10383 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
10384 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
10385 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
10386 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
10387 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
10388 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
10389 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
10390 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
10391 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
10392 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10393 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
10394 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
10395 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index*);
10396 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
10397 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
10398 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
10399 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
10400 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
10401 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
10402 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
10403 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
10404 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
10405   void (*)(sqlite3_context*,int,sqlite3_value **),
10406   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
10407 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
10408 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
10409
10410 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
10411 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
10412 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
10413 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
10414 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
10415 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
10416
10417 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
10418 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
10419
10420 /*
10421 ** The interface to the LEMON-generated parser
10422 */
10423 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
10424 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
10425 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
10426 #ifdef YYTRACKMAXSTACKDEPTH
10427 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
10428 #endif
10429
10430 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
10431 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10432 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
10433 #else
10434 # define sqlite3CloseExtensions(X)
10435 #endif
10436
10437 #ifndef SQLITE_OMIT_SHARED_CACHE
10438 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
10439 #else
10440   #define sqlite3TableLock(v,w,x,y,z)
10441 #endif
10442
10443 #ifdef SQLITE_TEST
10444 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
10445 #endif
10446
10447 #ifdef SQLITE_OMIT_VIRTUALTABLE
10448 #  define sqlite3VtabClear(Y)
10449 #  define sqlite3VtabSync(X,Y) SQLITE_OK
10450 #  define sqlite3VtabRollback(X)
10451 #  define sqlite3VtabCommit(X)
10452 #  define sqlite3VtabInSync(db) 0
10453 #  define sqlite3VtabLock(X) 
10454 #  define sqlite3VtabUnlock(X)
10455 #  define sqlite3VtabUnlockList(X)
10456 #else
10457 SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
10458 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
10459 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
10460 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
10461 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
10462 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
10463 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
10464 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
10465 #endif
10466 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
10467 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
10468 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
10469 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
10470 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
10471 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
10472 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
10473 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
10474 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
10475 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
10476 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
10477 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
10478 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
10479 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
10480 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
10481 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10482 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
10483 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
10484
10485 /* Declarations for functions in fkey.c. All of these are replaced by
10486 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
10487 ** key functionality is available. If OMIT_TRIGGER is defined but
10488 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
10489 ** this case foreign keys are parsed, but no other functionality is 
10490 ** provided (enforcement of FK constraints requires the triggers sub-system).
10491 */
10492 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
10493 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
10494 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
10495 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
10496 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
10497 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
10498 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
10499 #else
10500   #define sqlite3FkActions(a,b,c,d)
10501   #define sqlite3FkCheck(a,b,c,d)
10502   #define sqlite3FkDropTable(a,b,c)
10503   #define sqlite3FkOldmask(a,b)      0
10504   #define sqlite3FkRequired(a,b,c,d) 0
10505 #endif
10506 #ifndef SQLITE_OMIT_FOREIGN_KEY
10507 SQLITE_PRIVATE   void sqlite3FkDelete(Table*);
10508 #else
10509   #define sqlite3FkDelete(a)
10510 #endif
10511
10512
10513 /*
10514 ** Available fault injectors.  Should be numbered beginning with 0.
10515 */
10516 #define SQLITE_FAULTINJECTOR_MALLOC     0
10517 #define SQLITE_FAULTINJECTOR_COUNT      1
10518
10519 /*
10520 ** The interface to the code in fault.c used for identifying "benign"
10521 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
10522 ** is not defined.
10523 */
10524 #ifndef SQLITE_OMIT_BUILTIN_TEST
10525 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
10526 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
10527 #else
10528   #define sqlite3BeginBenignMalloc()
10529   #define sqlite3EndBenignMalloc()
10530 #endif
10531
10532 #define IN_INDEX_ROWID           1
10533 #define IN_INDEX_EPH             2
10534 #define IN_INDEX_INDEX           3
10535 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
10536
10537 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
10538 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
10539 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
10540 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
10541 #else
10542   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
10543 #endif
10544
10545 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
10546 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
10547 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
10548
10549 #if SQLITE_MAX_EXPR_DEPTH>0
10550 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
10551 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
10552 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
10553 #else
10554   #define sqlite3ExprSetHeight(x,y)
10555   #define sqlite3SelectExprHeight(x) 0
10556   #define sqlite3ExprCheckHeight(x,y)
10557 #endif
10558
10559 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
10560 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
10561
10562 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10563 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
10564 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
10565 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
10566 #else
10567   #define sqlite3ConnectionBlocked(x,y)
10568   #define sqlite3ConnectionUnlocked(x)
10569   #define sqlite3ConnectionClosed(x)
10570 #endif
10571
10572 #ifdef SQLITE_DEBUG
10573 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
10574 #endif
10575
10576 /*
10577 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
10578 ** sqlite3IoTrace is a pointer to a printf-like routine used to
10579 ** print I/O tracing messages. 
10580 */
10581 #ifdef SQLITE_ENABLE_IOTRACE
10582 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
10583 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
10584 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
10585 #else
10586 # define IOTRACE(A)
10587 # define sqlite3VdbeIOTraceSql(X)
10588 #endif
10589
10590 #endif
10591
10592 /************** End of sqliteInt.h *******************************************/
10593 /************** Begin file global.c ******************************************/
10594 /*
10595 ** 2008 June 13
10596 **
10597 ** The author disclaims copyright to this source code.  In place of
10598 ** a legal notice, here is a blessing:
10599 **
10600 **    May you do good and not evil.
10601 **    May you find forgiveness for yourself and forgive others.
10602 **    May you share freely, never taking more than you give.
10603 **
10604 *************************************************************************
10605 **
10606 ** This file contains definitions of global variables and contants.
10607 */
10608
10609 /* An array to map all upper-case characters into their corresponding
10610 ** lower-case character. 
10611 **
10612 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
10613 ** handle case conversions for the UTF character set since the tables
10614 ** involved are nearly as big or bigger than SQLite itself.
10615 */
10616 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
10617 #ifdef SQLITE_ASCII
10618       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
10619      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
10620      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
10621      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
10622     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
10623     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
10624     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
10625     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
10626     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
10627     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
10628     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
10629     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
10630     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
10631     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
10632     252,253,254,255
10633 #endif
10634 #ifdef SQLITE_EBCDIC
10635       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
10636      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
10637      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
10638      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
10639      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
10640      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
10641      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
10642     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
10643     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
10644     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
10645     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
10646     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
10647     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
10648     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
10649     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
10650     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
10651 #endif
10652 };
10653
10654 /*
10655 ** The following 256 byte lookup table is used to support SQLites built-in
10656 ** equivalents to the following standard library functions:
10657 **
10658 **   isspace()                        0x01
10659 **   isalpha()                        0x02
10660 **   isdigit()                        0x04
10661 **   isalnum()                        0x06
10662 **   isxdigit()                       0x08
10663 **   toupper()                        0x20
10664 **   SQLite identifier character      0x40
10665 **
10666 ** Bit 0x20 is set if the mapped character requires translation to upper
10667 ** case. i.e. if the character is a lower-case ASCII character.
10668 ** If x is a lower-case ASCII character, then its upper-case equivalent
10669 ** is (x - 0x20). Therefore toupper() can be implemented as:
10670 **
10671 **   (x & ~(map[x]&0x20))
10672 **
10673 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
10674 ** array. tolower() is used more often than toupper() by SQLite.
10675 **
10676 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
10677 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
10678 ** non-ASCII UTF character. Hence the test for whether or not a character is
10679 ** part of an identifier is 0x46.
10680 **
10681 ** SQLite's versions are identical to the standard versions assuming a
10682 ** locale of "C". They are implemented as macros in sqliteInt.h.
10683 */
10684 #ifdef SQLITE_ASCII
10685 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
10686   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
10687   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
10688   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
10689   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
10690   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
10691   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
10692   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
10693   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
10694
10695   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
10696   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
10697   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
10698   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
10699   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
10700   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
10701   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
10702   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
10703
10704   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
10705   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
10706   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
10707   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
10708   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
10709   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
10710   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
10711   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
10712
10713   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
10714   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
10715   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
10716   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
10717   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
10718   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
10719   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
10720   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
10721 };
10722 #endif
10723
10724
10725
10726 /*
10727 ** The following singleton contains the global configuration for
10728 ** the SQLite library.
10729 */
10730 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
10731    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
10732    1,                         /* bCoreMutex */
10733    SQLITE_THREADSAFE==1,      /* bFullMutex */
10734    0x7ffffffe,                /* mxStrlen */
10735    100,                       /* szLookaside */
10736    500,                       /* nLookaside */
10737    {0,0,0,0,0,0,0,0},         /* m */
10738    {0,0,0,0,0,0,0,0,0},       /* mutex */
10739    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
10740    (void*)0,                  /* pHeap */
10741    0,                         /* nHeap */
10742    0, 0,                      /* mnHeap, mxHeap */
10743    (void*)0,                  /* pScratch */
10744    0,                         /* szScratch */
10745    0,                         /* nScratch */
10746    (void*)0,                  /* pPage */
10747    0,                         /* szPage */
10748    0,                         /* nPage */
10749    0,                         /* mxParserStack */
10750    0,                         /* sharedCacheEnabled */
10751    /* All the rest should always be initialized to zero */
10752    0,                         /* isInit */
10753    0,                         /* inProgress */
10754    0,                         /* isMutexInit */
10755    0,                         /* isMallocInit */
10756    0,                         /* isPCacheInit */
10757    0,                         /* pInitMutex */
10758    0,                         /* nRefInitMutex */
10759 };
10760
10761
10762 /*
10763 ** Hash table for global functions - functions common to all
10764 ** database connections.  After initialization, this table is
10765 ** read-only.
10766 */
10767 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10768
10769 /*
10770 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
10771 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
10772 ** the database page that contains the pending byte.  It never attempts
10773 ** to read or write that page.  The pending byte page is set assign
10774 ** for use by the VFS layers as space for managing file locks.
10775 **
10776 ** During testing, it is often desirable to move the pending byte to
10777 ** a different position in the file.  This allows code that has to
10778 ** deal with the pending byte to run on files that are much smaller
10779 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
10780 ** move the pending byte.
10781 **
10782 ** IMPORTANT:  Changing the pending byte to any value other than
10783 ** 0x40000000 results in an incompatible database file format!
10784 ** Changing the pending byte during operating results in undefined
10785 ** and dileterious behavior.
10786 */
10787 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
10788
10789 /*
10790 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
10791 ** created by mkopcodeh.awk during compilation.  Data is obtained
10792 ** from the comments following the "case OP_xxxx:" statements in
10793 ** the vdbe.c file.  
10794 */
10795 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
10796
10797 /************** End of global.c **********************************************/
10798 /************** Begin file status.c ******************************************/
10799 /*
10800 ** 2008 June 18
10801 **
10802 ** The author disclaims copyright to this source code.  In place of
10803 ** a legal notice, here is a blessing:
10804 **
10805 **    May you do good and not evil.
10806 **    May you find forgiveness for yourself and forgive others.
10807 **    May you share freely, never taking more than you give.
10808 **
10809 *************************************************************************
10810 **
10811 ** This module implements the sqlite3_status() interface and related
10812 ** functionality.
10813 */
10814
10815 /*
10816 ** Variables in which to record status information.
10817 */
10818 typedef struct sqlite3StatType sqlite3StatType;
10819 static SQLITE_WSD struct sqlite3StatType {
10820   int nowValue[9];         /* Current value */
10821   int mxValue[9];          /* Maximum value */
10822 } sqlite3Stat = { {0,}, {0,} };
10823
10824
10825 /* The "wsdStat" macro will resolve to the status information
10826 ** state vector.  If writable static data is unsupported on the target,
10827 ** we have to locate the state vector at run-time.  In the more common
10828 ** case where writable static data is supported, wsdStat can refer directly
10829 ** to the "sqlite3Stat" state vector declared above.
10830 */
10831 #ifdef SQLITE_OMIT_WSD
10832 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
10833 # define wsdStat x[0]
10834 #else
10835 # define wsdStatInit
10836 # define wsdStat sqlite3Stat
10837 #endif
10838
10839 /*
10840 ** Return the current value of a status parameter.
10841 */
10842 SQLITE_PRIVATE int sqlite3StatusValue(int op){
10843   wsdStatInit;
10844   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10845   return wsdStat.nowValue[op];
10846 }
10847
10848 /*
10849 ** Add N to the value of a status record.  It is assumed that the
10850 ** caller holds appropriate locks.
10851 */
10852 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
10853   wsdStatInit;
10854   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10855   wsdStat.nowValue[op] += N;
10856   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
10857     wsdStat.mxValue[op] = wsdStat.nowValue[op];
10858   }
10859 }
10860
10861 /*
10862 ** Set the value of a status to X.
10863 */
10864 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
10865   wsdStatInit;
10866   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10867   wsdStat.nowValue[op] = X;
10868   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
10869     wsdStat.mxValue[op] = wsdStat.nowValue[op];
10870   }
10871 }
10872
10873 /*
10874 ** Query status information.
10875 **
10876 ** This implementation assumes that reading or writing an aligned
10877 ** 32-bit integer is an atomic operation.  If that assumption is not true,
10878 ** then this routine is not threadsafe.
10879 */
10880 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
10881   wsdStatInit;
10882   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
10883     return SQLITE_MISUSE;
10884   }
10885   *pCurrent = wsdStat.nowValue[op];
10886   *pHighwater = wsdStat.mxValue[op];
10887   if( resetFlag ){
10888     wsdStat.mxValue[op] = wsdStat.nowValue[op];
10889   }
10890   return SQLITE_OK;
10891 }
10892
10893 /*
10894 ** Query status information for a single database connection
10895 */
10896 SQLITE_API int sqlite3_db_status(
10897   sqlite3 *db,          /* The database connection whose status is desired */
10898   int op,               /* Status verb */
10899   int *pCurrent,        /* Write current value here */
10900   int *pHighwater,      /* Write high-water mark here */
10901   int resetFlag         /* Reset high-water mark if true */
10902 ){
10903   switch( op ){
10904     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
10905       *pCurrent = db->lookaside.nOut;
10906       *pHighwater = db->lookaside.mxOut;
10907       if( resetFlag ){
10908         db->lookaside.mxOut = db->lookaside.nOut;
10909       }
10910       break;
10911     }
10912     default: {
10913       return SQLITE_ERROR;
10914     }
10915   }
10916   return SQLITE_OK;
10917 }
10918
10919 /************** End of status.c **********************************************/
10920 /************** Begin file date.c ********************************************/
10921 /*
10922 ** 2003 October 31
10923 **
10924 ** The author disclaims copyright to this source code.  In place of
10925 ** a legal notice, here is a blessing:
10926 **
10927 **    May you do good and not evil.
10928 **    May you find forgiveness for yourself and forgive others.
10929 **    May you share freely, never taking more than you give.
10930 **
10931 *************************************************************************
10932 ** This file contains the C functions that implement date and time
10933 ** functions for SQLite.  
10934 **
10935 ** There is only one exported symbol in this file - the function
10936 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
10937 ** All other code has file scope.
10938 **
10939 ** SQLite processes all times and dates as Julian Day numbers.  The
10940 ** dates and times are stored as the number of days since noon
10941 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
10942 ** calendar system. 
10943 **
10944 ** 1970-01-01 00:00:00 is JD 2440587.5
10945 ** 2000-01-01 00:00:00 is JD 2451544.5
10946 **
10947 ** This implemention requires years to be expressed as a 4-digit number
10948 ** which means that only dates between 0000-01-01 and 9999-12-31 can
10949 ** be represented, even though julian day numbers allow a much wider
10950 ** range of dates.
10951 **
10952 ** The Gregorian calendar system is used for all dates and times,
10953 ** even those that predate the Gregorian calendar.  Historians usually
10954 ** use the Julian calendar for dates prior to 1582-10-15 and for some
10955 ** dates afterwards, depending on locale.  Beware of this difference.
10956 **
10957 ** The conversion algorithms are implemented based on descriptions
10958 ** in the following text:
10959 **
10960 **      Jean Meeus
10961 **      Astronomical Algorithms, 2nd Edition, 1998
10962 **      ISBM 0-943396-61-1
10963 **      Willmann-Bell, Inc
10964 **      Richmond, Virginia (USA)
10965 */
10966 #include <time.h>
10967
10968 #ifndef SQLITE_OMIT_DATETIME_FUNCS
10969
10970 /*
10971 ** On recent Windows platforms, the localtime_s() function is available
10972 ** as part of the "Secure CRT". It is essentially equivalent to 
10973 ** localtime_r() available under most POSIX platforms, except that the 
10974 ** order of the parameters is reversed.
10975 **
10976 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
10977 **
10978 ** If the user has not indicated to use localtime_r() or localtime_s()
10979 ** already, check for an MSVC build environment that provides 
10980 ** localtime_s().
10981 */
10982 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
10983      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
10984 #define HAVE_LOCALTIME_S 1
10985 #endif
10986
10987 /*
10988 ** A structure for holding a single date and time.
10989 */
10990 typedef struct DateTime DateTime;
10991 struct DateTime {
10992   sqlite3_int64 iJD; /* The julian day number times 86400000 */
10993   int Y, M, D;       /* Year, month, and day */
10994   int h, m;          /* Hour and minutes */
10995   int tz;            /* Timezone offset in minutes */
10996   double s;          /* Seconds */
10997   char validYMD;     /* True (1) if Y,M,D are valid */
10998   char validHMS;     /* True (1) if h,m,s are valid */
10999   char validJD;      /* True (1) if iJD is valid */
11000   char validTZ;      /* True (1) if tz is valid */
11001 };
11002
11003
11004 /*
11005 ** Convert zDate into one or more integers.  Additional arguments
11006 ** come in groups of 5 as follows:
11007 **
11008 **       N       number of digits in the integer
11009 **       min     minimum allowed value of the integer
11010 **       max     maximum allowed value of the integer
11011 **       nextC   first character after the integer
11012 **       pVal    where to write the integers value.
11013 **
11014 ** Conversions continue until one with nextC==0 is encountered.
11015 ** The function returns the number of successful conversions.
11016 */
11017 static int getDigits(const char *zDate, ...){
11018   va_list ap;
11019   int val;
11020   int N;
11021   int min;
11022   int max;
11023   int nextC;
11024   int *pVal;
11025   int cnt = 0;
11026   va_start(ap, zDate);
11027   do{
11028     N = va_arg(ap, int);
11029     min = va_arg(ap, int);
11030     max = va_arg(ap, int);
11031     nextC = va_arg(ap, int);
11032     pVal = va_arg(ap, int*);
11033     val = 0;
11034     while( N-- ){
11035       if( !sqlite3Isdigit(*zDate) ){
11036         goto end_getDigits;
11037       }
11038       val = val*10 + *zDate - '0';
11039       zDate++;
11040     }
11041     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
11042       goto end_getDigits;
11043     }
11044     *pVal = val;
11045     zDate++;
11046     cnt++;
11047   }while( nextC );
11048 end_getDigits:
11049   va_end(ap);
11050   return cnt;
11051 }
11052
11053 /*
11054 ** Read text from z[] and convert into a floating point number.  Return
11055 ** the number of digits converted.
11056 */
11057 #define getValue sqlite3AtoF
11058
11059 /*
11060 ** Parse a timezone extension on the end of a date-time.
11061 ** The extension is of the form:
11062 **
11063 **        (+/-)HH:MM
11064 **
11065 ** Or the "zulu" notation:
11066 **
11067 **        Z
11068 **
11069 ** If the parse is successful, write the number of minutes
11070 ** of change in p->tz and return 0.  If a parser error occurs,
11071 ** return non-zero.
11072 **
11073 ** A missing specifier is not considered an error.
11074 */
11075 static int parseTimezone(const char *zDate, DateTime *p){
11076   int sgn = 0;
11077   int nHr, nMn;
11078   int c;
11079   while( sqlite3Isspace(*zDate) ){ zDate++; }
11080   p->tz = 0;
11081   c = *zDate;
11082   if( c=='-' ){
11083     sgn = -1;
11084   }else if( c=='+' ){
11085     sgn = +1;
11086   }else if( c=='Z' || c=='z' ){
11087     zDate++;
11088     goto zulu_time;
11089   }else{
11090     return c!=0;
11091   }
11092   zDate++;
11093   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
11094     return 1;
11095   }
11096   zDate += 5;
11097   p->tz = sgn*(nMn + nHr*60);
11098 zulu_time:
11099   while( sqlite3Isspace(*zDate) ){ zDate++; }
11100   return *zDate!=0;
11101 }
11102
11103 /*
11104 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
11105 ** The HH, MM, and SS must each be exactly 2 digits.  The
11106 ** fractional seconds FFFF can be one or more digits.
11107 **
11108 ** Return 1 if there is a parsing error and 0 on success.
11109 */
11110 static int parseHhMmSs(const char *zDate, DateTime *p){
11111   int h, m, s;
11112   double ms = 0.0;
11113   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
11114     return 1;
11115   }
11116   zDate += 5;
11117   if( *zDate==':' ){
11118     zDate++;
11119     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
11120       return 1;
11121     }
11122     zDate += 2;
11123     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
11124       double rScale = 1.0;
11125       zDate++;
11126       while( sqlite3Isdigit(*zDate) ){
11127         ms = ms*10.0 + *zDate - '0';
11128         rScale *= 10.0;
11129         zDate++;
11130       }
11131       ms /= rScale;
11132     }
11133   }else{
11134     s = 0;
11135   }
11136   p->validJD = 0;
11137   p->validHMS = 1;
11138   p->h = h;
11139   p->m = m;
11140   p->s = s + ms;
11141   if( parseTimezone(zDate, p) ) return 1;
11142   p->validTZ = (p->tz!=0)?1:0;
11143   return 0;
11144 }
11145
11146 /*
11147 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
11148 ** that the YYYY-MM-DD is according to the Gregorian calendar.
11149 **
11150 ** Reference:  Meeus page 61
11151 */
11152 static void computeJD(DateTime *p){
11153   int Y, M, D, A, B, X1, X2;
11154
11155   if( p->validJD ) return;
11156   if( p->validYMD ){
11157     Y = p->Y;
11158     M = p->M;
11159     D = p->D;
11160   }else{
11161     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
11162     M = 1;
11163     D = 1;
11164   }
11165   if( M<=2 ){
11166     Y--;
11167     M += 12;
11168   }
11169   A = Y/100;
11170   B = 2 - A + (A/4);
11171   X1 = 36525*(Y+4716)/100;
11172   X2 = 306001*(M+1)/10000;
11173   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
11174   p->validJD = 1;
11175   if( p->validHMS ){
11176     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
11177     if( p->validTZ ){
11178       p->iJD -= p->tz*60000;
11179       p->validYMD = 0;
11180       p->validHMS = 0;
11181       p->validTZ = 0;
11182     }
11183   }
11184 }
11185
11186 /*
11187 ** Parse dates of the form
11188 **
11189 **     YYYY-MM-DD HH:MM:SS.FFF
11190 **     YYYY-MM-DD HH:MM:SS
11191 **     YYYY-MM-DD HH:MM
11192 **     YYYY-MM-DD
11193 **
11194 ** Write the result into the DateTime structure and return 0
11195 ** on success and 1 if the input string is not a well-formed
11196 ** date.
11197 */
11198 static int parseYyyyMmDd(const char *zDate, DateTime *p){
11199   int Y, M, D, neg;
11200
11201   if( zDate[0]=='-' ){
11202     zDate++;
11203     neg = 1;
11204   }else{
11205     neg = 0;
11206   }
11207   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
11208     return 1;
11209   }
11210   zDate += 10;
11211   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
11212   if( parseHhMmSs(zDate, p)==0 ){
11213     /* We got the time */
11214   }else if( *zDate==0 ){
11215     p->validHMS = 0;
11216   }else{
11217     return 1;
11218   }
11219   p->validJD = 0;
11220   p->validYMD = 1;
11221   p->Y = neg ? -Y : Y;
11222   p->M = M;
11223   p->D = D;
11224   if( p->validTZ ){
11225     computeJD(p);
11226   }
11227   return 0;
11228 }
11229
11230 /*
11231 ** Set the time to the current time reported by the VFS
11232 */
11233 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
11234   double r;
11235   sqlite3 *db = sqlite3_context_db_handle(context);
11236   sqlite3OsCurrentTime(db->pVfs, &r);
11237   p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11238   p->validJD = 1;
11239 }
11240
11241 /*
11242 ** Attempt to parse the given string into a Julian Day Number.  Return
11243 ** the number of errors.
11244 **
11245 ** The following are acceptable forms for the input string:
11246 **
11247 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
11248 **      DDDD.DD 
11249 **      now
11250 **
11251 ** In the first form, the +/-HH:MM is always optional.  The fractional
11252 ** seconds extension (the ".FFF") is optional.  The seconds portion
11253 ** (":SS.FFF") is option.  The year and date can be omitted as long
11254 ** as there is a time string.  The time string can be omitted as long
11255 ** as there is a year and date.
11256 */
11257 static int parseDateOrTime(
11258   sqlite3_context *context, 
11259   const char *zDate, 
11260   DateTime *p
11261 ){
11262   int isRealNum;    /* Return from sqlite3IsNumber().  Not used */
11263   if( parseYyyyMmDd(zDate,p)==0 ){
11264     return 0;
11265   }else if( parseHhMmSs(zDate, p)==0 ){
11266     return 0;
11267   }else if( sqlite3StrICmp(zDate,"now")==0){
11268     setDateTimeToCurrent(context, p);
11269     return 0;
11270   }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
11271     double r;
11272     getValue(zDate, &r);
11273     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11274     p->validJD = 1;
11275     return 0;
11276   }
11277   return 1;
11278 }
11279
11280 /*
11281 ** Compute the Year, Month, and Day from the julian day number.
11282 */
11283 static void computeYMD(DateTime *p){
11284   int Z, A, B, C, D, E, X1;
11285   if( p->validYMD ) return;
11286   if( !p->validJD ){
11287     p->Y = 2000;
11288     p->M = 1;
11289     p->D = 1;
11290   }else{
11291     Z = (int)((p->iJD + 43200000)/86400000);
11292     A = (int)((Z - 1867216.25)/36524.25);
11293     A = Z + 1 + A - (A/4);
11294     B = A + 1524;
11295     C = (int)((B - 122.1)/365.25);
11296     D = (36525*C)/100;
11297     E = (int)((B-D)/30.6001);
11298     X1 = (int)(30.6001*E);
11299     p->D = B - D - X1;
11300     p->M = E<14 ? E-1 : E-13;
11301     p->Y = p->M>2 ? C - 4716 : C - 4715;
11302   }
11303   p->validYMD = 1;
11304 }
11305
11306 /*
11307 ** Compute the Hour, Minute, and Seconds from the julian day number.
11308 */
11309 static void computeHMS(DateTime *p){
11310   int s;
11311   if( p->validHMS ) return;
11312   computeJD(p);
11313   s = (int)((p->iJD + 43200000) % 86400000);
11314   p->s = s/1000.0;
11315   s = (int)p->s;
11316   p->s -= s;
11317   p->h = s/3600;
11318   s -= p->h*3600;
11319   p->m = s/60;
11320   p->s += s - p->m*60;
11321   p->validHMS = 1;
11322 }
11323
11324 /*
11325 ** Compute both YMD and HMS
11326 */
11327 static void computeYMD_HMS(DateTime *p){
11328   computeYMD(p);
11329   computeHMS(p);
11330 }
11331
11332 /*
11333 ** Clear the YMD and HMS and the TZ
11334 */
11335 static void clearYMD_HMS_TZ(DateTime *p){
11336   p->validYMD = 0;
11337   p->validHMS = 0;
11338   p->validTZ = 0;
11339 }
11340
11341 #ifndef SQLITE_OMIT_LOCALTIME
11342 /*
11343 ** Compute the difference (in milliseconds)
11344 ** between localtime and UTC (a.k.a. GMT)
11345 ** for the time value p where p is in UTC.
11346 */
11347 static sqlite3_int64 localtimeOffset(DateTime *p){
11348   DateTime x, y;
11349   time_t t;
11350   x = *p;
11351   computeYMD_HMS(&x);
11352   if( x.Y<1971 || x.Y>=2038 ){
11353     x.Y = 2000;
11354     x.M = 1;
11355     x.D = 1;
11356     x.h = 0;
11357     x.m = 0;
11358     x.s = 0.0;
11359   } else {
11360     int s = (int)(x.s + 0.5);
11361     x.s = s;
11362   }
11363   x.tz = 0;
11364   x.validJD = 0;
11365   computeJD(&x);
11366   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
11367 #ifdef HAVE_LOCALTIME_R
11368   {
11369     struct tm sLocal;
11370     localtime_r(&t, &sLocal);
11371     y.Y = sLocal.tm_year + 1900;
11372     y.M = sLocal.tm_mon + 1;
11373     y.D = sLocal.tm_mday;
11374     y.h = sLocal.tm_hour;
11375     y.m = sLocal.tm_min;
11376     y.s = sLocal.tm_sec;
11377   }
11378 #elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
11379   {
11380     struct tm sLocal;
11381     localtime_s(&sLocal, &t);
11382     y.Y = sLocal.tm_year + 1900;
11383     y.M = sLocal.tm_mon + 1;
11384     y.D = sLocal.tm_mday;
11385     y.h = sLocal.tm_hour;
11386     y.m = sLocal.tm_min;
11387     y.s = sLocal.tm_sec;
11388   }
11389 #else
11390   {
11391     struct tm *pTm;
11392     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11393     pTm = localtime(&t);
11394     y.Y = pTm->tm_year + 1900;
11395     y.M = pTm->tm_mon + 1;
11396     y.D = pTm->tm_mday;
11397     y.h = pTm->tm_hour;
11398     y.m = pTm->tm_min;
11399     y.s = pTm->tm_sec;
11400     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11401   }
11402 #endif
11403   y.validYMD = 1;
11404   y.validHMS = 1;
11405   y.validJD = 0;
11406   y.validTZ = 0;
11407   computeJD(&y);
11408   return y.iJD - x.iJD;
11409 }
11410 #endif /* SQLITE_OMIT_LOCALTIME */
11411
11412 /*
11413 ** Process a modifier to a date-time stamp.  The modifiers are
11414 ** as follows:
11415 **
11416 **     NNN days
11417 **     NNN hours
11418 **     NNN minutes
11419 **     NNN.NNNN seconds
11420 **     NNN months
11421 **     NNN years
11422 **     start of month
11423 **     start of year
11424 **     start of week
11425 **     start of day
11426 **     weekday N
11427 **     unixepoch
11428 **     localtime
11429 **     utc
11430 **
11431 ** Return 0 on success and 1 if there is any kind of error.
11432 */
11433 static int parseModifier(const char *zMod, DateTime *p){
11434   int rc = 1;
11435   int n;
11436   double r;
11437   char *z, zBuf[30];
11438   z = zBuf;
11439   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
11440     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
11441   }
11442   z[n] = 0;
11443   switch( z[0] ){
11444 #ifndef SQLITE_OMIT_LOCALTIME
11445     case 'l': {
11446       /*    localtime
11447       **
11448       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
11449       ** show local time.
11450       */
11451       if( strcmp(z, "localtime")==0 ){
11452         computeJD(p);
11453         p->iJD += localtimeOffset(p);
11454         clearYMD_HMS_TZ(p);
11455         rc = 0;
11456       }
11457       break;
11458     }
11459 #endif
11460     case 'u': {
11461       /*
11462       **    unixepoch
11463       **
11464       ** Treat the current value of p->iJD as the number of
11465       ** seconds since 1970.  Convert to a real julian day number.
11466       */
11467       if( strcmp(z, "unixepoch")==0 && p->validJD ){
11468         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
11469         clearYMD_HMS_TZ(p);
11470         rc = 0;
11471       }
11472 #ifndef SQLITE_OMIT_LOCALTIME
11473       else if( strcmp(z, "utc")==0 ){
11474         sqlite3_int64 c1;
11475         computeJD(p);
11476         c1 = localtimeOffset(p);
11477         p->iJD -= c1;
11478         clearYMD_HMS_TZ(p);
11479         p->iJD += c1 - localtimeOffset(p);
11480         rc = 0;
11481       }
11482 #endif
11483       break;
11484     }
11485     case 'w': {
11486       /*
11487       **    weekday N
11488       **
11489       ** Move the date to the same time on the next occurrence of
11490       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
11491       ** date is already on the appropriate weekday, this is a no-op.
11492       */
11493       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
11494                  && (n=(int)r)==r && n>=0 && r<7 ){
11495         sqlite3_int64 Z;
11496         computeYMD_HMS(p);
11497         p->validTZ = 0;
11498         p->validJD = 0;
11499         computeJD(p);
11500         Z = ((p->iJD + 129600000)/86400000) % 7;
11501         if( Z>n ) Z -= 7;
11502         p->iJD += (n - Z)*86400000;
11503         clearYMD_HMS_TZ(p);
11504         rc = 0;
11505       }
11506       break;
11507     }
11508     case 's': {
11509       /*
11510       **    start of TTTTT
11511       **
11512       ** Move the date backwards to the beginning of the current day,
11513       ** or month or year.
11514       */
11515       if( strncmp(z, "start of ", 9)!=0 ) break;
11516       z += 9;
11517       computeYMD(p);
11518       p->validHMS = 1;
11519       p->h = p->m = 0;
11520       p->s = 0.0;
11521       p->validTZ = 0;
11522       p->validJD = 0;
11523       if( strcmp(z,"month")==0 ){
11524         p->D = 1;
11525         rc = 0;
11526       }else if( strcmp(z,"year")==0 ){
11527         computeYMD(p);
11528         p->M = 1;
11529         p->D = 1;
11530         rc = 0;
11531       }else if( strcmp(z,"day")==0 ){
11532         rc = 0;
11533       }
11534       break;
11535     }
11536     case '+':
11537     case '-':
11538     case '0':
11539     case '1':
11540     case '2':
11541     case '3':
11542     case '4':
11543     case '5':
11544     case '6':
11545     case '7':
11546     case '8':
11547     case '9': {
11548       double rRounder;
11549       n = getValue(z, &r);
11550       assert( n>=1 );
11551       if( z[n]==':' ){
11552         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
11553         ** specified number of hours, minutes, seconds, and fractional seconds
11554         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
11555         ** omitted.
11556         */
11557         const char *z2 = z;
11558         DateTime tx;
11559         sqlite3_int64 day;
11560         if( !sqlite3Isdigit(*z2) ) z2++;
11561         memset(&tx, 0, sizeof(tx));
11562         if( parseHhMmSs(z2, &tx) ) break;
11563         computeJD(&tx);
11564         tx.iJD -= 43200000;
11565         day = tx.iJD/86400000;
11566         tx.iJD -= day*86400000;
11567         if( z[0]=='-' ) tx.iJD = -tx.iJD;
11568         computeJD(p);
11569         clearYMD_HMS_TZ(p);
11570         p->iJD += tx.iJD;
11571         rc = 0;
11572         break;
11573       }
11574       z += n;
11575       while( sqlite3Isspace(*z) ) z++;
11576       n = sqlite3Strlen30(z);
11577       if( n>10 || n<3 ) break;
11578       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
11579       computeJD(p);
11580       rc = 0;
11581       rRounder = r<0 ? -0.5 : +0.5;
11582       if( n==3 && strcmp(z,"day")==0 ){
11583         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
11584       }else if( n==4 && strcmp(z,"hour")==0 ){
11585         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
11586       }else if( n==6 && strcmp(z,"minute")==0 ){
11587         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
11588       }else if( n==6 && strcmp(z,"second")==0 ){
11589         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
11590       }else if( n==5 && strcmp(z,"month")==0 ){
11591         int x, y;
11592         computeYMD_HMS(p);
11593         p->M += (int)r;
11594         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
11595         p->Y += x;
11596         p->M -= x*12;
11597         p->validJD = 0;
11598         computeJD(p);
11599         y = (int)r;
11600         if( y!=r ){
11601           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
11602         }
11603       }else if( n==4 && strcmp(z,"year")==0 ){
11604         int y = (int)r;
11605         computeYMD_HMS(p);
11606         p->Y += y;
11607         p->validJD = 0;
11608         computeJD(p);
11609         if( y!=r ){
11610           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
11611         }
11612       }else{
11613         rc = 1;
11614       }
11615       clearYMD_HMS_TZ(p);
11616       break;
11617     }
11618     default: {
11619       break;
11620     }
11621   }
11622   return rc;
11623 }
11624
11625 /*
11626 ** Process time function arguments.  argv[0] is a date-time stamp.
11627 ** argv[1] and following are modifiers.  Parse them all and write
11628 ** the resulting time into the DateTime structure p.  Return 0
11629 ** on success and 1 if there are any errors.
11630 **
11631 ** If there are zero parameters (if even argv[0] is undefined)
11632 ** then assume a default value of "now" for argv[0].
11633 */
11634 static int isDate(
11635   sqlite3_context *context, 
11636   int argc, 
11637   sqlite3_value **argv, 
11638   DateTime *p
11639 ){
11640   int i;
11641   const unsigned char *z;
11642   int eType;
11643   memset(p, 0, sizeof(*p));
11644   if( argc==0 ){
11645     setDateTimeToCurrent(context, p);
11646   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
11647                    || eType==SQLITE_INTEGER ){
11648     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
11649     p->validJD = 1;
11650   }else{
11651     z = sqlite3_value_text(argv[0]);
11652     if( !z || parseDateOrTime(context, (char*)z, p) ){
11653       return 1;
11654     }
11655   }
11656   for(i=1; i<argc; i++){
11657     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
11658       return 1;
11659     }
11660   }
11661   return 0;
11662 }
11663
11664
11665 /*
11666 ** The following routines implement the various date and time functions
11667 ** of SQLite.
11668 */
11669
11670 /*
11671 **    julianday( TIMESTRING, MOD, MOD, ...)
11672 **
11673 ** Return the julian day number of the date specified in the arguments
11674 */
11675 static void juliandayFunc(
11676   sqlite3_context *context,
11677   int argc,
11678   sqlite3_value **argv
11679 ){
11680   DateTime x;
11681   if( isDate(context, argc, argv, &x)==0 ){
11682     computeJD(&x);
11683     sqlite3_result_double(context, x.iJD/86400000.0);
11684   }
11685 }
11686
11687 /*
11688 **    datetime( TIMESTRING, MOD, MOD, ...)
11689 **
11690 ** Return YYYY-MM-DD HH:MM:SS
11691 */
11692 static void datetimeFunc(
11693   sqlite3_context *context,
11694   int argc,
11695   sqlite3_value **argv
11696 ){
11697   DateTime x;
11698   if( isDate(context, argc, argv, &x)==0 ){
11699     char zBuf[100];
11700     computeYMD_HMS(&x);
11701     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
11702                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
11703     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11704   }
11705 }
11706
11707 /*
11708 **    time( TIMESTRING, MOD, MOD, ...)
11709 **
11710 ** Return HH:MM:SS
11711 */
11712 static void timeFunc(
11713   sqlite3_context *context,
11714   int argc,
11715   sqlite3_value **argv
11716 ){
11717   DateTime x;
11718   if( isDate(context, argc, argv, &x)==0 ){
11719     char zBuf[100];
11720     computeHMS(&x);
11721     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
11722     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11723   }
11724 }
11725
11726 /*
11727 **    date( TIMESTRING, MOD, MOD, ...)
11728 **
11729 ** Return YYYY-MM-DD
11730 */
11731 static void dateFunc(
11732   sqlite3_context *context,
11733   int argc,
11734   sqlite3_value **argv
11735 ){
11736   DateTime x;
11737   if( isDate(context, argc, argv, &x)==0 ){
11738     char zBuf[100];
11739     computeYMD(&x);
11740     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
11741     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11742   }
11743 }
11744
11745 /*
11746 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
11747 **
11748 ** Return a string described by FORMAT.  Conversions as follows:
11749 **
11750 **   %d  day of month
11751 **   %f  ** fractional seconds  SS.SSS
11752 **   %H  hour 00-24
11753 **   %j  day of year 000-366
11754 **   %J  ** Julian day number
11755 **   %m  month 01-12
11756 **   %M  minute 00-59
11757 **   %s  seconds since 1970-01-01
11758 **   %S  seconds 00-59
11759 **   %w  day of week 0-6  sunday==0
11760 **   %W  week of year 00-53
11761 **   %Y  year 0000-9999
11762 **   %%  %
11763 */
11764 static void strftimeFunc(
11765   sqlite3_context *context,
11766   int argc,
11767   sqlite3_value **argv
11768 ){
11769   DateTime x;
11770   u64 n;
11771   size_t i,j;
11772   char *z;
11773   sqlite3 *db;
11774   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
11775   char zBuf[100];
11776   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
11777   db = sqlite3_context_db_handle(context);
11778   for(i=0, n=1; zFmt[i]; i++, n++){
11779     if( zFmt[i]=='%' ){
11780       switch( zFmt[i+1] ){
11781         case 'd':
11782         case 'H':
11783         case 'm':
11784         case 'M':
11785         case 'S':
11786         case 'W':
11787           n++;
11788           /* fall thru */
11789         case 'w':
11790         case '%':
11791           break;
11792         case 'f':
11793           n += 8;
11794           break;
11795         case 'j':
11796           n += 3;
11797           break;
11798         case 'Y':
11799           n += 8;
11800           break;
11801         case 's':
11802         case 'J':
11803           n += 50;
11804           break;
11805         default:
11806           return;  /* ERROR.  return a NULL */
11807       }
11808       i++;
11809     }
11810   }
11811   testcase( n==sizeof(zBuf)-1 );
11812   testcase( n==sizeof(zBuf) );
11813   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
11814   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
11815   if( n<sizeof(zBuf) ){
11816     z = zBuf;
11817   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
11818     sqlite3_result_error_toobig(context);
11819     return;
11820   }else{
11821     z = sqlite3DbMallocRaw(db, (int)n);
11822     if( z==0 ){
11823       sqlite3_result_error_nomem(context);
11824       return;
11825     }
11826   }
11827   computeJD(&x);
11828   computeYMD_HMS(&x);
11829   for(i=j=0; zFmt[i]; i++){
11830     if( zFmt[i]!='%' ){
11831       z[j++] = zFmt[i];
11832     }else{
11833       i++;
11834       switch( zFmt[i] ){
11835         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
11836         case 'f': {
11837           double s = x.s;
11838           if( s>59.999 ) s = 59.999;
11839           sqlite3_snprintf(7, &z[j],"%06.3f", s);
11840           j += sqlite3Strlen30(&z[j]);
11841           break;
11842         }
11843         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
11844         case 'W': /* Fall thru */
11845         case 'j': {
11846           int nDay;             /* Number of days since 1st day of year */
11847           DateTime y = x;
11848           y.validJD = 0;
11849           y.M = 1;
11850           y.D = 1;
11851           computeJD(&y);
11852           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
11853           if( zFmt[i]=='W' ){
11854             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
11855             wd = (int)(((x.iJD+43200000)/86400000)%7);
11856             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
11857             j += 2;
11858           }else{
11859             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
11860             j += 3;
11861           }
11862           break;
11863         }
11864         case 'J': {
11865           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
11866           j+=sqlite3Strlen30(&z[j]);
11867           break;
11868         }
11869         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
11870         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
11871         case 's': {
11872           sqlite3_snprintf(30,&z[j],"%lld",
11873                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
11874           j += sqlite3Strlen30(&z[j]);
11875           break;
11876         }
11877         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
11878         case 'w': {
11879           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
11880           break;
11881         }
11882         case 'Y': {
11883           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
11884           break;
11885         }
11886         default:   z[j++] = '%'; break;
11887       }
11888     }
11889   }
11890   z[j] = 0;
11891   sqlite3_result_text(context, z, -1,
11892                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
11893 }
11894
11895 /*
11896 ** current_time()
11897 **
11898 ** This function returns the same value as time('now').
11899 */
11900 static void ctimeFunc(
11901   sqlite3_context *context,
11902   int NotUsed,
11903   sqlite3_value **NotUsed2
11904 ){
11905   UNUSED_PARAMETER2(NotUsed, NotUsed2);
11906   timeFunc(context, 0, 0);
11907 }
11908
11909 /*
11910 ** current_date()
11911 **
11912 ** This function returns the same value as date('now').
11913 */
11914 static void cdateFunc(
11915   sqlite3_context *context,
11916   int NotUsed,
11917   sqlite3_value **NotUsed2
11918 ){
11919   UNUSED_PARAMETER2(NotUsed, NotUsed2);
11920   dateFunc(context, 0, 0);
11921 }
11922
11923 /*
11924 ** current_timestamp()
11925 **
11926 ** This function returns the same value as datetime('now').
11927 */
11928 static void ctimestampFunc(
11929   sqlite3_context *context,
11930   int NotUsed,
11931   sqlite3_value **NotUsed2
11932 ){
11933   UNUSED_PARAMETER2(NotUsed, NotUsed2);
11934   datetimeFunc(context, 0, 0);
11935 }
11936 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
11937
11938 #ifdef SQLITE_OMIT_DATETIME_FUNCS
11939 /*
11940 ** If the library is compiled to omit the full-scale date and time
11941 ** handling (to get a smaller binary), the following minimal version
11942 ** of the functions current_time(), current_date() and current_timestamp()
11943 ** are included instead. This is to support column declarations that
11944 ** include "DEFAULT CURRENT_TIME" etc.
11945 **
11946 ** This function uses the C-library functions time(), gmtime()
11947 ** and strftime(). The format string to pass to strftime() is supplied
11948 ** as the user-data for the function.
11949 */
11950 static void currentTimeFunc(
11951   sqlite3_context *context,
11952   int argc,
11953   sqlite3_value **argv
11954 ){
11955   time_t t;
11956   char *zFormat = (char *)sqlite3_user_data(context);
11957   sqlite3 *db;
11958   double rT;
11959   char zBuf[20];
11960
11961   UNUSED_PARAMETER(argc);
11962   UNUSED_PARAMETER(argv);
11963
11964   db = sqlite3_context_db_handle(context);
11965   sqlite3OsCurrentTime(db->pVfs, &rT);
11966 #ifndef SQLITE_OMIT_FLOATING_POINT
11967   t = 86400.0*(rT - 2440587.5) + 0.5;
11968 #else
11969   /* without floating point support, rT will have
11970   ** already lost fractional day precision.
11971   */
11972   t = 86400 * (rT - 2440587) - 43200;
11973 #endif
11974 #ifdef HAVE_GMTIME_R
11975   {
11976     struct tm sNow;
11977     gmtime_r(&t, &sNow);
11978     strftime(zBuf, 20, zFormat, &sNow);
11979   }
11980 #else
11981   {
11982     struct tm *pTm;
11983     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11984     pTm = gmtime(&t);
11985     strftime(zBuf, 20, zFormat, pTm);
11986     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11987   }
11988 #endif
11989
11990   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11991 }
11992 #endif
11993
11994 /*
11995 ** This function registered all of the above C functions as SQL
11996 ** functions.  This should be the only routine in this file with
11997 ** external linkage.
11998 */
11999 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
12000   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
12001 #ifndef SQLITE_OMIT_DATETIME_FUNCS
12002     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
12003     FUNCTION(date,             -1, 0, 0, dateFunc      ),
12004     FUNCTION(time,             -1, 0, 0, timeFunc      ),
12005     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
12006     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
12007     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
12008     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
12009     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
12010 #else
12011     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
12012     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d",          0, currentTimeFunc),
12013     STR_FUNCTION(current_date,      0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
12014 #endif
12015   };
12016   int i;
12017   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
12018   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
12019
12020   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
12021     sqlite3FuncDefInsert(pHash, &aFunc[i]);
12022   }
12023 }
12024
12025 /************** End of date.c ************************************************/
12026 /************** Begin file os.c **********************************************/
12027 /*
12028 ** 2005 November 29
12029 **
12030 ** The author disclaims copyright to this source code.  In place of
12031 ** a legal notice, here is a blessing:
12032 **
12033 **    May you do good and not evil.
12034 **    May you find forgiveness for yourself and forgive others.
12035 **    May you share freely, never taking more than you give.
12036 **
12037 ******************************************************************************
12038 **
12039 ** This file contains OS interface code that is common to all
12040 ** architectures.
12041 */
12042 #define _SQLITE_OS_C_ 1
12043 #undef _SQLITE_OS_C_
12044
12045 /*
12046 ** The default SQLite sqlite3_vfs implementations do not allocate
12047 ** memory (actually, os_unix.c allocates a small amount of memory
12048 ** from within OsOpen()), but some third-party implementations may.
12049 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
12050 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
12051 **
12052 ** The following functions are instrumented for malloc() failure 
12053 ** testing:
12054 **
12055 **     sqlite3OsOpen()
12056 **     sqlite3OsRead()
12057 **     sqlite3OsWrite()
12058 **     sqlite3OsSync()
12059 **     sqlite3OsLock()
12060 **
12061 */
12062 #if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0)
12063   #define DO_OS_MALLOC_TEST(x) if (!x || !sqlite3IsMemJournal(x)) {     \
12064     void *pTstAlloc = sqlite3Malloc(10);                             \
12065     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
12066     sqlite3_free(pTstAlloc);                                         \
12067   }
12068 #else
12069   #define DO_OS_MALLOC_TEST(x)
12070 #endif
12071
12072 /*
12073 ** The following routines are convenience wrappers around methods
12074 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
12075 ** of this would be completely automatic if SQLite were coded using
12076 ** C++ instead of plain old C.
12077 */
12078 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
12079   int rc = SQLITE_OK;
12080   if( pId->pMethods ){
12081     rc = pId->pMethods->xClose(pId);
12082     pId->pMethods = 0;
12083   }
12084   return rc;
12085 }
12086 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
12087   DO_OS_MALLOC_TEST(id);
12088   return id->pMethods->xRead(id, pBuf, amt, offset);
12089 }
12090 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
12091   DO_OS_MALLOC_TEST(id);
12092   return id->pMethods->xWrite(id, pBuf, amt, offset);
12093 }
12094 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
12095   return id->pMethods->xTruncate(id, size);
12096 }
12097 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
12098   DO_OS_MALLOC_TEST(id);
12099   return id->pMethods->xSync(id, flags);
12100 }
12101 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
12102   DO_OS_MALLOC_TEST(id);
12103   return id->pMethods->xFileSize(id, pSize);
12104 }
12105 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
12106   DO_OS_MALLOC_TEST(id);
12107   return id->pMethods->xLock(id, lockType);
12108 }
12109 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
12110   return id->pMethods->xUnlock(id, lockType);
12111 }
12112 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
12113   DO_OS_MALLOC_TEST(id);
12114   return id->pMethods->xCheckReservedLock(id, pResOut);
12115 }
12116 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
12117   return id->pMethods->xFileControl(id, op, pArg);
12118 }
12119 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
12120   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
12121   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
12122 }
12123 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
12124   return id->pMethods->xDeviceCharacteristics(id);
12125 }
12126
12127 /*
12128 ** The next group of routines are convenience wrappers around the
12129 ** VFS methods.
12130 */
12131 SQLITE_PRIVATE int sqlite3OsOpen(
12132   sqlite3_vfs *pVfs, 
12133   const char *zPath, 
12134   sqlite3_file *pFile, 
12135   int flags, 
12136   int *pFlagsOut
12137 ){
12138   int rc;
12139   DO_OS_MALLOC_TEST(0);
12140   /* 0x7f1f is a mask of SQLITE_OPEN_ flags that are valid to be passed
12141   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
12142   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
12143   ** reaching the VFS. */
12144   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x7f1f, pFlagsOut);
12145   assert( rc==SQLITE_OK || pFile->pMethods==0 );
12146   return rc;
12147 }
12148 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
12149   return pVfs->xDelete(pVfs, zPath, dirSync);
12150 }
12151 SQLITE_PRIVATE int sqlite3OsAccess(
12152   sqlite3_vfs *pVfs, 
12153   const char *zPath, 
12154   int flags, 
12155   int *pResOut
12156 ){
12157   DO_OS_MALLOC_TEST(0);
12158   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
12159 }
12160 SQLITE_PRIVATE int sqlite3OsFullPathname(
12161   sqlite3_vfs *pVfs, 
12162   const char *zPath, 
12163   int nPathOut, 
12164   char *zPathOut
12165 ){
12166   zPathOut[0] = 0;
12167   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
12168 }
12169 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12170 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
12171   return pVfs->xDlOpen(pVfs, zPath);
12172 }
12173 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12174   pVfs->xDlError(pVfs, nByte, zBufOut);
12175 }
12176 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
12177   return pVfs->xDlSym(pVfs, pHdle, zSym);
12178 }
12179 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
12180   pVfs->xDlClose(pVfs, pHandle);
12181 }
12182 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
12183 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12184   return pVfs->xRandomness(pVfs, nByte, zBufOut);
12185 }
12186 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
12187   return pVfs->xSleep(pVfs, nMicro);
12188 }
12189 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
12190   return pVfs->xCurrentTime(pVfs, pTimeOut);
12191 }
12192
12193 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
12194   sqlite3_vfs *pVfs, 
12195   const char *zFile, 
12196   sqlite3_file **ppFile, 
12197   int flags,
12198   int *pOutFlags
12199 ){
12200   int rc = SQLITE_NOMEM;
12201   sqlite3_file *pFile;
12202   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
12203   if( pFile ){
12204     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
12205     if( rc!=SQLITE_OK ){
12206       sqlite3_free(pFile);
12207     }else{
12208       *ppFile = pFile;
12209     }
12210   }
12211   return rc;
12212 }
12213 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
12214   int rc = SQLITE_OK;
12215   assert( pFile );
12216   rc = sqlite3OsClose(pFile);
12217   sqlite3_free(pFile);
12218   return rc;
12219 }
12220
12221 /*
12222 ** This function is a wrapper around the OS specific implementation of
12223 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
12224 ** ability to simulate a malloc failure, so that the handling of an
12225 ** error in sqlite3_os_init() by the upper layers can be tested.
12226 */
12227 SQLITE_PRIVATE int sqlite3OsInit(void){
12228   void *p = sqlite3_malloc(10);
12229   if( p==0 ) return SQLITE_NOMEM;
12230   sqlite3_free(p);
12231   return sqlite3_os_init();
12232 }
12233
12234 /*
12235 ** The list of all registered VFS implementations.
12236 */
12237 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
12238 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
12239
12240 /*
12241 ** Locate a VFS by name.  If no name is given, simply return the
12242 ** first VFS on the list.
12243 */
12244 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
12245   sqlite3_vfs *pVfs = 0;
12246 #if SQLITE_THREADSAFE
12247   sqlite3_mutex *mutex;
12248 #endif
12249 #ifndef SQLITE_OMIT_AUTOINIT
12250   int rc = sqlite3_initialize();
12251   if( rc ) return 0;
12252 #endif
12253 #if SQLITE_THREADSAFE
12254   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12255 #endif
12256   sqlite3_mutex_enter(mutex);
12257   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
12258     if( zVfs==0 ) break;
12259     if( strcmp(zVfs, pVfs->zName)==0 ) break;
12260   }
12261   sqlite3_mutex_leave(mutex);
12262   return pVfs;
12263 }
12264
12265 /*
12266 ** Unlink a VFS from the linked list
12267 */
12268 static void vfsUnlink(sqlite3_vfs *pVfs){
12269   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
12270   if( pVfs==0 ){
12271     /* No-op */
12272   }else if( vfsList==pVfs ){
12273     vfsList = pVfs->pNext;
12274   }else if( vfsList ){
12275     sqlite3_vfs *p = vfsList;
12276     while( p->pNext && p->pNext!=pVfs ){
12277       p = p->pNext;
12278     }
12279     if( p->pNext==pVfs ){
12280       p->pNext = pVfs->pNext;
12281     }
12282   }
12283 }
12284
12285 /*
12286 ** Register a VFS with the system.  It is harmless to register the same
12287 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
12288 ** true.
12289 */
12290 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
12291   sqlite3_mutex *mutex = 0;
12292 #ifndef SQLITE_OMIT_AUTOINIT
12293   int rc = sqlite3_initialize();
12294   if( rc ) return rc;
12295 #endif
12296   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12297   sqlite3_mutex_enter(mutex);
12298   vfsUnlink(pVfs);
12299   if( makeDflt || vfsList==0 ){
12300     pVfs->pNext = vfsList;
12301     vfsList = pVfs;
12302   }else{
12303     pVfs->pNext = vfsList->pNext;
12304     vfsList->pNext = pVfs;
12305   }
12306   assert(vfsList);
12307   sqlite3_mutex_leave(mutex);
12308   return SQLITE_OK;
12309 }
12310
12311 /*
12312 ** Unregister a VFS so that it is no longer accessible.
12313 */
12314 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
12315 #if SQLITE_THREADSAFE
12316   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12317 #endif
12318   sqlite3_mutex_enter(mutex);
12319   vfsUnlink(pVfs);
12320   sqlite3_mutex_leave(mutex);
12321   return SQLITE_OK;
12322 }
12323
12324 /************** End of os.c **************************************************/
12325 /************** Begin file fault.c *******************************************/
12326 /*
12327 ** 2008 Jan 22
12328 **
12329 ** The author disclaims copyright to this source code.  In place of
12330 ** a legal notice, here is a blessing:
12331 **
12332 **    May you do good and not evil.
12333 **    May you find forgiveness for yourself and forgive others.
12334 **    May you share freely, never taking more than you give.
12335 **
12336 *************************************************************************
12337 **
12338 ** This file contains code to support the concept of "benign" 
12339 ** malloc failures (when the xMalloc() or xRealloc() method of the
12340 ** sqlite3_mem_methods structure fails to allocate a block of memory
12341 ** and returns 0). 
12342 **
12343 ** Most malloc failures are non-benign. After they occur, SQLite
12344 ** abandons the current operation and returns an error code (usually
12345 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
12346 ** fatal. For example, if a malloc fails while resizing a hash table, this 
12347 ** is completely recoverable simply by not carrying out the resize. The 
12348 ** hash table will continue to function normally.  So a malloc failure 
12349 ** during a hash table resize is a benign fault.
12350 */
12351
12352
12353 #ifndef SQLITE_OMIT_BUILTIN_TEST
12354
12355 /*
12356 ** Global variables.
12357 */
12358 typedef struct BenignMallocHooks BenignMallocHooks;
12359 static SQLITE_WSD struct BenignMallocHooks {
12360   void (*xBenignBegin)(void);
12361   void (*xBenignEnd)(void);
12362 } sqlite3Hooks = { 0, 0 };
12363
12364 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
12365 ** structure.  If writable static data is unsupported on the target,
12366 ** we have to locate the state vector at run-time.  In the more common
12367 ** case where writable static data is supported, wsdHooks can refer directly
12368 ** to the "sqlite3Hooks" state vector declared above.
12369 */
12370 #ifdef SQLITE_OMIT_WSD
12371 # define wsdHooksInit \
12372   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
12373 # define wsdHooks x[0]
12374 #else
12375 # define wsdHooksInit
12376 # define wsdHooks sqlite3Hooks
12377 #endif
12378
12379
12380 /*
12381 ** Register hooks to call when sqlite3BeginBenignMalloc() and
12382 ** sqlite3EndBenignMalloc() are called, respectively.
12383 */
12384 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
12385   void (*xBenignBegin)(void),
12386   void (*xBenignEnd)(void)
12387 ){
12388   wsdHooksInit;
12389   wsdHooks.xBenignBegin = xBenignBegin;
12390   wsdHooks.xBenignEnd = xBenignEnd;
12391 }
12392
12393 /*
12394 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
12395 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
12396 ** indicates that subsequent malloc failures are non-benign.
12397 */
12398 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
12399   wsdHooksInit;
12400   if( wsdHooks.xBenignBegin ){
12401     wsdHooks.xBenignBegin();
12402   }
12403 }
12404 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
12405   wsdHooksInit;
12406   if( wsdHooks.xBenignEnd ){
12407     wsdHooks.xBenignEnd();
12408   }
12409 }
12410
12411 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
12412
12413 /************** End of fault.c ***********************************************/
12414 /************** Begin file mem0.c ********************************************/
12415 /*
12416 ** 2008 October 28
12417 **
12418 ** The author disclaims copyright to this source code.  In place of
12419 ** a legal notice, here is a blessing:
12420 **
12421 **    May you do good and not evil.
12422 **    May you find forgiveness for yourself and forgive others.
12423 **    May you share freely, never taking more than you give.
12424 **
12425 *************************************************************************
12426 **
12427 ** This file contains a no-op memory allocation drivers for use when
12428 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
12429 ** here always fail.  SQLite will not operate with these drivers.  These
12430 ** are merely placeholders.  Real drivers must be substituted using
12431 ** sqlite3_config() before SQLite will operate.
12432 */
12433
12434 /*
12435 ** This version of the memory allocator is the default.  It is
12436 ** used when no other memory allocator is specified using compile-time
12437 ** macros.
12438 */
12439 #ifdef SQLITE_ZERO_MALLOC
12440
12441 /*
12442 ** No-op versions of all memory allocation routines
12443 */
12444 static void *sqlite3MemMalloc(int nByte){ return 0; }
12445 static void sqlite3MemFree(void *pPrior){ return; }
12446 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
12447 static int sqlite3MemSize(void *pPrior){ return 0; }
12448 static int sqlite3MemRoundup(int n){ return n; }
12449 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
12450 static void sqlite3MemShutdown(void *NotUsed){ return; }
12451
12452 /*
12453 ** This routine is the only routine in this file with external linkage.
12454 **
12455 ** Populate the low-level memory allocation function pointers in
12456 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
12457 */
12458 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12459   static const sqlite3_mem_methods defaultMethods = {
12460      sqlite3MemMalloc,
12461      sqlite3MemFree,
12462      sqlite3MemRealloc,
12463      sqlite3MemSize,
12464      sqlite3MemRoundup,
12465      sqlite3MemInit,
12466      sqlite3MemShutdown,
12467      0
12468   };
12469   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
12470 }
12471
12472 #endif /* SQLITE_ZERO_MALLOC */
12473
12474 /************** End of mem0.c ************************************************/
12475 /************** Begin file mem1.c ********************************************/
12476 /*
12477 ** 2007 August 14
12478 **
12479 ** The author disclaims copyright to this source code.  In place of
12480 ** a legal notice, here is a blessing:
12481 **
12482 **    May you do good and not evil.
12483 **    May you find forgiveness for yourself and forgive others.
12484 **    May you share freely, never taking more than you give.
12485 **
12486 *************************************************************************
12487 **
12488 ** This file contains low-level memory allocation drivers for when
12489 ** SQLite will use the standard C-library malloc/realloc/free interface
12490 ** to obtain the memory it needs.
12491 **
12492 ** This file contains implementations of the low-level memory allocation
12493 ** routines specified in the sqlite3_mem_methods object.
12494 */
12495
12496 /*
12497 ** This version of the memory allocator is the default.  It is
12498 ** used when no other memory allocator is specified using compile-time
12499 ** macros.
12500 */
12501 #ifdef SQLITE_SYSTEM_MALLOC
12502
12503 /*
12504 ** Like malloc(), but remember the size of the allocation
12505 ** so that we can find it later using sqlite3MemSize().
12506 **
12507 ** For this low-level routine, we are guaranteed that nByte>0 because
12508 ** cases of nByte<=0 will be intercepted and dealt with by higher level
12509 ** routines.
12510 */
12511 static void *sqlite3MemMalloc(int nByte){
12512   sqlite3_int64 *p;
12513   assert( nByte>0 );
12514   nByte = ROUND8(nByte);
12515   p = malloc( nByte+8 );
12516   if( p ){
12517     p[0] = nByte;
12518     p++;
12519   }
12520   return (void *)p;
12521 }
12522
12523 /*
12524 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
12525 ** or sqlite3MemRealloc().
12526 **
12527 ** For this low-level routine, we already know that pPrior!=0 since
12528 ** cases where pPrior==0 will have been intecepted and dealt with
12529 ** by higher-level routines.
12530 */
12531 static void sqlite3MemFree(void *pPrior){
12532   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12533   assert( pPrior!=0 );
12534   p--;
12535   free(p);
12536 }
12537
12538 /*
12539 ** Like realloc().  Resize an allocation previously obtained from
12540 ** sqlite3MemMalloc().
12541 **
12542 ** For this low-level interface, we know that pPrior!=0.  Cases where
12543 ** pPrior==0 while have been intercepted by higher-level routine and
12544 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
12545 ** cases where nByte<=0 will have been intercepted by higher-level
12546 ** routines and redirected to xFree.
12547 */
12548 static void *sqlite3MemRealloc(void *pPrior, int nByte){
12549   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12550   assert( pPrior!=0 && nByte>0 );
12551   nByte = ROUND8(nByte);
12552   p = (sqlite3_int64*)pPrior;
12553   p--;
12554   p = realloc(p, nByte+8 );
12555   if( p ){
12556     p[0] = nByte;
12557     p++;
12558   }
12559   return (void*)p;
12560 }
12561
12562 /*
12563 ** Report the allocated size of a prior return from xMalloc()
12564 ** or xRealloc().
12565 */
12566 static int sqlite3MemSize(void *pPrior){
12567   sqlite3_int64 *p;
12568   if( pPrior==0 ) return 0;
12569   p = (sqlite3_int64*)pPrior;
12570   p--;
12571   return (int)p[0];
12572 }
12573
12574 /*
12575 ** Round up a request size to the next valid allocation size.
12576 */
12577 static int sqlite3MemRoundup(int n){
12578   return ROUND8(n);
12579 }
12580
12581 /*
12582 ** Initialize this module.
12583 */
12584 static int sqlite3MemInit(void *NotUsed){
12585   UNUSED_PARAMETER(NotUsed);
12586   return SQLITE_OK;
12587 }
12588
12589 /*
12590 ** Deinitialize this module.
12591 */
12592 static void sqlite3MemShutdown(void *NotUsed){
12593   UNUSED_PARAMETER(NotUsed);
12594   return;
12595 }
12596
12597 /*
12598 ** This routine is the only routine in this file with external linkage.
12599 **
12600 ** Populate the low-level memory allocation function pointers in
12601 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
12602 */
12603 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12604   static const sqlite3_mem_methods defaultMethods = {
12605      sqlite3MemMalloc,
12606      sqlite3MemFree,
12607      sqlite3MemRealloc,
12608      sqlite3MemSize,
12609      sqlite3MemRoundup,
12610      sqlite3MemInit,
12611      sqlite3MemShutdown,
12612      0
12613   };
12614   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
12615 }
12616
12617 #endif /* SQLITE_SYSTEM_MALLOC */
12618
12619 /************** End of mem1.c ************************************************/
12620 /************** Begin file mem2.c ********************************************/
12621 /*
12622 ** 2007 August 15
12623 **
12624 ** The author disclaims copyright to this source code.  In place of
12625 ** a legal notice, here is a blessing:
12626 **
12627 **    May you do good and not evil.
12628 **    May you find forgiveness for yourself and forgive others.
12629 **    May you share freely, never taking more than you give.
12630 **
12631 *************************************************************************
12632 **
12633 ** This file contains low-level memory allocation drivers for when
12634 ** SQLite will use the standard C-library malloc/realloc/free interface
12635 ** to obtain the memory it needs while adding lots of additional debugging
12636 ** information to each allocation in order to help detect and fix memory
12637 ** leaks and memory usage errors.
12638 **
12639 ** This file contains implementations of the low-level memory allocation
12640 ** routines specified in the sqlite3_mem_methods object.
12641 */
12642
12643 /*
12644 ** This version of the memory allocator is used only if the
12645 ** SQLITE_MEMDEBUG macro is defined
12646 */
12647 #ifdef SQLITE_MEMDEBUG
12648
12649 /*
12650 ** The backtrace functionality is only available with GLIBC
12651 */
12652 #ifdef __GLIBC__
12653   extern int backtrace(void**,int);
12654   extern void backtrace_symbols_fd(void*const*,int,int);
12655 #else
12656 # define backtrace(A,B) 1
12657 # define backtrace_symbols_fd(A,B,C)
12658 #endif
12659
12660 /*
12661 ** Each memory allocation looks like this:
12662 **
12663 **  ------------------------------------------------------------------------
12664 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
12665 **  ------------------------------------------------------------------------
12666 **
12667 ** The application code sees only a pointer to the allocation.  We have
12668 ** to back up from the allocation pointer to find the MemBlockHdr.  The
12669 ** MemBlockHdr tells us the size of the allocation and the number of
12670 ** backtrace pointers.  There is also a guard word at the end of the
12671 ** MemBlockHdr.
12672 */
12673 struct MemBlockHdr {
12674   i64 iSize;                          /* Size of this allocation */
12675   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
12676   char nBacktrace;                    /* Number of backtraces on this alloc */
12677   char nBacktraceSlots;               /* Available backtrace slots */
12678   short nTitle;                       /* Bytes of title; includes '\0' */
12679   int iForeGuard;                     /* Guard word for sanity */
12680 };
12681
12682 /*
12683 ** Guard words
12684 */
12685 #define FOREGUARD 0x80F5E153
12686 #define REARGUARD 0xE4676B53
12687
12688 /*
12689 ** Number of malloc size increments to track.
12690 */
12691 #define NCSIZE  1000
12692
12693 /*
12694 ** All of the static variables used by this module are collected
12695 ** into a single structure named "mem".  This is to keep the
12696 ** static variables organized and to reduce namespace pollution
12697 ** when this module is combined with other in the amalgamation.
12698 */
12699 static struct {
12700   
12701   /*
12702   ** Mutex to control access to the memory allocation subsystem.
12703   */
12704   sqlite3_mutex *mutex;
12705
12706   /*
12707   ** Head and tail of a linked list of all outstanding allocations
12708   */
12709   struct MemBlockHdr *pFirst;
12710   struct MemBlockHdr *pLast;
12711   
12712   /*
12713   ** The number of levels of backtrace to save in new allocations.
12714   */
12715   int nBacktrace;
12716   void (*xBacktrace)(int, int, void **);
12717
12718   /*
12719   ** Title text to insert in front of each block
12720   */
12721   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
12722   char zTitle[100];  /* The title text */
12723
12724   /* 
12725   ** sqlite3MallocDisallow() increments the following counter.
12726   ** sqlite3MallocAllow() decrements it.
12727   */
12728   int disallow; /* Do not allow memory allocation */
12729
12730   /*
12731   ** Gather statistics on the sizes of memory allocations.
12732   ** nAlloc[i] is the number of allocation attempts of i*8
12733   ** bytes.  i==NCSIZE is the number of allocation attempts for
12734   ** sizes more than NCSIZE*8 bytes.
12735   */
12736   int nAlloc[NCSIZE];      /* Total number of allocations */
12737   int nCurrent[NCSIZE];    /* Current number of allocations */
12738   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
12739
12740 } mem;
12741
12742
12743 /*
12744 ** Adjust memory usage statistics
12745 */
12746 static void adjustStats(int iSize, int increment){
12747   int i = ROUND8(iSize)/8;
12748   if( i>NCSIZE-1 ){
12749     i = NCSIZE - 1;
12750   }
12751   if( increment>0 ){
12752     mem.nAlloc[i]++;
12753     mem.nCurrent[i]++;
12754     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
12755       mem.mxCurrent[i] = mem.nCurrent[i];
12756     }
12757   }else{
12758     mem.nCurrent[i]--;
12759     assert( mem.nCurrent[i]>=0 );
12760   }
12761 }
12762
12763 /*
12764 ** Given an allocation, find the MemBlockHdr for that allocation.
12765 **
12766 ** This routine checks the guards at either end of the allocation and
12767 ** if they are incorrect it asserts.
12768 */
12769 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
12770   struct MemBlockHdr *p;
12771   int *pInt;
12772   u8 *pU8;
12773   int nReserve;
12774
12775   p = (struct MemBlockHdr*)pAllocation;
12776   p--;
12777   assert( p->iForeGuard==(int)FOREGUARD );
12778   nReserve = ROUND8(p->iSize);
12779   pInt = (int*)pAllocation;
12780   pU8 = (u8*)pAllocation;
12781   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
12782   /* This checks any of the "extra" bytes allocated due
12783   ** to rounding up to an 8 byte boundary to ensure 
12784   ** they haven't been overwritten.
12785   */
12786   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
12787   return p;
12788 }
12789
12790 /*
12791 ** Return the number of bytes currently allocated at address p.
12792 */
12793 static int sqlite3MemSize(void *p){
12794   struct MemBlockHdr *pHdr;
12795   if( !p ){
12796     return 0;
12797   }
12798   pHdr = sqlite3MemsysGetHeader(p);
12799   return pHdr->iSize;
12800 }
12801
12802 /*
12803 ** Initialize the memory allocation subsystem.
12804 */
12805 static int sqlite3MemInit(void *NotUsed){
12806   UNUSED_PARAMETER(NotUsed);
12807   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
12808   if( !sqlite3GlobalConfig.bMemstat ){
12809     /* If memory status is enabled, then the malloc.c wrapper will already
12810     ** hold the STATIC_MEM mutex when the routines here are invoked. */
12811     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
12812   }
12813   return SQLITE_OK;
12814 }
12815
12816 /*
12817 ** Deinitialize the memory allocation subsystem.
12818 */
12819 static void sqlite3MemShutdown(void *NotUsed){
12820   UNUSED_PARAMETER(NotUsed);
12821   mem.mutex = 0;
12822 }
12823
12824 /*
12825 ** Round up a request size to the next valid allocation size.
12826 */
12827 static int sqlite3MemRoundup(int n){
12828   return ROUND8(n);
12829 }
12830
12831 /*
12832 ** Fill a buffer with pseudo-random bytes.  This is used to preset
12833 ** the content of a new memory allocation to unpredictable values and
12834 ** to clear the content of a freed allocation to unpredictable values.
12835 */
12836 static void randomFill(char *pBuf, int nByte){
12837   unsigned int x, y, r;
12838   x = SQLITE_PTR_TO_INT(pBuf);
12839   y = nByte | 1;
12840   while( nByte >= 4 ){
12841     x = (x>>1) ^ (-(x&1) & 0xd0000001);
12842     y = y*1103515245 + 12345;
12843     r = x ^ y;
12844     *(int*)pBuf = r;
12845     pBuf += 4;
12846     nByte -= 4;
12847   }
12848   while( nByte-- > 0 ){
12849     x = (x>>1) ^ (-(x&1) & 0xd0000001);
12850     y = y*1103515245 + 12345;
12851     r = x ^ y;
12852     *(pBuf++) = r & 0xff;
12853   }
12854 }
12855
12856 /*
12857 ** Allocate nByte bytes of memory.
12858 */
12859 static void *sqlite3MemMalloc(int nByte){
12860   struct MemBlockHdr *pHdr;
12861   void **pBt;
12862   char *z;
12863   int *pInt;
12864   void *p = 0;
12865   int totalSize;
12866   int nReserve;
12867   sqlite3_mutex_enter(mem.mutex);
12868   assert( mem.disallow==0 );
12869   nReserve = ROUND8(nByte);
12870   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
12871                mem.nBacktrace*sizeof(void*) + mem.nTitle;
12872   p = malloc(totalSize);
12873   if( p ){
12874     z = p;
12875     pBt = (void**)&z[mem.nTitle];
12876     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
12877     pHdr->pNext = 0;
12878     pHdr->pPrev = mem.pLast;
12879     if( mem.pLast ){
12880       mem.pLast->pNext = pHdr;
12881     }else{
12882       mem.pFirst = pHdr;
12883     }
12884     mem.pLast = pHdr;
12885     pHdr->iForeGuard = FOREGUARD;
12886     pHdr->nBacktraceSlots = mem.nBacktrace;
12887     pHdr->nTitle = mem.nTitle;
12888     if( mem.nBacktrace ){
12889       void *aAddr[40];
12890       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
12891       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
12892       assert(pBt[0]);
12893       if( mem.xBacktrace ){
12894         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
12895       }
12896     }else{
12897       pHdr->nBacktrace = 0;
12898     }
12899     if( mem.nTitle ){
12900       memcpy(z, mem.zTitle, mem.nTitle);
12901     }
12902     pHdr->iSize = nByte;
12903     adjustStats(nByte, +1);
12904     pInt = (int*)&pHdr[1];
12905     pInt[nReserve/sizeof(int)] = REARGUARD;
12906     randomFill((char*)pInt, nByte);
12907     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
12908     p = (void*)pInt;
12909   }
12910   sqlite3_mutex_leave(mem.mutex);
12911   return p; 
12912 }
12913
12914 /*
12915 ** Free memory.
12916 */
12917 static void sqlite3MemFree(void *pPrior){
12918   struct MemBlockHdr *pHdr;
12919   void **pBt;
12920   char *z;
12921   assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 );
12922   pHdr = sqlite3MemsysGetHeader(pPrior);
12923   pBt = (void**)pHdr;
12924   pBt -= pHdr->nBacktraceSlots;
12925   sqlite3_mutex_enter(mem.mutex);
12926   if( pHdr->pPrev ){
12927     assert( pHdr->pPrev->pNext==pHdr );
12928     pHdr->pPrev->pNext = pHdr->pNext;
12929   }else{
12930     assert( mem.pFirst==pHdr );
12931     mem.pFirst = pHdr->pNext;
12932   }
12933   if( pHdr->pNext ){
12934     assert( pHdr->pNext->pPrev==pHdr );
12935     pHdr->pNext->pPrev = pHdr->pPrev;
12936   }else{
12937     assert( mem.pLast==pHdr );
12938     mem.pLast = pHdr->pPrev;
12939   }
12940   z = (char*)pBt;
12941   z -= pHdr->nTitle;
12942   adjustStats(pHdr->iSize, -1);
12943   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
12944                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
12945   free(z);
12946   sqlite3_mutex_leave(mem.mutex);  
12947 }
12948
12949 /*
12950 ** Change the size of an existing memory allocation.
12951 **
12952 ** For this debugging implementation, we *always* make a copy of the
12953 ** allocation into a new place in memory.  In this way, if the 
12954 ** higher level code is using pointer to the old allocation, it is 
12955 ** much more likely to break and we are much more liking to find
12956 ** the error.
12957 */
12958 static void *sqlite3MemRealloc(void *pPrior, int nByte){
12959   struct MemBlockHdr *pOldHdr;
12960   void *pNew;
12961   assert( mem.disallow==0 );
12962   pOldHdr = sqlite3MemsysGetHeader(pPrior);
12963   pNew = sqlite3MemMalloc(nByte);
12964   if( pNew ){
12965     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
12966     if( nByte>pOldHdr->iSize ){
12967       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
12968     }
12969     sqlite3MemFree(pPrior);
12970   }
12971   return pNew;
12972 }
12973
12974 /*
12975 ** Populate the low-level memory allocation function pointers in
12976 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
12977 */
12978 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12979   static const sqlite3_mem_methods defaultMethods = {
12980      sqlite3MemMalloc,
12981      sqlite3MemFree,
12982      sqlite3MemRealloc,
12983      sqlite3MemSize,
12984      sqlite3MemRoundup,
12985      sqlite3MemInit,
12986      sqlite3MemShutdown,
12987      0
12988   };
12989   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
12990 }
12991
12992 /*
12993 ** Set the number of backtrace levels kept for each allocation.
12994 ** A value of zero turns off backtracing.  The number is always rounded
12995 ** up to a multiple of 2.
12996 */
12997 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
12998   if( depth<0 ){ depth = 0; }
12999   if( depth>20 ){ depth = 20; }
13000   depth = (depth+1)&0xfe;
13001   mem.nBacktrace = depth;
13002 }
13003
13004 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
13005   mem.xBacktrace = xBacktrace;
13006 }
13007
13008 /*
13009 ** Set the title string for subsequent allocations.
13010 */
13011 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
13012   unsigned int n = sqlite3Strlen30(zTitle) + 1;
13013   sqlite3_mutex_enter(mem.mutex);
13014   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
13015   memcpy(mem.zTitle, zTitle, n);
13016   mem.zTitle[n] = 0;
13017   mem.nTitle = ROUND8(n);
13018   sqlite3_mutex_leave(mem.mutex);
13019 }
13020
13021 SQLITE_PRIVATE void sqlite3MemdebugSync(){
13022   struct MemBlockHdr *pHdr;
13023   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13024     void **pBt = (void**)pHdr;
13025     pBt -= pHdr->nBacktraceSlots;
13026     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
13027   }
13028 }
13029
13030 /*
13031 ** Open the file indicated and write a log of all unfreed memory 
13032 ** allocations into that log.
13033 */
13034 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
13035   FILE *out;
13036   struct MemBlockHdr *pHdr;
13037   void **pBt;
13038   int i;
13039   out = fopen(zFilename, "w");
13040   if( out==0 ){
13041     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13042                     zFilename);
13043     return;
13044   }
13045   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13046     char *z = (char*)pHdr;
13047     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
13048     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
13049             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
13050     if( pHdr->nBacktrace ){
13051       fflush(out);
13052       pBt = (void**)pHdr;
13053       pBt -= pHdr->nBacktraceSlots;
13054       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
13055       fprintf(out, "\n");
13056     }
13057   }
13058   fprintf(out, "COUNTS:\n");
13059   for(i=0; i<NCSIZE-1; i++){
13060     if( mem.nAlloc[i] ){
13061       fprintf(out, "   %5d: %10d %10d %10d\n", 
13062             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
13063     }
13064   }
13065   if( mem.nAlloc[NCSIZE-1] ){
13066     fprintf(out, "   %5d: %10d %10d %10d\n",
13067              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
13068              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
13069   }
13070   fclose(out);
13071 }
13072
13073 /*
13074 ** Return the number of times sqlite3MemMalloc() has been called.
13075 */
13076 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
13077   int i;
13078   int nTotal = 0;
13079   for(i=0; i<NCSIZE; i++){
13080     nTotal += mem.nAlloc[i];
13081   }
13082   return nTotal;
13083 }
13084
13085
13086 #endif /* SQLITE_MEMDEBUG */
13087
13088 /************** End of mem2.c ************************************************/
13089 /************** Begin file mem3.c ********************************************/
13090 /*
13091 ** 2007 October 14
13092 **
13093 ** The author disclaims copyright to this source code.  In place of
13094 ** a legal notice, here is a blessing:
13095 **
13096 **    May you do good and not evil.
13097 **    May you find forgiveness for yourself and forgive others.
13098 **    May you share freely, never taking more than you give.
13099 **
13100 *************************************************************************
13101 ** This file contains the C functions that implement a memory
13102 ** allocation subsystem for use by SQLite. 
13103 **
13104 ** This version of the memory allocation subsystem omits all
13105 ** use of malloc(). The SQLite user supplies a block of memory
13106 ** before calling sqlite3_initialize() from which allocations
13107 ** are made and returned by the xMalloc() and xRealloc() 
13108 ** implementations. Once sqlite3_initialize() has been called,
13109 ** the amount of memory available to SQLite is fixed and cannot
13110 ** be changed.
13111 **
13112 ** This version of the memory allocation subsystem is included
13113 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
13114 */
13115
13116 /*
13117 ** This version of the memory allocator is only built into the library
13118 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
13119 ** mean that the library will use a memory-pool by default, just that
13120 ** it is available. The mempool allocator is activated by calling
13121 ** sqlite3_config().
13122 */
13123 #ifdef SQLITE_ENABLE_MEMSYS3
13124
13125 /*
13126 ** Maximum size (in Mem3Blocks) of a "small" chunk.
13127 */
13128 #define MX_SMALL 10
13129
13130
13131 /*
13132 ** Number of freelist hash slots
13133 */
13134 #define N_HASH  61
13135
13136 /*
13137 ** A memory allocation (also called a "chunk") consists of two or 
13138 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
13139 ** a header that is not returned to the user.
13140 **
13141 ** A chunk is two or more blocks that is either checked out or
13142 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
13143 ** size of the allocation in blocks if the allocation is free.
13144 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
13145 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
13146 ** is true if the previous chunk is checked out and false if the
13147 ** previous chunk is free.  The u.hdr.prevSize field is the size of
13148 ** the previous chunk in blocks if the previous chunk is on the
13149 ** freelist. If the previous chunk is checked out, then
13150 ** u.hdr.prevSize can be part of the data for that chunk and should
13151 ** not be read or written.
13152 **
13153 ** We often identify a chunk by its index in mem3.aPool[].  When
13154 ** this is done, the chunk index refers to the second block of
13155 ** the chunk.  In this way, the first chunk has an index of 1.
13156 ** A chunk index of 0 means "no such chunk" and is the equivalent
13157 ** of a NULL pointer.
13158 **
13159 ** The second block of free chunks is of the form u.list.  The
13160 ** two fields form a double-linked list of chunks of related sizes.
13161 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
13162 ** for smaller chunks and mem3.aiHash[] for larger chunks.
13163 **
13164 ** The second block of a chunk is user data if the chunk is checked 
13165 ** out.  If a chunk is checked out, the user data may extend into
13166 ** the u.hdr.prevSize value of the following chunk.
13167 */
13168 typedef struct Mem3Block Mem3Block;
13169 struct Mem3Block {
13170   union {
13171     struct {
13172       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
13173       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
13174     } hdr;
13175     struct {
13176       u32 next;       /* Index in mem3.aPool[] of next free chunk */
13177       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
13178     } list;
13179   } u;
13180 };
13181
13182 /*
13183 ** All of the static variables used by this module are collected
13184 ** into a single structure named "mem3".  This is to keep the
13185 ** static variables organized and to reduce namespace pollution
13186 ** when this module is combined with other in the amalgamation.
13187 */
13188 static SQLITE_WSD struct Mem3Global {
13189   /*
13190   ** Memory available for allocation. nPool is the size of the array
13191   ** (in Mem3Blocks) pointed to by aPool less 2.
13192   */
13193   u32 nPool;
13194   Mem3Block *aPool;
13195
13196   /*
13197   ** True if we are evaluating an out-of-memory callback.
13198   */
13199   int alarmBusy;
13200   
13201   /*
13202   ** Mutex to control access to the memory allocation subsystem.
13203   */
13204   sqlite3_mutex *mutex;
13205   
13206   /*
13207   ** The minimum amount of free space that we have seen.
13208   */
13209   u32 mnMaster;
13210
13211   /*
13212   ** iMaster is the index of the master chunk.  Most new allocations
13213   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
13214   ** of the current master.  iMaster is 0 if there is not master chunk.
13215   ** The master chunk is not in either the aiHash[] or aiSmall[].
13216   */
13217   u32 iMaster;
13218   u32 szMaster;
13219
13220   /*
13221   ** Array of lists of free blocks according to the block size 
13222   ** for smaller chunks, or a hash on the block size for larger
13223   ** chunks.
13224   */
13225   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
13226   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
13227 } mem3 = { 97535575 };
13228
13229 #define mem3 GLOBAL(struct Mem3Global, mem3)
13230
13231 /*
13232 ** Unlink the chunk at mem3.aPool[i] from list it is currently
13233 ** on.  *pRoot is the list that i is a member of.
13234 */
13235 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
13236   u32 next = mem3.aPool[i].u.list.next;
13237   u32 prev = mem3.aPool[i].u.list.prev;
13238   assert( sqlite3_mutex_held(mem3.mutex) );
13239   if( prev==0 ){
13240     *pRoot = next;
13241   }else{
13242     mem3.aPool[prev].u.list.next = next;
13243   }
13244   if( next ){
13245     mem3.aPool[next].u.list.prev = prev;
13246   }
13247   mem3.aPool[i].u.list.next = 0;
13248   mem3.aPool[i].u.list.prev = 0;
13249 }
13250
13251 /*
13252 ** Unlink the chunk at index i from 
13253 ** whatever list is currently a member of.
13254 */
13255 static void memsys3Unlink(u32 i){
13256   u32 size, hash;
13257   assert( sqlite3_mutex_held(mem3.mutex) );
13258   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13259   assert( i>=1 );
13260   size = mem3.aPool[i-1].u.hdr.size4x/4;
13261   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13262   assert( size>=2 );
13263   if( size <= MX_SMALL ){
13264     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
13265   }else{
13266     hash = size % N_HASH;
13267     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13268   }
13269 }
13270
13271 /*
13272 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
13273 ** at *pRoot.
13274 */
13275 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
13276   assert( sqlite3_mutex_held(mem3.mutex) );
13277   mem3.aPool[i].u.list.next = *pRoot;
13278   mem3.aPool[i].u.list.prev = 0;
13279   if( *pRoot ){
13280     mem3.aPool[*pRoot].u.list.prev = i;
13281   }
13282   *pRoot = i;
13283 }
13284
13285 /*
13286 ** Link the chunk at index i into either the appropriate
13287 ** small chunk list, or into the large chunk hash table.
13288 */
13289 static void memsys3Link(u32 i){
13290   u32 size, hash;
13291   assert( sqlite3_mutex_held(mem3.mutex) );
13292   assert( i>=1 );
13293   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13294   size = mem3.aPool[i-1].u.hdr.size4x/4;
13295   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13296   assert( size>=2 );
13297   if( size <= MX_SMALL ){
13298     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
13299   }else{
13300     hash = size % N_HASH;
13301     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
13302   }
13303 }
13304
13305 /*
13306 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13307 ** will already be held (obtained by code in malloc.c) if
13308 ** sqlite3GlobalConfig.bMemStat is true.
13309 */
13310 static void memsys3Enter(void){
13311   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
13312     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13313   }
13314   sqlite3_mutex_enter(mem3.mutex);
13315 }
13316 static void memsys3Leave(void){
13317   sqlite3_mutex_leave(mem3.mutex);
13318 }
13319
13320 /*
13321 ** Called when we are unable to satisfy an allocation of nBytes.
13322 */
13323 static void memsys3OutOfMemory(int nByte){
13324   if( !mem3.alarmBusy ){
13325     mem3.alarmBusy = 1;
13326     assert( sqlite3_mutex_held(mem3.mutex) );
13327     sqlite3_mutex_leave(mem3.mutex);
13328     sqlite3_release_memory(nByte);
13329     sqlite3_mutex_enter(mem3.mutex);
13330     mem3.alarmBusy = 0;
13331   }
13332 }
13333
13334
13335 /*
13336 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
13337 ** size parameters for check-out and return a pointer to the 
13338 ** user portion of the chunk.
13339 */
13340 static void *memsys3Checkout(u32 i, u32 nBlock){
13341   u32 x;
13342   assert( sqlite3_mutex_held(mem3.mutex) );
13343   assert( i>=1 );
13344   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
13345   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
13346   x = mem3.aPool[i-1].u.hdr.size4x;
13347   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
13348   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
13349   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
13350   return &mem3.aPool[i];
13351 }
13352
13353 /*
13354 ** Carve a piece off of the end of the mem3.iMaster free chunk.
13355 ** Return a pointer to the new allocation.  Or, if the master chunk
13356 ** is not large enough, return 0.
13357 */
13358 static void *memsys3FromMaster(u32 nBlock){
13359   assert( sqlite3_mutex_held(mem3.mutex) );
13360   assert( mem3.szMaster>=nBlock );
13361   if( nBlock>=mem3.szMaster-1 ){
13362     /* Use the entire master */
13363     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
13364     mem3.iMaster = 0;
13365     mem3.szMaster = 0;
13366     mem3.mnMaster = 0;
13367     return p;
13368   }else{
13369     /* Split the master block.  Return the tail. */
13370     u32 newi, x;
13371     newi = mem3.iMaster + mem3.szMaster - nBlock;
13372     assert( newi > mem3.iMaster+1 );
13373     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
13374     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
13375     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
13376     mem3.szMaster -= nBlock;
13377     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
13378     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13379     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13380     if( mem3.szMaster < mem3.mnMaster ){
13381       mem3.mnMaster = mem3.szMaster;
13382     }
13383     return (void*)&mem3.aPool[newi];
13384   }
13385 }
13386
13387 /*
13388 ** *pRoot is the head of a list of free chunks of the same size
13389 ** or same size hash.  In other words, *pRoot is an entry in either
13390 ** mem3.aiSmall[] or mem3.aiHash[].  
13391 **
13392 ** This routine examines all entries on the given list and tries
13393 ** to coalesce each entries with adjacent free chunks.  
13394 **
13395 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
13396 ** the current mem3.iMaster with the new larger chunk.  In order for
13397 ** this mem3.iMaster replacement to work, the master chunk must be
13398 ** linked into the hash tables.  That is not the normal state of
13399 ** affairs, of course.  The calling routine must link the master
13400 ** chunk before invoking this routine, then must unlink the (possibly
13401 ** changed) master chunk once this routine has finished.
13402 */
13403 static void memsys3Merge(u32 *pRoot){
13404   u32 iNext, prev, size, i, x;
13405
13406   assert( sqlite3_mutex_held(mem3.mutex) );
13407   for(i=*pRoot; i>0; i=iNext){
13408     iNext = mem3.aPool[i].u.list.next;
13409     size = mem3.aPool[i-1].u.hdr.size4x;
13410     assert( (size&1)==0 );
13411     if( (size&2)==0 ){
13412       memsys3UnlinkFromList(i, pRoot);
13413       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
13414       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
13415       if( prev==iNext ){
13416         iNext = mem3.aPool[prev].u.list.next;
13417       }
13418       memsys3Unlink(prev);
13419       size = i + size/4 - prev;
13420       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
13421       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
13422       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
13423       memsys3Link(prev);
13424       i = prev;
13425     }else{
13426       size /= 4;
13427     }
13428     if( size>mem3.szMaster ){
13429       mem3.iMaster = i;
13430       mem3.szMaster = size;
13431     }
13432   }
13433 }
13434
13435 /*
13436 ** Return a block of memory of at least nBytes in size.
13437 ** Return NULL if unable.
13438 **
13439 ** This function assumes that the necessary mutexes, if any, are
13440 ** already held by the caller. Hence "Unsafe".
13441 */
13442 static void *memsys3MallocUnsafe(int nByte){
13443   u32 i;
13444   u32 nBlock;
13445   u32 toFree;
13446
13447   assert( sqlite3_mutex_held(mem3.mutex) );
13448   assert( sizeof(Mem3Block)==8 );
13449   if( nByte<=12 ){
13450     nBlock = 2;
13451   }else{
13452     nBlock = (nByte + 11)/8;
13453   }
13454   assert( nBlock>=2 );
13455
13456   /* STEP 1:
13457   ** Look for an entry of the correct size in either the small
13458   ** chunk table or in the large chunk hash table.  This is
13459   ** successful most of the time (about 9 times out of 10).
13460   */
13461   if( nBlock <= MX_SMALL ){
13462     i = mem3.aiSmall[nBlock-2];
13463     if( i>0 ){
13464       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
13465       return memsys3Checkout(i, nBlock);
13466     }
13467   }else{
13468     int hash = nBlock % N_HASH;
13469     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
13470       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
13471         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13472         return memsys3Checkout(i, nBlock);
13473       }
13474     }
13475   }
13476
13477   /* STEP 2:
13478   ** Try to satisfy the allocation by carving a piece off of the end
13479   ** of the master chunk.  This step usually works if step 1 fails.
13480   */
13481   if( mem3.szMaster>=nBlock ){
13482     return memsys3FromMaster(nBlock);
13483   }
13484
13485
13486   /* STEP 3:  
13487   ** Loop through the entire memory pool.  Coalesce adjacent free
13488   ** chunks.  Recompute the master chunk as the largest free chunk.
13489   ** Then try again to satisfy the allocation by carving a piece off
13490   ** of the end of the master chunk.  This step happens very
13491   ** rarely (we hope!)
13492   */
13493   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
13494     memsys3OutOfMemory(toFree);
13495     if( mem3.iMaster ){
13496       memsys3Link(mem3.iMaster);
13497       mem3.iMaster = 0;
13498       mem3.szMaster = 0;
13499     }
13500     for(i=0; i<N_HASH; i++){
13501       memsys3Merge(&mem3.aiHash[i]);
13502     }
13503     for(i=0; i<MX_SMALL-1; i++){
13504       memsys3Merge(&mem3.aiSmall[i]);
13505     }
13506     if( mem3.szMaster ){
13507       memsys3Unlink(mem3.iMaster);
13508       if( mem3.szMaster>=nBlock ){
13509         return memsys3FromMaster(nBlock);
13510       }
13511     }
13512   }
13513
13514   /* If none of the above worked, then we fail. */
13515   return 0;
13516 }
13517
13518 /*
13519 ** Free an outstanding memory allocation.
13520 **
13521 ** This function assumes that the necessary mutexes, if any, are
13522 ** already held by the caller. Hence "Unsafe".
13523 */
13524 void memsys3FreeUnsafe(void *pOld){
13525   Mem3Block *p = (Mem3Block*)pOld;
13526   int i;
13527   u32 size, x;
13528   assert( sqlite3_mutex_held(mem3.mutex) );
13529   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
13530   i = p - mem3.aPool;
13531   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
13532   size = mem3.aPool[i-1].u.hdr.size4x/4;
13533   assert( i+size<=mem3.nPool+1 );
13534   mem3.aPool[i-1].u.hdr.size4x &= ~1;
13535   mem3.aPool[i+size-1].u.hdr.prevSize = size;
13536   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
13537   memsys3Link(i);
13538
13539   /* Try to expand the master using the newly freed chunk */
13540   if( mem3.iMaster ){
13541     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
13542       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
13543       mem3.iMaster -= size;
13544       mem3.szMaster += size;
13545       memsys3Unlink(mem3.iMaster);
13546       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13547       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13548       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
13549     }
13550     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13551     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
13552       memsys3Unlink(mem3.iMaster+mem3.szMaster);
13553       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
13554       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13555       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
13556     }
13557   }
13558 }
13559
13560 /*
13561 ** Return the size of an outstanding allocation, in bytes.  The
13562 ** size returned omits the 8-byte header overhead.  This only
13563 ** works for chunks that are currently checked out.
13564 */
13565 static int memsys3Size(void *p){
13566   Mem3Block *pBlock;
13567   if( p==0 ) return 0;
13568   pBlock = (Mem3Block*)p;
13569   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
13570   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
13571 }
13572
13573 /*
13574 ** Round up a request size to the next valid allocation size.
13575 */
13576 static int memsys3Roundup(int n){
13577   if( n<=12 ){
13578     return 12;
13579   }else{
13580     return ((n+11)&~7) - 4;
13581   }
13582 }
13583
13584 /*
13585 ** Allocate nBytes of memory.
13586 */
13587 static void *memsys3Malloc(int nBytes){
13588   sqlite3_int64 *p;
13589   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
13590   memsys3Enter();
13591   p = memsys3MallocUnsafe(nBytes);
13592   memsys3Leave();
13593   return (void*)p; 
13594 }
13595
13596 /*
13597 ** Free memory.
13598 */
13599 void memsys3Free(void *pPrior){
13600   assert( pPrior );
13601   memsys3Enter();
13602   memsys3FreeUnsafe(pPrior);
13603   memsys3Leave();
13604 }
13605
13606 /*
13607 ** Change the size of an existing memory allocation
13608 */
13609 void *memsys3Realloc(void *pPrior, int nBytes){
13610   int nOld;
13611   void *p;
13612   if( pPrior==0 ){
13613     return sqlite3_malloc(nBytes);
13614   }
13615   if( nBytes<=0 ){
13616     sqlite3_free(pPrior);
13617     return 0;
13618   }
13619   nOld = memsys3Size(pPrior);
13620   if( nBytes<=nOld && nBytes>=nOld-128 ){
13621     return pPrior;
13622   }
13623   memsys3Enter();
13624   p = memsys3MallocUnsafe(nBytes);
13625   if( p ){
13626     if( nOld<nBytes ){
13627       memcpy(p, pPrior, nOld);
13628     }else{
13629       memcpy(p, pPrior, nBytes);
13630     }
13631     memsys3FreeUnsafe(pPrior);
13632   }
13633   memsys3Leave();
13634   return p;
13635 }
13636
13637 /*
13638 ** Initialize this module.
13639 */
13640 static int memsys3Init(void *NotUsed){
13641   UNUSED_PARAMETER(NotUsed);
13642   if( !sqlite3GlobalConfig.pHeap ){
13643     return SQLITE_ERROR;
13644   }
13645
13646   /* Store a pointer to the memory block in global structure mem3. */
13647   assert( sizeof(Mem3Block)==8 );
13648   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
13649   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
13650
13651   /* Initialize the master block. */
13652   mem3.szMaster = mem3.nPool;
13653   mem3.mnMaster = mem3.szMaster;
13654   mem3.iMaster = 1;
13655   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
13656   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
13657   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
13658
13659   return SQLITE_OK;
13660 }
13661
13662 /*
13663 ** Deinitialize this module.
13664 */
13665 static void memsys3Shutdown(void *NotUsed){
13666   UNUSED_PARAMETER(NotUsed);
13667   mem3.mutex = 0;
13668   return;
13669 }
13670
13671
13672
13673 /*
13674 ** Open the file indicated and write a log of all unfreed memory 
13675 ** allocations into that log.
13676 */
13677 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
13678 #ifdef SQLITE_DEBUG
13679   FILE *out;
13680   u32 i, j;
13681   u32 size;
13682   if( zFilename==0 || zFilename[0]==0 ){
13683     out = stdout;
13684   }else{
13685     out = fopen(zFilename, "w");
13686     if( out==0 ){
13687       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13688                       zFilename);
13689       return;
13690     }
13691   }
13692   memsys3Enter();
13693   fprintf(out, "CHUNKS:\n");
13694   for(i=1; i<=mem3.nPool; i+=size/4){
13695     size = mem3.aPool[i-1].u.hdr.size4x;
13696     if( size/4<=1 ){
13697       fprintf(out, "%p size error\n", &mem3.aPool[i]);
13698       assert( 0 );
13699       break;
13700     }
13701     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
13702       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
13703       assert( 0 );
13704       break;
13705     }
13706     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
13707       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
13708       assert( 0 );
13709       break;
13710     }
13711     if( size&1 ){
13712       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
13713     }else{
13714       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
13715                   i==mem3.iMaster ? " **master**" : "");
13716     }
13717   }
13718   for(i=0; i<MX_SMALL-1; i++){
13719     if( mem3.aiSmall[i]==0 ) continue;
13720     fprintf(out, "small(%2d):", i);
13721     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
13722       fprintf(out, " %p(%d)", &mem3.aPool[j],
13723               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
13724     }
13725     fprintf(out, "\n"); 
13726   }
13727   for(i=0; i<N_HASH; i++){
13728     if( mem3.aiHash[i]==0 ) continue;
13729     fprintf(out, "hash(%2d):", i);
13730     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
13731       fprintf(out, " %p(%d)", &mem3.aPool[j],
13732               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
13733     }
13734     fprintf(out, "\n"); 
13735   }
13736   fprintf(out, "master=%d\n", mem3.iMaster);
13737   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
13738   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
13739   sqlite3_mutex_leave(mem3.mutex);
13740   if( out==stdout ){
13741     fflush(stdout);
13742   }else{
13743     fclose(out);
13744   }
13745 #else
13746   UNUSED_PARAMETER(zFilename);
13747 #endif
13748 }
13749
13750 /*
13751 ** This routine is the only routine in this file with external 
13752 ** linkage.
13753 **
13754 ** Populate the low-level memory allocation function pointers in
13755 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
13756 ** arguments specify the block of memory to manage.
13757 **
13758 ** This routine is only called by sqlite3_config(), and therefore
13759 ** is not required to be threadsafe (it is not).
13760 */
13761 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
13762   static const sqlite3_mem_methods mempoolMethods = {
13763      memsys3Malloc,
13764      memsys3Free,
13765      memsys3Realloc,
13766      memsys3Size,
13767      memsys3Roundup,
13768      memsys3Init,
13769      memsys3Shutdown,
13770      0
13771   };
13772   return &mempoolMethods;
13773 }
13774
13775 #endif /* SQLITE_ENABLE_MEMSYS3 */
13776
13777 /************** End of mem3.c ************************************************/
13778 /************** Begin file mem5.c ********************************************/
13779 /*
13780 ** 2007 October 14
13781 **
13782 ** The author disclaims copyright to this source code.  In place of
13783 ** a legal notice, here is a blessing:
13784 **
13785 **    May you do good and not evil.
13786 **    May you find forgiveness for yourself and forgive others.
13787 **    May you share freely, never taking more than you give.
13788 **
13789 *************************************************************************
13790 ** This file contains the C functions that implement a memory
13791 ** allocation subsystem for use by SQLite. 
13792 **
13793 ** This version of the memory allocation subsystem omits all
13794 ** use of malloc(). The application gives SQLite a block of memory
13795 ** before calling sqlite3_initialize() from which allocations
13796 ** are made and returned by the xMalloc() and xRealloc() 
13797 ** implementations. Once sqlite3_initialize() has been called,
13798 ** the amount of memory available to SQLite is fixed and cannot
13799 ** be changed.
13800 **
13801 ** This version of the memory allocation subsystem is included
13802 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
13803 **
13804 ** This memory allocator uses the following algorithm:
13805 **
13806 **   1.  All memory allocations sizes are rounded up to a power of 2.
13807 **
13808 **   2.  If two adjacent free blocks are the halves of a larger block,
13809 **       then the two blocks are coalesed into the single larger block.
13810 **
13811 **   3.  New memory is allocated from the first available free block.
13812 **
13813 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
13814 ** Concerning Dynamic Storage Allocation". Journal of the Association for
13815 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
13816 ** 
13817 ** Let n be the size of the largest allocation divided by the minimum
13818 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
13819 ** be the maximum amount of memory ever outstanding at one time.  Let
13820 ** N be the total amount of memory available for allocation.  Robson
13821 ** proved that this memory allocator will never breakdown due to 
13822 ** fragmentation as long as the following constraint holds:
13823 **
13824 **      N >=  M*(1 + log2(n)/2) - n + 1
13825 **
13826 ** The sqlite3_status() logic tracks the maximum values of n and M so
13827 ** that an application can, at any time, verify this constraint.
13828 */
13829
13830 /*
13831 ** This version of the memory allocator is used only when 
13832 ** SQLITE_ENABLE_MEMSYS5 is defined.
13833 */
13834 #ifdef SQLITE_ENABLE_MEMSYS5
13835
13836 /*
13837 ** A minimum allocation is an instance of the following structure.
13838 ** Larger allocations are an array of these structures where the
13839 ** size of the array is a power of 2.
13840 **
13841 ** The size of this object must be a power of two.  That fact is
13842 ** verified in memsys5Init().
13843 */
13844 typedef struct Mem5Link Mem5Link;
13845 struct Mem5Link {
13846   int next;       /* Index of next free chunk */
13847   int prev;       /* Index of previous free chunk */
13848 };
13849
13850 /*
13851 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
13852 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
13853 ** it is not actually possible to reach this limit.
13854 */
13855 #define LOGMAX 30
13856
13857 /*
13858 ** Masks used for mem5.aCtrl[] elements.
13859 */
13860 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
13861 #define CTRL_FREE     0x20    /* True if not checked out */
13862
13863 /*
13864 ** All of the static variables used by this module are collected
13865 ** into a single structure named "mem5".  This is to keep the
13866 ** static variables organized and to reduce namespace pollution
13867 ** when this module is combined with other in the amalgamation.
13868 */
13869 static SQLITE_WSD struct Mem5Global {
13870   /*
13871   ** Memory available for allocation
13872   */
13873   int szAtom;      /* Smallest possible allocation in bytes */
13874   int nBlock;      /* Number of szAtom sized blocks in zPool */
13875   u8 *zPool;       /* Memory available to be allocated */
13876   
13877   /*
13878   ** Mutex to control access to the memory allocation subsystem.
13879   */
13880   sqlite3_mutex *mutex;
13881
13882   /*
13883   ** Performance statistics
13884   */
13885   u64 nAlloc;         /* Total number of calls to malloc */
13886   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
13887   u64 totalExcess;    /* Total internal fragmentation */
13888   u32 currentOut;     /* Current checkout, including internal fragmentation */
13889   u32 currentCount;   /* Current number of distinct checkouts */
13890   u32 maxOut;         /* Maximum instantaneous currentOut */
13891   u32 maxCount;       /* Maximum instantaneous currentCount */
13892   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
13893   
13894   /*
13895   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
13896   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
13897   ** and so forth.
13898   */
13899   int aiFreelist[LOGMAX+1];
13900
13901   /*
13902   ** Space for tracking which blocks are checked out and the size
13903   ** of each block.  One byte per block.
13904   */
13905   u8 *aCtrl;
13906
13907 } mem5 = { 0 };
13908
13909 /*
13910 ** Access the static variable through a macro for SQLITE_OMIT_WSD
13911 */
13912 #define mem5 GLOBAL(struct Mem5Global, mem5)
13913
13914 /*
13915 ** Assuming mem5.zPool is divided up into an array of Mem5Link
13916 ** structures, return a pointer to the idx-th such lik.
13917 */
13918 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
13919
13920 /*
13921 ** Unlink the chunk at mem5.aPool[i] from list it is currently
13922 ** on.  It should be found on mem5.aiFreelist[iLogsize].
13923 */
13924 static void memsys5Unlink(int i, int iLogsize){
13925   int next, prev;
13926   assert( i>=0 && i<mem5.nBlock );
13927   assert( iLogsize>=0 && iLogsize<=LOGMAX );
13928   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
13929
13930   next = MEM5LINK(i)->next;
13931   prev = MEM5LINK(i)->prev;
13932   if( prev<0 ){
13933     mem5.aiFreelist[iLogsize] = next;
13934   }else{
13935     MEM5LINK(prev)->next = next;
13936   }
13937   if( next>=0 ){
13938     MEM5LINK(next)->prev = prev;
13939   }
13940 }
13941
13942 /*
13943 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
13944 ** free list.
13945 */
13946 static void memsys5Link(int i, int iLogsize){
13947   int x;
13948   assert( sqlite3_mutex_held(mem5.mutex) );
13949   assert( i>=0 && i<mem5.nBlock );
13950   assert( iLogsize>=0 && iLogsize<=LOGMAX );
13951   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
13952
13953   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
13954   MEM5LINK(i)->prev = -1;
13955   if( x>=0 ){
13956     assert( x<mem5.nBlock );
13957     MEM5LINK(x)->prev = i;
13958   }
13959   mem5.aiFreelist[iLogsize] = i;
13960 }
13961
13962 /*
13963 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13964 ** will already be held (obtained by code in malloc.c) if
13965 ** sqlite3GlobalConfig.bMemStat is true.
13966 */
13967 static void memsys5Enter(void){
13968   sqlite3_mutex_enter(mem5.mutex);
13969 }
13970 static void memsys5Leave(void){
13971   sqlite3_mutex_leave(mem5.mutex);
13972 }
13973
13974 /*
13975 ** Return the size of an outstanding allocation, in bytes.  The
13976 ** size returned omits the 8-byte header overhead.  This only
13977 ** works for chunks that are currently checked out.
13978 */
13979 static int memsys5Size(void *p){
13980   int iSize = 0;
13981   if( p ){
13982     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
13983     assert( i>=0 && i<mem5.nBlock );
13984     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
13985   }
13986   return iSize;
13987 }
13988
13989 /*
13990 ** Find the first entry on the freelist iLogsize.  Unlink that
13991 ** entry and return its index. 
13992 */
13993 static int memsys5UnlinkFirst(int iLogsize){
13994   int i;
13995   int iFirst;
13996
13997   assert( iLogsize>=0 && iLogsize<=LOGMAX );
13998   i = iFirst = mem5.aiFreelist[iLogsize];
13999   assert( iFirst>=0 );
14000   while( i>0 ){
14001     if( i<iFirst ) iFirst = i;
14002     i = MEM5LINK(i)->next;
14003   }
14004   memsys5Unlink(iFirst, iLogsize);
14005   return iFirst;
14006 }
14007
14008 /*
14009 ** Return a block of memory of at least nBytes in size.
14010 ** Return NULL if unable.  Return NULL if nBytes==0.
14011 **
14012 ** The caller guarantees that nByte positive.
14013 **
14014 ** The caller has obtained a mutex prior to invoking this
14015 ** routine so there is never any chance that two or more
14016 ** threads can be in this routine at the same time.
14017 */
14018 static void *memsys5MallocUnsafe(int nByte){
14019   int i;           /* Index of a mem5.aPool[] slot */
14020   int iBin;        /* Index into mem5.aiFreelist[] */
14021   int iFullSz;     /* Size of allocation rounded up to power of 2 */
14022   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
14023
14024   /* nByte must be a positive */
14025   assert( nByte>0 );
14026
14027   /* Keep track of the maximum allocation request.  Even unfulfilled
14028   ** requests are counted */
14029   if( (u32)nByte>mem5.maxRequest ){
14030     mem5.maxRequest = nByte;
14031   }
14032
14033   /* Abort if the requested allocation size is larger than the largest
14034   ** power of two that we can represent using 32-bit signed integers.
14035   */
14036   if( nByte > 0x40000000 ){
14037     return 0;
14038   }
14039
14040   /* Round nByte up to the next valid power of two */
14041   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
14042
14043   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
14044   ** block.  If not, then split a block of the next larger power of
14045   ** two in order to create a new free block of size iLogsize.
14046   */
14047   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
14048   if( iBin>LOGMAX ) return 0;
14049   i = memsys5UnlinkFirst(iBin);
14050   while( iBin>iLogsize ){
14051     int newSize;
14052
14053     iBin--;
14054     newSize = 1 << iBin;
14055     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
14056     memsys5Link(i+newSize, iBin);
14057   }
14058   mem5.aCtrl[i] = iLogsize;
14059
14060   /* Update allocator performance statistics. */
14061   mem5.nAlloc++;
14062   mem5.totalAlloc += iFullSz;
14063   mem5.totalExcess += iFullSz - nByte;
14064   mem5.currentCount++;
14065   mem5.currentOut += iFullSz;
14066   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
14067   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
14068
14069   /* Return a pointer to the allocated memory. */
14070   return (void*)&mem5.zPool[i*mem5.szAtom];
14071 }
14072
14073 /*
14074 ** Free an outstanding memory allocation.
14075 */
14076 static void memsys5FreeUnsafe(void *pOld){
14077   u32 size, iLogsize;
14078   int iBlock;
14079
14080   /* Set iBlock to the index of the block pointed to by pOld in 
14081   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
14082   */
14083   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
14084
14085   /* Check that the pointer pOld points to a valid, non-free block. */
14086   assert( iBlock>=0 && iBlock<mem5.nBlock );
14087   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
14088   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
14089
14090   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
14091   size = 1<<iLogsize;
14092   assert( iBlock+size-1<(u32)mem5.nBlock );
14093
14094   mem5.aCtrl[iBlock] |= CTRL_FREE;
14095   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
14096   assert( mem5.currentCount>0 );
14097   assert( mem5.currentOut>=(size*mem5.szAtom) );
14098   mem5.currentCount--;
14099   mem5.currentOut -= size*mem5.szAtom;
14100   assert( mem5.currentOut>0 || mem5.currentCount==0 );
14101   assert( mem5.currentCount>0 || mem5.currentOut==0 );
14102
14103   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14104   while( ALWAYS(iLogsize<LOGMAX) ){
14105     int iBuddy;
14106     if( (iBlock>>iLogsize) & 1 ){
14107       iBuddy = iBlock - size;
14108     }else{
14109       iBuddy = iBlock + size;
14110     }
14111     assert( iBuddy>=0 );
14112     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
14113     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
14114     memsys5Unlink(iBuddy, iLogsize);
14115     iLogsize++;
14116     if( iBuddy<iBlock ){
14117       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
14118       mem5.aCtrl[iBlock] = 0;
14119       iBlock = iBuddy;
14120     }else{
14121       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14122       mem5.aCtrl[iBuddy] = 0;
14123     }
14124     size *= 2;
14125   }
14126   memsys5Link(iBlock, iLogsize);
14127 }
14128
14129 /*
14130 ** Allocate nBytes of memory
14131 */
14132 static void *memsys5Malloc(int nBytes){
14133   sqlite3_int64 *p = 0;
14134   if( nBytes>0 ){
14135     memsys5Enter();
14136     p = memsys5MallocUnsafe(nBytes);
14137     memsys5Leave();
14138   }
14139   return (void*)p; 
14140 }
14141
14142 /*
14143 ** Free memory.
14144 **
14145 ** The outer layer memory allocator prevents this routine from
14146 ** being called with pPrior==0.
14147 */
14148 static void memsys5Free(void *pPrior){
14149   assert( pPrior!=0 );
14150   memsys5Enter();
14151   memsys5FreeUnsafe(pPrior);
14152   memsys5Leave();  
14153 }
14154
14155 /*
14156 ** Change the size of an existing memory allocation.
14157 **
14158 ** The outer layer memory allocator prevents this routine from
14159 ** being called with pPrior==0.  
14160 **
14161 ** nBytes is always a value obtained from a prior call to
14162 ** memsys5Round().  Hence nBytes is always a non-negative power
14163 ** of two.  If nBytes==0 that means that an oversize allocation
14164 ** (an allocation larger than 0x40000000) was requested and this
14165 ** routine should return 0 without freeing pPrior.
14166 */
14167 static void *memsys5Realloc(void *pPrior, int nBytes){
14168   int nOld;
14169   void *p;
14170   assert( pPrior!=0 );
14171   assert( (nBytes&(nBytes-1))==0 );
14172   assert( nBytes>=0 );
14173   if( nBytes==0 ){
14174     return 0;
14175   }
14176   nOld = memsys5Size(pPrior);
14177   if( nBytes<=nOld ){
14178     return pPrior;
14179   }
14180   memsys5Enter();
14181   p = memsys5MallocUnsafe(nBytes);
14182   if( p ){
14183     memcpy(p, pPrior, nOld);
14184     memsys5FreeUnsafe(pPrior);
14185   }
14186   memsys5Leave();
14187   return p;
14188 }
14189
14190 /*
14191 ** Round up a request size to the next valid allocation size.  If
14192 ** the allocation is too large to be handled by this allocation system,
14193 ** return 0.
14194 **
14195 ** All allocations must be a power of two and must be expressed by a
14196 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
14197 ** or 1073741824 bytes.
14198 */
14199 static int memsys5Roundup(int n){
14200   int iFullSz;
14201   if( n > 0x40000000 ) return 0;
14202   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
14203   return iFullSz;
14204 }
14205
14206 /*
14207 ** Return the ceiling of the logarithm base 2 of iValue.
14208 **
14209 ** Examples:   memsys5Log(1) -> 0
14210 **             memsys5Log(2) -> 1
14211 **             memsys5Log(4) -> 2
14212 **             memsys5Log(5) -> 3
14213 **             memsys5Log(8) -> 3
14214 **             memsys5Log(9) -> 4
14215 */
14216 static int memsys5Log(int iValue){
14217   int iLog;
14218   for(iLog=0; (1<<iLog)<iValue; iLog++);
14219   return iLog;
14220 }
14221
14222 /*
14223 ** Initialize the memory allocator.
14224 **
14225 ** This routine is not threadsafe.  The caller must be holding a mutex
14226 ** to prevent multiple threads from entering at the same time.
14227 */
14228 static int memsys5Init(void *NotUsed){
14229   int ii;            /* Loop counter */
14230   int nByte;         /* Number of bytes of memory available to this allocator */
14231   u8 *zByte;         /* Memory usable by this allocator */
14232   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
14233   int iOffset;       /* An offset into mem5.aCtrl[] */
14234
14235   UNUSED_PARAMETER(NotUsed);
14236
14237   /* For the purposes of this routine, disable the mutex */
14238   mem5.mutex = 0;
14239
14240   /* The size of a Mem5Link object must be a power of two.  Verify that
14241   ** this is case.
14242   */
14243   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
14244
14245   nByte = sqlite3GlobalConfig.nHeap;
14246   zByte = (u8*)sqlite3GlobalConfig.pHeap;
14247   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
14248
14249   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
14250   mem5.szAtom = (1<<nMinLog);
14251   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
14252     mem5.szAtom = mem5.szAtom << 1;
14253   }
14254
14255   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
14256   mem5.zPool = zByte;
14257   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
14258
14259   for(ii=0; ii<=LOGMAX; ii++){
14260     mem5.aiFreelist[ii] = -1;
14261   }
14262
14263   iOffset = 0;
14264   for(ii=LOGMAX; ii>=0; ii--){
14265     int nAlloc = (1<<ii);
14266     if( (iOffset+nAlloc)<=mem5.nBlock ){
14267       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
14268       memsys5Link(iOffset, ii);
14269       iOffset += nAlloc;
14270     }
14271     assert((iOffset+nAlloc)>mem5.nBlock);
14272   }
14273
14274   /* If a mutex is required for normal operation, allocate one */
14275   if( sqlite3GlobalConfig.bMemstat==0 ){
14276     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14277   }
14278
14279   return SQLITE_OK;
14280 }
14281
14282 /*
14283 ** Deinitialize this module.
14284 */
14285 static void memsys5Shutdown(void *NotUsed){
14286   UNUSED_PARAMETER(NotUsed);
14287   mem5.mutex = 0;
14288   return;
14289 }
14290
14291 #ifdef SQLITE_TEST
14292 /*
14293 ** Open the file indicated and write a log of all unfreed memory 
14294 ** allocations into that log.
14295 */
14296 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
14297   FILE *out;
14298   int i, j, n;
14299   int nMinLog;
14300
14301   if( zFilename==0 || zFilename[0]==0 ){
14302     out = stdout;
14303   }else{
14304     out = fopen(zFilename, "w");
14305     if( out==0 ){
14306       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14307                       zFilename);
14308       return;
14309     }
14310   }
14311   memsys5Enter();
14312   nMinLog = memsys5Log(mem5.szAtom);
14313   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
14314     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
14315     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
14316   }
14317   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
14318   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
14319   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
14320   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
14321   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
14322   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
14323   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
14324   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
14325   memsys5Leave();
14326   if( out==stdout ){
14327     fflush(stdout);
14328   }else{
14329     fclose(out);
14330   }
14331 }
14332 #endif
14333
14334 /*
14335 ** This routine is the only routine in this file with external 
14336 ** linkage. It returns a pointer to a static sqlite3_mem_methods
14337 ** struct populated with the memsys5 methods.
14338 */
14339 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
14340   static const sqlite3_mem_methods memsys5Methods = {
14341      memsys5Malloc,
14342      memsys5Free,
14343      memsys5Realloc,
14344      memsys5Size,
14345      memsys5Roundup,
14346      memsys5Init,
14347      memsys5Shutdown,
14348      0
14349   };
14350   return &memsys5Methods;
14351 }
14352
14353 #endif /* SQLITE_ENABLE_MEMSYS5 */
14354
14355 /************** End of mem5.c ************************************************/
14356 /************** Begin file mutex.c *******************************************/
14357 /*
14358 ** 2007 August 14
14359 **
14360 ** The author disclaims copyright to this source code.  In place of
14361 ** a legal notice, here is a blessing:
14362 **
14363 **    May you do good and not evil.
14364 **    May you find forgiveness for yourself and forgive others.
14365 **    May you share freely, never taking more than you give.
14366 **
14367 *************************************************************************
14368 ** This file contains the C functions that implement mutexes.
14369 **
14370 ** This file contains code that is common across all mutex implementations.
14371 */
14372
14373 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
14374 /*
14375 ** For debugging purposes, record when the mutex subsystem is initialized
14376 ** and uninitialized so that we can assert() if there is an attempt to
14377 ** allocate a mutex while the system is uninitialized.
14378 */
14379 static SQLITE_WSD int mutexIsInit = 0;
14380 #endif /* SQLITE_DEBUG */
14381
14382
14383 #ifndef SQLITE_MUTEX_OMIT
14384 /*
14385 ** Initialize the mutex system.
14386 */
14387 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
14388   int rc = SQLITE_OK;
14389   if( sqlite3GlobalConfig.bCoreMutex ){
14390     if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
14391       /* If the xMutexAlloc method has not been set, then the user did not
14392       ** install a mutex implementation via sqlite3_config() prior to 
14393       ** sqlite3_initialize() being called. This block copies pointers to
14394       ** the default implementation into the sqlite3GlobalConfig structure.
14395       */
14396       sqlite3_mutex_methods *pFrom = sqlite3DefaultMutex();
14397       sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
14398
14399       memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
14400       memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
14401              sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
14402       pTo->xMutexAlloc = pFrom->xMutexAlloc;
14403     }
14404     rc = sqlite3GlobalConfig.mutex.xMutexInit();
14405   }
14406
14407 #ifdef SQLITE_DEBUG
14408   GLOBAL(int, mutexIsInit) = 1;
14409 #endif
14410
14411   return rc;
14412 }
14413
14414 /*
14415 ** Shutdown the mutex system. This call frees resources allocated by
14416 ** sqlite3MutexInit().
14417 */
14418 SQLITE_PRIVATE int sqlite3MutexEnd(void){
14419   int rc = SQLITE_OK;
14420   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
14421     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
14422   }
14423
14424 #ifdef SQLITE_DEBUG
14425   GLOBAL(int, mutexIsInit) = 0;
14426 #endif
14427
14428   return rc;
14429 }
14430
14431 /*
14432 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
14433 */
14434 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
14435 #ifndef SQLITE_OMIT_AUTOINIT
14436   if( sqlite3_initialize() ) return 0;
14437 #endif
14438   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14439 }
14440
14441 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
14442   if( !sqlite3GlobalConfig.bCoreMutex ){
14443     return 0;
14444   }
14445   assert( GLOBAL(int, mutexIsInit) );
14446   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14447 }
14448
14449 /*
14450 ** Free a dynamic mutex.
14451 */
14452 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
14453   if( p ){
14454     sqlite3GlobalConfig.mutex.xMutexFree(p);
14455   }
14456 }
14457
14458 /*
14459 ** Obtain the mutex p. If some other thread already has the mutex, block
14460 ** until it can be obtained.
14461 */
14462 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
14463   if( p ){
14464     sqlite3GlobalConfig.mutex.xMutexEnter(p);
14465   }
14466 }
14467
14468 /*
14469 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
14470 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
14471 */
14472 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
14473   int rc = SQLITE_OK;
14474   if( p ){
14475     return sqlite3GlobalConfig.mutex.xMutexTry(p);
14476   }
14477   return rc;
14478 }
14479
14480 /*
14481 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
14482 ** entered by the same thread.  The behavior is undefined if the mutex 
14483 ** is not currently entered. If a NULL pointer is passed as an argument
14484 ** this function is a no-op.
14485 */
14486 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
14487   if( p ){
14488     sqlite3GlobalConfig.mutex.xMutexLeave(p);
14489   }
14490 }
14491
14492 #ifndef NDEBUG
14493 /*
14494 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14495 ** intended for use inside assert() statements.
14496 */
14497 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
14498   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
14499 }
14500 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
14501   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
14502 }
14503 #endif
14504
14505 #endif /* SQLITE_MUTEX_OMIT */
14506
14507 /************** End of mutex.c ***********************************************/
14508 /************** Begin file mutex_noop.c **************************************/
14509 /*
14510 ** 2008 October 07
14511 **
14512 ** The author disclaims copyright to this source code.  In place of
14513 ** a legal notice, here is a blessing:
14514 **
14515 **    May you do good and not evil.
14516 **    May you find forgiveness for yourself and forgive others.
14517 **    May you share freely, never taking more than you give.
14518 **
14519 *************************************************************************
14520 ** This file contains the C functions that implement mutexes.
14521 **
14522 ** This implementation in this file does not provide any mutual
14523 ** exclusion and is thus suitable for use only in applications
14524 ** that use SQLite in a single thread.  The routines defined
14525 ** here are place-holders.  Applications can substitute working
14526 ** mutex routines at start-time using the
14527 **
14528 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
14529 **
14530 ** interface.
14531 **
14532 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
14533 ** that does error checking on mutexes to make sure they are being
14534 ** called correctly.
14535 */
14536
14537
14538 #if defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG)
14539 /*
14540 ** Stub routines for all mutex methods.
14541 **
14542 ** This routines provide no mutual exclusion or error checking.
14543 */
14544 static int noopMutexHeld(sqlite3_mutex *p){ return 1; }
14545 static int noopMutexNotheld(sqlite3_mutex *p){ return 1; }
14546 static int noopMutexInit(void){ return SQLITE_OK; }
14547 static int noopMutexEnd(void){ return SQLITE_OK; }
14548 static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; }
14549 static void noopMutexFree(sqlite3_mutex *p){ return; }
14550 static void noopMutexEnter(sqlite3_mutex *p){ return; }
14551 static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; }
14552 static void noopMutexLeave(sqlite3_mutex *p){ return; }
14553
14554 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14555   static sqlite3_mutex_methods sMutex = {
14556     noopMutexInit,
14557     noopMutexEnd,
14558     noopMutexAlloc,
14559     noopMutexFree,
14560     noopMutexEnter,
14561     noopMutexTry,
14562     noopMutexLeave,
14563
14564     noopMutexHeld,
14565     noopMutexNotheld
14566   };
14567
14568   return &sMutex;
14569 }
14570 #endif /* defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG) */
14571
14572 #if defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG)
14573 /*
14574 ** In this implementation, error checking is provided for testing
14575 ** and debugging purposes.  The mutexes still do not provide any
14576 ** mutual exclusion.
14577 */
14578
14579 /*
14580 ** The mutex object
14581 */
14582 struct sqlite3_mutex {
14583   int id;     /* The mutex type */
14584   int cnt;    /* Number of entries without a matching leave */
14585 };
14586
14587 /*
14588 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14589 ** intended for use inside assert() statements.
14590 */
14591 static int debugMutexHeld(sqlite3_mutex *p){
14592   return p==0 || p->cnt>0;
14593 }
14594 static int debugMutexNotheld(sqlite3_mutex *p){
14595   return p==0 || p->cnt==0;
14596 }
14597
14598 /*
14599 ** Initialize and deinitialize the mutex subsystem.
14600 */
14601 static int debugMutexInit(void){ return SQLITE_OK; }
14602 static int debugMutexEnd(void){ return SQLITE_OK; }
14603
14604 /*
14605 ** The sqlite3_mutex_alloc() routine allocates a new
14606 ** mutex and returns a pointer to it.  If it returns NULL
14607 ** that means that a mutex could not be allocated. 
14608 */
14609 static sqlite3_mutex *debugMutexAlloc(int id){
14610   static sqlite3_mutex aStatic[6];
14611   sqlite3_mutex *pNew = 0;
14612   switch( id ){
14613     case SQLITE_MUTEX_FAST:
14614     case SQLITE_MUTEX_RECURSIVE: {
14615       pNew = sqlite3Malloc(sizeof(*pNew));
14616       if( pNew ){
14617         pNew->id = id;
14618         pNew->cnt = 0;
14619       }
14620       break;
14621     }
14622     default: {
14623       assert( id-2 >= 0 );
14624       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
14625       pNew = &aStatic[id-2];
14626       pNew->id = id;
14627       break;
14628     }
14629   }
14630   return pNew;
14631 }
14632
14633 /*
14634 ** This routine deallocates a previously allocated mutex.
14635 */
14636 static void debugMutexFree(sqlite3_mutex *p){
14637   assert( p->cnt==0 );
14638   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
14639   sqlite3_free(p);
14640 }
14641
14642 /*
14643 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
14644 ** to enter a mutex.  If another thread is already within the mutex,
14645 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
14646 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
14647 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
14648 ** be entered multiple times by the same thread.  In such cases the,
14649 ** mutex must be exited an equal number of times before another thread
14650 ** can enter.  If the same thread tries to enter any other kind of mutex
14651 ** more than once, the behavior is undefined.
14652 */
14653 static void debugMutexEnter(sqlite3_mutex *p){
14654   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14655   p->cnt++;
14656 }
14657 static int debugMutexTry(sqlite3_mutex *p){
14658   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14659   p->cnt++;
14660   return SQLITE_OK;
14661 }
14662
14663 /*
14664 ** The sqlite3_mutex_leave() routine exits a mutex that was
14665 ** previously entered by the same thread.  The behavior
14666 ** is undefined if the mutex is not currently entered or
14667 ** is not currently allocated.  SQLite will never do either.
14668 */
14669 static void debugMutexLeave(sqlite3_mutex *p){
14670   assert( debugMutexHeld(p) );
14671   p->cnt--;
14672   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14673 }
14674
14675 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14676   static sqlite3_mutex_methods sMutex = {
14677     debugMutexInit,
14678     debugMutexEnd,
14679     debugMutexAlloc,
14680     debugMutexFree,
14681     debugMutexEnter,
14682     debugMutexTry,
14683     debugMutexLeave,
14684
14685     debugMutexHeld,
14686     debugMutexNotheld
14687   };
14688
14689   return &sMutex;
14690 }
14691 #endif /* defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG) */
14692
14693 /************** End of mutex_noop.c ******************************************/
14694 /************** Begin file mutex_os2.c ***************************************/
14695 /*
14696 ** 2007 August 28
14697 **
14698 ** The author disclaims copyright to this source code.  In place of
14699 ** a legal notice, here is a blessing:
14700 **
14701 **    May you do good and not evil.
14702 **    May you find forgiveness for yourself and forgive others.
14703 **    May you share freely, never taking more than you give.
14704 **
14705 *************************************************************************
14706 ** This file contains the C functions that implement mutexes for OS/2
14707 */
14708
14709 /*
14710 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
14711 ** See the mutex.h file for details.
14712 */
14713 #ifdef SQLITE_MUTEX_OS2
14714
14715 /********************** OS/2 Mutex Implementation **********************
14716 **
14717 ** This implementation of mutexes is built using the OS/2 API.
14718 */
14719
14720 /*
14721 ** The mutex object
14722 ** Each recursive mutex is an instance of the following structure.
14723 */
14724 struct sqlite3_mutex {
14725   HMTX mutex;       /* Mutex controlling the lock */
14726   int  id;          /* Mutex type */
14727   int  nRef;        /* Number of references */
14728   TID  owner;       /* Thread holding this mutex */
14729 };
14730
14731 #define OS2_MUTEX_INITIALIZER   0,0,0,0
14732
14733 /*
14734 ** Initialize and deinitialize the mutex subsystem.
14735 */
14736 static int os2MutexInit(void){ return SQLITE_OK; }
14737 static int os2MutexEnd(void){ return SQLITE_OK; }
14738
14739 /*
14740 ** The sqlite3_mutex_alloc() routine allocates a new
14741 ** mutex and returns a pointer to it.  If it returns NULL
14742 ** that means that a mutex could not be allocated. 
14743 ** SQLite will unwind its stack and return an error.  The argument
14744 ** to sqlite3_mutex_alloc() is one of these integer constants:
14745 **
14746 ** <ul>
14747 ** <li>  SQLITE_MUTEX_FAST               0
14748 ** <li>  SQLITE_MUTEX_RECURSIVE          1
14749 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
14750 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
14751 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
14752 ** </ul>
14753 **
14754 ** The first two constants cause sqlite3_mutex_alloc() to create
14755 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
14756 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
14757 ** The mutex implementation does not need to make a distinction
14758 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
14759 ** not want to.  But SQLite will only request a recursive mutex in
14760 ** cases where it really needs one.  If a faster non-recursive mutex
14761 ** implementation is available on the host platform, the mutex subsystem
14762 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
14763 **
14764 ** The other allowed parameters to sqlite3_mutex_alloc() each return
14765 ** a pointer to a static preexisting mutex.  Three static mutexes are
14766 ** used by the current version of SQLite.  Future versions of SQLite
14767 ** may add additional static mutexes.  Static mutexes are for internal
14768 ** use by SQLite only.  Applications that use SQLite mutexes should
14769 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
14770 ** SQLITE_MUTEX_RECURSIVE.
14771 **
14772 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
14773 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
14774 ** returns a different mutex on every call.  But for the static
14775 ** mutex types, the same mutex is returned on every call that has
14776 ** the same type number.
14777 */
14778 static sqlite3_mutex *os2MutexAlloc(int iType){
14779   sqlite3_mutex *p = NULL;
14780   switch( iType ){
14781     case SQLITE_MUTEX_FAST:
14782     case SQLITE_MUTEX_RECURSIVE: {
14783       p = sqlite3MallocZero( sizeof(*p) );
14784       if( p ){
14785         p->id = iType;
14786         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
14787           sqlite3_free( p );
14788           p = NULL;
14789         }
14790       }
14791       break;
14792     }
14793     default: {
14794       static volatile int isInit = 0;
14795       static sqlite3_mutex staticMutexes[] = {
14796         { OS2_MUTEX_INITIALIZER, },
14797         { OS2_MUTEX_INITIALIZER, },
14798         { OS2_MUTEX_INITIALIZER, },
14799         { OS2_MUTEX_INITIALIZER, },
14800         { OS2_MUTEX_INITIALIZER, },
14801         { OS2_MUTEX_INITIALIZER, },
14802       };
14803       if ( !isInit ){
14804         APIRET rc;
14805         PTIB ptib;
14806         PPIB ppib;
14807         HMTX mutex;
14808         char name[32];
14809         DosGetInfoBlocks( &ptib, &ppib );
14810         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
14811                           ppib->pib_ulpid );
14812         while( !isInit ){
14813           mutex = 0;
14814           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
14815           if( rc == NO_ERROR ){
14816             unsigned int i;
14817             if( !isInit ){
14818               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
14819                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
14820               }
14821               isInit = 1;
14822             }
14823             DosCloseMutexSem( mutex );
14824           }else if( rc == ERROR_DUPLICATE_NAME ){
14825             DosSleep( 1 );
14826           }else{
14827             return p;
14828           }
14829         }
14830       }
14831       assert( iType-2 >= 0 );
14832       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
14833       p = &staticMutexes[iType-2];
14834       p->id = iType;
14835       break;
14836     }
14837   }
14838   return p;
14839 }
14840
14841
14842 /*
14843 ** This routine deallocates a previously allocated mutex.
14844 ** SQLite is careful to deallocate every mutex that it allocates.
14845 */
14846 static void os2MutexFree(sqlite3_mutex *p){
14847   if( p==0 ) return;
14848   assert( p->nRef==0 );
14849   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
14850   DosCloseMutexSem( p->mutex );
14851   sqlite3_free( p );
14852 }
14853
14854 #ifdef SQLITE_DEBUG
14855 /*
14856 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14857 ** intended for use inside assert() statements.
14858 */
14859 static int os2MutexHeld(sqlite3_mutex *p){
14860   TID tid;
14861   PID pid;
14862   ULONG ulCount;
14863   PTIB ptib;
14864   if( p!=0 ) {
14865     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
14866   } else {
14867     DosGetInfoBlocks(&ptib, NULL);
14868     tid = ptib->tib_ptib2->tib2_ultid;
14869   }
14870   return p==0 || (p->nRef!=0 && p->owner==tid);
14871 }
14872 static int os2MutexNotheld(sqlite3_mutex *p){
14873   TID tid;
14874   PID pid;
14875   ULONG ulCount;
14876   PTIB ptib;
14877   if( p!= 0 ) {
14878     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
14879   } else {
14880     DosGetInfoBlocks(&ptib, NULL);
14881     tid = ptib->tib_ptib2->tib2_ultid;
14882   }
14883   return p==0 || p->nRef==0 || p->owner!=tid;
14884 }
14885 #endif
14886
14887 /*
14888 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
14889 ** to enter a mutex.  If another thread is already within the mutex,
14890 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
14891 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
14892 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
14893 ** be entered multiple times by the same thread.  In such cases the,
14894 ** mutex must be exited an equal number of times before another thread
14895 ** can enter.  If the same thread tries to enter any other kind of mutex
14896 ** more than once, the behavior is undefined.
14897 */
14898 static void os2MutexEnter(sqlite3_mutex *p){
14899   TID tid;
14900   PID holder1;
14901   ULONG holder2;
14902   if( p==0 ) return;
14903   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
14904   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
14905   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14906   p->owner = tid;
14907   p->nRef++;
14908 }
14909 static int os2MutexTry(sqlite3_mutex *p){
14910   int rc;
14911   TID tid;
14912   PID holder1;
14913   ULONG holder2;
14914   if( p==0 ) return SQLITE_OK;
14915   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
14916   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
14917     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14918     p->owner = tid;
14919     p->nRef++;
14920     rc = SQLITE_OK;
14921   } else {
14922     rc = SQLITE_BUSY;
14923   }
14924
14925   return rc;
14926 }
14927
14928 /*
14929 ** The sqlite3_mutex_leave() routine exits a mutex that was
14930 ** previously entered by the same thread.  The behavior
14931 ** is undefined if the mutex is not currently entered or
14932 ** is not currently allocated.  SQLite will never do either.
14933 */
14934 static void os2MutexLeave(sqlite3_mutex *p){
14935   TID tid;
14936   PID holder1;
14937   ULONG holder2;
14938   if( p==0 ) return;
14939   assert( p->nRef>0 );
14940   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14941   assert( p->owner==tid );
14942   p->nRef--;
14943   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
14944   DosReleaseMutexSem(p->mutex);
14945 }
14946
14947 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14948   static sqlite3_mutex_methods sMutex = {
14949     os2MutexInit,
14950     os2MutexEnd,
14951     os2MutexAlloc,
14952     os2MutexFree,
14953     os2MutexEnter,
14954     os2MutexTry,
14955     os2MutexLeave,
14956 #ifdef SQLITE_DEBUG
14957     os2MutexHeld,
14958     os2MutexNotheld
14959 #endif
14960   };
14961
14962   return &sMutex;
14963 }
14964 #endif /* SQLITE_MUTEX_OS2 */
14965
14966 /************** End of mutex_os2.c *******************************************/
14967 /************** Begin file mutex_unix.c **************************************/
14968 /*
14969 ** 2007 August 28
14970 **
14971 ** The author disclaims copyright to this source code.  In place of
14972 ** a legal notice, here is a blessing:
14973 **
14974 **    May you do good and not evil.
14975 **    May you find forgiveness for yourself and forgive others.
14976 **    May you share freely, never taking more than you give.
14977 **
14978 *************************************************************************
14979 ** This file contains the C functions that implement mutexes for pthreads
14980 */
14981
14982 /*
14983 ** The code in this file is only used if we are compiling threadsafe
14984 ** under unix with pthreads.
14985 **
14986 ** Note that this implementation requires a version of pthreads that
14987 ** supports recursive mutexes.
14988 */
14989 #ifdef SQLITE_MUTEX_PTHREADS
14990
14991 #include <pthread.h>
14992
14993
14994 /*
14995 ** Each recursive mutex is an instance of the following structure.
14996 */
14997 struct sqlite3_mutex {
14998   pthread_mutex_t mutex;     /* Mutex controlling the lock */
14999   int id;                    /* Mutex type */
15000   int nRef;                  /* Number of entrances */
15001   pthread_t owner;           /* Thread that is within this mutex */
15002 #ifdef SQLITE_DEBUG
15003   int trace;                 /* True to trace changes */
15004 #endif
15005 };
15006 #ifdef SQLITE_DEBUG
15007 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
15008 #else
15009 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
15010 #endif
15011
15012 /*
15013 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15014 ** intended for use only inside assert() statements.  On some platforms,
15015 ** there might be race conditions that can cause these routines to
15016 ** deliver incorrect results.  In particular, if pthread_equal() is
15017 ** not an atomic operation, then these routines might delivery
15018 ** incorrect results.  On most platforms, pthread_equal() is a 
15019 ** comparison of two integers and is therefore atomic.  But we are
15020 ** told that HPUX is not such a platform.  If so, then these routines
15021 ** will not always work correctly on HPUX.
15022 **
15023 ** On those platforms where pthread_equal() is not atomic, SQLite
15024 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
15025 ** make sure no assert() statements are evaluated and hence these
15026 ** routines are never called.
15027 */
15028 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
15029 static int pthreadMutexHeld(sqlite3_mutex *p){
15030   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
15031 }
15032 static int pthreadMutexNotheld(sqlite3_mutex *p){
15033   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
15034 }
15035 #endif
15036
15037 /*
15038 ** Initialize and deinitialize the mutex subsystem.
15039 */
15040 static int pthreadMutexInit(void){ return SQLITE_OK; }
15041 static int pthreadMutexEnd(void){ return SQLITE_OK; }
15042
15043 /*
15044 ** The sqlite3_mutex_alloc() routine allocates a new
15045 ** mutex and returns a pointer to it.  If it returns NULL
15046 ** that means that a mutex could not be allocated.  SQLite
15047 ** will unwind its stack and return an error.  The argument
15048 ** to sqlite3_mutex_alloc() is one of these integer constants:
15049 **
15050 ** <ul>
15051 ** <li>  SQLITE_MUTEX_FAST
15052 ** <li>  SQLITE_MUTEX_RECURSIVE
15053 ** <li>  SQLITE_MUTEX_STATIC_MASTER
15054 ** <li>  SQLITE_MUTEX_STATIC_MEM
15055 ** <li>  SQLITE_MUTEX_STATIC_MEM2
15056 ** <li>  SQLITE_MUTEX_STATIC_PRNG
15057 ** <li>  SQLITE_MUTEX_STATIC_LRU
15058 ** <li>  SQLITE_MUTEX_STATIC_LRU2
15059 ** </ul>
15060 **
15061 ** The first two constants cause sqlite3_mutex_alloc() to create
15062 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15063 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15064 ** The mutex implementation does not need to make a distinction
15065 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15066 ** not want to.  But SQLite will only request a recursive mutex in
15067 ** cases where it really needs one.  If a faster non-recursive mutex
15068 ** implementation is available on the host platform, the mutex subsystem
15069 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15070 **
15071 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15072 ** a pointer to a static preexisting mutex.  Six static mutexes are
15073 ** used by the current version of SQLite.  Future versions of SQLite
15074 ** may add additional static mutexes.  Static mutexes are for internal
15075 ** use by SQLite only.  Applications that use SQLite mutexes should
15076 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15077 ** SQLITE_MUTEX_RECURSIVE.
15078 **
15079 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15080 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15081 ** returns a different mutex on every call.  But for the static 
15082 ** mutex types, the same mutex is returned on every call that has
15083 ** the same type number.
15084 */
15085 static sqlite3_mutex *pthreadMutexAlloc(int iType){
15086   static sqlite3_mutex staticMutexes[] = {
15087     SQLITE3_MUTEX_INITIALIZER,
15088     SQLITE3_MUTEX_INITIALIZER,
15089     SQLITE3_MUTEX_INITIALIZER,
15090     SQLITE3_MUTEX_INITIALIZER,
15091     SQLITE3_MUTEX_INITIALIZER,
15092     SQLITE3_MUTEX_INITIALIZER
15093   };
15094   sqlite3_mutex *p;
15095   switch( iType ){
15096     case SQLITE_MUTEX_RECURSIVE: {
15097       p = sqlite3MallocZero( sizeof(*p) );
15098       if( p ){
15099 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15100         /* If recursive mutexes are not available, we will have to
15101         ** build our own.  See below. */
15102         pthread_mutex_init(&p->mutex, 0);
15103 #else
15104         /* Use a recursive mutex if it is available */
15105         pthread_mutexattr_t recursiveAttr;
15106         pthread_mutexattr_init(&recursiveAttr);
15107         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
15108         pthread_mutex_init(&p->mutex, &recursiveAttr);
15109         pthread_mutexattr_destroy(&recursiveAttr);
15110 #endif
15111         p->id = iType;
15112       }
15113       break;
15114     }
15115     case SQLITE_MUTEX_FAST: {
15116       p = sqlite3MallocZero( sizeof(*p) );
15117       if( p ){
15118         p->id = iType;
15119         pthread_mutex_init(&p->mutex, 0);
15120       }
15121       break;
15122     }
15123     default: {
15124       assert( iType-2 >= 0 );
15125       assert( iType-2 < ArraySize(staticMutexes) );
15126       p = &staticMutexes[iType-2];
15127       p->id = iType;
15128       break;
15129     }
15130   }
15131   return p;
15132 }
15133
15134
15135 /*
15136 ** This routine deallocates a previously
15137 ** allocated mutex.  SQLite is careful to deallocate every
15138 ** mutex that it allocates.
15139 */
15140 static void pthreadMutexFree(sqlite3_mutex *p){
15141   assert( p->nRef==0 );
15142   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15143   pthread_mutex_destroy(&p->mutex);
15144   sqlite3_free(p);
15145 }
15146
15147 /*
15148 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15149 ** to enter a mutex.  If another thread is already within the mutex,
15150 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15151 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15152 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15153 ** be entered multiple times by the same thread.  In such cases the,
15154 ** mutex must be exited an equal number of times before another thread
15155 ** can enter.  If the same thread tries to enter any other kind of mutex
15156 ** more than once, the behavior is undefined.
15157 */
15158 static void pthreadMutexEnter(sqlite3_mutex *p){
15159   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15160
15161 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15162   /* If recursive mutexes are not available, then we have to grow
15163   ** our own.  This implementation assumes that pthread_equal()
15164   ** is atomic - that it cannot be deceived into thinking self
15165   ** and p->owner are equal if p->owner changes between two values
15166   ** that are not equal to self while the comparison is taking place.
15167   ** This implementation also assumes a coherent cache - that 
15168   ** separate processes cannot read different values from the same
15169   ** address at the same time.  If either of these two conditions
15170   ** are not met, then the mutexes will fail and problems will result.
15171   */
15172   {
15173     pthread_t self = pthread_self();
15174     if( p->nRef>0 && pthread_equal(p->owner, self) ){
15175       p->nRef++;
15176     }else{
15177       pthread_mutex_lock(&p->mutex);
15178       assert( p->nRef==0 );
15179       p->owner = self;
15180       p->nRef = 1;
15181     }
15182   }
15183 #else
15184   /* Use the built-in recursive mutexes if they are available.
15185   */
15186   pthread_mutex_lock(&p->mutex);
15187   p->owner = pthread_self();
15188   p->nRef++;
15189 #endif
15190
15191 #ifdef SQLITE_DEBUG
15192   if( p->trace ){
15193     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15194   }
15195 #endif
15196 }
15197 static int pthreadMutexTry(sqlite3_mutex *p){
15198   int rc;
15199   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15200
15201 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15202   /* If recursive mutexes are not available, then we have to grow
15203   ** our own.  This implementation assumes that pthread_equal()
15204   ** is atomic - that it cannot be deceived into thinking self
15205   ** and p->owner are equal if p->owner changes between two values
15206   ** that are not equal to self while the comparison is taking place.
15207   ** This implementation also assumes a coherent cache - that 
15208   ** separate processes cannot read different values from the same
15209   ** address at the same time.  If either of these two conditions
15210   ** are not met, then the mutexes will fail and problems will result.
15211   */
15212   {
15213     pthread_t self = pthread_self();
15214     if( p->nRef>0 && pthread_equal(p->owner, self) ){
15215       p->nRef++;
15216       rc = SQLITE_OK;
15217     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
15218       assert( p->nRef==0 );
15219       p->owner = self;
15220       p->nRef = 1;
15221       rc = SQLITE_OK;
15222     }else{
15223       rc = SQLITE_BUSY;
15224     }
15225   }
15226 #else
15227   /* Use the built-in recursive mutexes if they are available.
15228   */
15229   if( pthread_mutex_trylock(&p->mutex)==0 ){
15230     p->owner = pthread_self();
15231     p->nRef++;
15232     rc = SQLITE_OK;
15233   }else{
15234     rc = SQLITE_BUSY;
15235   }
15236 #endif
15237
15238 #ifdef SQLITE_DEBUG
15239   if( rc==SQLITE_OK && p->trace ){
15240     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15241   }
15242 #endif
15243   return rc;
15244 }
15245
15246 /*
15247 ** The sqlite3_mutex_leave() routine exits a mutex that was
15248 ** previously entered by the same thread.  The behavior
15249 ** is undefined if the mutex is not currently entered or
15250 ** is not currently allocated.  SQLite will never do either.
15251 */
15252 static void pthreadMutexLeave(sqlite3_mutex *p){
15253   assert( pthreadMutexHeld(p) );
15254   p->nRef--;
15255   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15256
15257 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15258   if( p->nRef==0 ){
15259     pthread_mutex_unlock(&p->mutex);
15260   }
15261 #else
15262   pthread_mutex_unlock(&p->mutex);
15263 #endif
15264
15265 #ifdef SQLITE_DEBUG
15266   if( p->trace ){
15267     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15268   }
15269 #endif
15270 }
15271
15272 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15273   static sqlite3_mutex_methods sMutex = {
15274     pthreadMutexInit,
15275     pthreadMutexEnd,
15276     pthreadMutexAlloc,
15277     pthreadMutexFree,
15278     pthreadMutexEnter,
15279     pthreadMutexTry,
15280     pthreadMutexLeave,
15281 #ifdef SQLITE_DEBUG
15282     pthreadMutexHeld,
15283     pthreadMutexNotheld
15284 #else
15285     0,
15286     0
15287 #endif
15288   };
15289
15290   return &sMutex;
15291 }
15292
15293 #endif /* SQLITE_MUTEX_PTHREAD */
15294
15295 /************** End of mutex_unix.c ******************************************/
15296 /************** Begin file mutex_w32.c ***************************************/
15297 /*
15298 ** 2007 August 14
15299 **
15300 ** The author disclaims copyright to this source code.  In place of
15301 ** a legal notice, here is a blessing:
15302 **
15303 **    May you do good and not evil.
15304 **    May you find forgiveness for yourself and forgive others.
15305 **    May you share freely, never taking more than you give.
15306 **
15307 *************************************************************************
15308 ** This file contains the C functions that implement mutexes for win32
15309 */
15310
15311 /*
15312 ** The code in this file is only used if we are compiling multithreaded
15313 ** on a win32 system.
15314 */
15315 #ifdef SQLITE_MUTEX_W32
15316
15317 /*
15318 ** Each recursive mutex is an instance of the following structure.
15319 */
15320 struct sqlite3_mutex {
15321   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
15322   int id;                    /* Mutex type */
15323   int nRef;                  /* Number of enterances */
15324   DWORD owner;               /* Thread holding this mutex */
15325 };
15326
15327 /*
15328 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
15329 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
15330 **
15331 ** Here is an interesting observation:  Win95, Win98, and WinME lack
15332 ** the LockFileEx() API.  But we can still statically link against that
15333 ** API as long as we don't call it win running Win95/98/ME.  A call to
15334 ** this routine is used to determine if the host is Win95/98/ME or
15335 ** WinNT/2K/XP so that we will know whether or not we can safely call
15336 ** the LockFileEx() API.
15337 **
15338 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
15339 ** which is only available if your application was compiled with 
15340 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
15341 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
15342 ** this out as well.
15343 */
15344 #if 0
15345 #if SQLITE_OS_WINCE
15346 # define mutexIsNT()  (1)
15347 #else
15348   static int mutexIsNT(void){
15349     static int osType = 0;
15350     if( osType==0 ){
15351       OSVERSIONINFO sInfo;
15352       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
15353       GetVersionEx(&sInfo);
15354       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
15355     }
15356     return osType==2;
15357   }
15358 #endif /* SQLITE_OS_WINCE */
15359 #endif
15360
15361 #ifdef SQLITE_DEBUG
15362 /*
15363 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15364 ** intended for use only inside assert() statements.
15365 */
15366 static int winMutexHeld(sqlite3_mutex *p){
15367   return p->nRef!=0 && p->owner==GetCurrentThreadId();
15368 }
15369 static int winMutexNotheld(sqlite3_mutex *p){
15370   return p->nRef==0 || p->owner!=GetCurrentThreadId();
15371 }
15372 #endif
15373
15374
15375 /*
15376 ** Initialize and deinitialize the mutex subsystem.
15377 */
15378 static sqlite3_mutex winMutex_staticMutexes[6];
15379 static int winMutex_isInit = 0;
15380 /* As winMutexInit() and winMutexEnd() are called as part
15381 ** of the sqlite3_initialize and sqlite3_shutdown()
15382 ** processing, the "interlocked" magic is probably not
15383 ** strictly necessary.
15384 */
15385 static long winMutex_lock = 0;
15386
15387 static int winMutexInit(void){ 
15388   /* The first to increment to 1 does actual initialization */
15389   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
15390     int i;
15391     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
15392       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
15393     }
15394     winMutex_isInit = 1;
15395   }else{
15396     /* Someone else is in the process of initing the static mutexes */
15397     while( !winMutex_isInit ){
15398       Sleep(1);
15399     }
15400   }
15401   return SQLITE_OK; 
15402 }
15403
15404 static int winMutexEnd(void){ 
15405   /* The first to decrement to 0 does actual shutdown 
15406   ** (which should be the last to shutdown.) */
15407   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
15408     if( winMutex_isInit==1 ){
15409       int i;
15410       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
15411         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
15412       }
15413       winMutex_isInit = 0;
15414     }
15415   }
15416   return SQLITE_OK; 
15417 }
15418
15419 /*
15420 ** The sqlite3_mutex_alloc() routine allocates a new
15421 ** mutex and returns a pointer to it.  If it returns NULL
15422 ** that means that a mutex could not be allocated.  SQLite
15423 ** will unwind its stack and return an error.  The argument
15424 ** to sqlite3_mutex_alloc() is one of these integer constants:
15425 **
15426 ** <ul>
15427 ** <li>  SQLITE_MUTEX_FAST
15428 ** <li>  SQLITE_MUTEX_RECURSIVE
15429 ** <li>  SQLITE_MUTEX_STATIC_MASTER
15430 ** <li>  SQLITE_MUTEX_STATIC_MEM
15431 ** <li>  SQLITE_MUTEX_STATIC_MEM2
15432 ** <li>  SQLITE_MUTEX_STATIC_PRNG
15433 ** <li>  SQLITE_MUTEX_STATIC_LRU
15434 ** <li>  SQLITE_MUTEX_STATIC_LRU2
15435 ** </ul>
15436 **
15437 ** The first two constants cause sqlite3_mutex_alloc() to create
15438 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15439 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15440 ** The mutex implementation does not need to make a distinction
15441 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15442 ** not want to.  But SQLite will only request a recursive mutex in
15443 ** cases where it really needs one.  If a faster non-recursive mutex
15444 ** implementation is available on the host platform, the mutex subsystem
15445 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15446 **
15447 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15448 ** a pointer to a static preexisting mutex.  Six static mutexes are
15449 ** used by the current version of SQLite.  Future versions of SQLite
15450 ** may add additional static mutexes.  Static mutexes are for internal
15451 ** use by SQLite only.  Applications that use SQLite mutexes should
15452 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15453 ** SQLITE_MUTEX_RECURSIVE.
15454 **
15455 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15456 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15457 ** returns a different mutex on every call.  But for the static 
15458 ** mutex types, the same mutex is returned on every call that has
15459 ** the same type number.
15460 */
15461 static sqlite3_mutex *winMutexAlloc(int iType){
15462   sqlite3_mutex *p;
15463
15464   switch( iType ){
15465     case SQLITE_MUTEX_FAST:
15466     case SQLITE_MUTEX_RECURSIVE: {
15467       p = sqlite3MallocZero( sizeof(*p) );
15468       if( p ){  
15469         p->id = iType;
15470         InitializeCriticalSection(&p->mutex);
15471       }
15472       break;
15473     }
15474     default: {
15475       assert( winMutex_isInit==1 );
15476       assert( iType-2 >= 0 );
15477       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
15478       p = &winMutex_staticMutexes[iType-2];
15479       p->id = iType;
15480       break;
15481     }
15482   }
15483   return p;
15484 }
15485
15486
15487 /*
15488 ** This routine deallocates a previously
15489 ** allocated mutex.  SQLite is careful to deallocate every
15490 ** mutex that it allocates.
15491 */
15492 static void winMutexFree(sqlite3_mutex *p){
15493   assert( p );
15494   assert( p->nRef==0 );
15495   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15496   DeleteCriticalSection(&p->mutex);
15497   sqlite3_free(p);
15498 }
15499
15500 /*
15501 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15502 ** to enter a mutex.  If another thread is already within the mutex,
15503 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15504 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15505 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15506 ** be entered multiple times by the same thread.  In such cases the,
15507 ** mutex must be exited an equal number of times before another thread
15508 ** can enter.  If the same thread tries to enter any other kind of mutex
15509 ** more than once, the behavior is undefined.
15510 */
15511 static void winMutexEnter(sqlite3_mutex *p){
15512   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15513   EnterCriticalSection(&p->mutex);
15514   p->owner = GetCurrentThreadId(); 
15515   p->nRef++;
15516 }
15517 static int winMutexTry(sqlite3_mutex *p){
15518   int rc = SQLITE_BUSY;
15519   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15520   /*
15521   ** The sqlite3_mutex_try() routine is very rarely used, and when it
15522   ** is used it is merely an optimization.  So it is OK for it to always
15523   ** fail.  
15524   **
15525   ** The TryEnterCriticalSection() interface is only available on WinNT.
15526   ** And some windows compilers complain if you try to use it without
15527   ** first doing some #defines that prevent SQLite from building on Win98.
15528   ** For that reason, we will omit this optimization for now.  See
15529   ** ticket #2685.
15530   */
15531 #if 0
15532   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
15533     p->owner = GetCurrentThreadId();
15534     p->nRef++;
15535     rc = SQLITE_OK;
15536   }
15537 #else
15538   UNUSED_PARAMETER(p);
15539 #endif
15540   return rc;
15541 }
15542
15543 /*
15544 ** The sqlite3_mutex_leave() routine exits a mutex that was
15545 ** previously entered by the same thread.  The behavior
15546 ** is undefined if the mutex is not currently entered or
15547 ** is not currently allocated.  SQLite will never do either.
15548 */
15549 static void winMutexLeave(sqlite3_mutex *p){
15550   assert( p->nRef>0 );
15551   assert( p->owner==GetCurrentThreadId() );
15552   p->nRef--;
15553   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15554   LeaveCriticalSection(&p->mutex);
15555 }
15556
15557 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15558   static sqlite3_mutex_methods sMutex = {
15559     winMutexInit,
15560     winMutexEnd,
15561     winMutexAlloc,
15562     winMutexFree,
15563     winMutexEnter,
15564     winMutexTry,
15565     winMutexLeave,
15566 #ifdef SQLITE_DEBUG
15567     winMutexHeld,
15568     winMutexNotheld
15569 #else
15570     0,
15571     0
15572 #endif
15573   };
15574
15575   return &sMutex;
15576 }
15577 #endif /* SQLITE_MUTEX_W32 */
15578
15579 /************** End of mutex_w32.c *******************************************/
15580 /************** Begin file malloc.c ******************************************/
15581 /*
15582 ** 2001 September 15
15583 **
15584 ** The author disclaims copyright to this source code.  In place of
15585 ** a legal notice, here is a blessing:
15586 **
15587 **    May you do good and not evil.
15588 **    May you find forgiveness for yourself and forgive others.
15589 **    May you share freely, never taking more than you give.
15590 **
15591 *************************************************************************
15592 **
15593 ** Memory allocation functions used throughout sqlite.
15594 */
15595
15596 /*
15597 ** This routine runs when the memory allocator sees that the
15598 ** total memory allocation is about to exceed the soft heap
15599 ** limit.
15600 */
15601 static void softHeapLimitEnforcer(
15602   void *NotUsed, 
15603   sqlite3_int64 NotUsed2,
15604   int allocSize
15605 ){
15606   UNUSED_PARAMETER2(NotUsed, NotUsed2);
15607   sqlite3_release_memory(allocSize);
15608 }
15609
15610 /*
15611 ** Set the soft heap-size limit for the library. Passing a zero or 
15612 ** negative value indicates no limit.
15613 */
15614 SQLITE_API void sqlite3_soft_heap_limit(int n){
15615   sqlite3_uint64 iLimit;
15616   int overage;
15617   if( n<0 ){
15618     iLimit = 0;
15619   }else{
15620     iLimit = n;
15621   }
15622 #ifndef SQLITE_OMIT_AUTOINIT
15623   sqlite3_initialize();
15624 #endif
15625   if( iLimit>0 ){
15626     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
15627   }else{
15628     sqlite3MemoryAlarm(0, 0, 0);
15629   }
15630   overage = (int)(sqlite3_memory_used() - (i64)n);
15631   if( overage>0 ){
15632     sqlite3_release_memory(overage);
15633   }
15634 }
15635
15636 /*
15637 ** Attempt to release up to n bytes of non-essential memory currently
15638 ** held by SQLite. An example of non-essential memory is memory used to
15639 ** cache database pages that are not currently in use.
15640 */
15641 SQLITE_API int sqlite3_release_memory(int n){
15642 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
15643   int nRet = 0;
15644   nRet += sqlite3PcacheReleaseMemory(n-nRet);
15645   return nRet;
15646 #else
15647   UNUSED_PARAMETER(n);
15648   return SQLITE_OK;
15649 #endif
15650 }
15651
15652 /*
15653 ** State information local to the memory allocation subsystem.
15654 */
15655 static SQLITE_WSD struct Mem0Global {
15656   /* Number of free pages for scratch and page-cache memory */
15657   u32 nScratchFree;
15658   u32 nPageFree;
15659
15660   sqlite3_mutex *mutex;         /* Mutex to serialize access */
15661
15662   /*
15663   ** The alarm callback and its arguments.  The mem0.mutex lock will
15664   ** be held while the callback is running.  Recursive calls into
15665   ** the memory subsystem are allowed, but no new callbacks will be
15666   ** issued.
15667   */
15668   sqlite3_int64 alarmThreshold;
15669   void (*alarmCallback)(void*, sqlite3_int64,int);
15670   void *alarmArg;
15671
15672   /*
15673   ** Pointers to the end of sqlite3GlobalConfig.pScratch and
15674   ** sqlite3GlobalConfig.pPage to a block of memory that records
15675   ** which pages are available.
15676   */
15677   u32 *aScratchFree;
15678   u32 *aPageFree;
15679 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
15680
15681 #define mem0 GLOBAL(struct Mem0Global, mem0)
15682
15683 /*
15684 ** Initialize the memory allocation subsystem.
15685 */
15686 SQLITE_PRIVATE int sqlite3MallocInit(void){
15687   if( sqlite3GlobalConfig.m.xMalloc==0 ){
15688     sqlite3MemSetDefault();
15689   }
15690   memset(&mem0, 0, sizeof(mem0));
15691   if( sqlite3GlobalConfig.bCoreMutex ){
15692     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15693   }
15694   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
15695       && sqlite3GlobalConfig.nScratch>=0 ){
15696     int i;
15697     sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
15698     mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
15699                   [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
15700     for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
15701     mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
15702   }else{
15703     sqlite3GlobalConfig.pScratch = 0;
15704     sqlite3GlobalConfig.szScratch = 0;
15705   }
15706   if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
15707       && sqlite3GlobalConfig.nPage>=1 ){
15708     int i;
15709     int overhead;
15710     int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
15711     int n = sqlite3GlobalConfig.nPage;
15712     overhead = (4*n + sz - 1)/sz;
15713     sqlite3GlobalConfig.nPage -= overhead;
15714     mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
15715                   [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
15716     for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
15717     mem0.nPageFree = sqlite3GlobalConfig.nPage;
15718   }else{
15719     sqlite3GlobalConfig.pPage = 0;
15720     sqlite3GlobalConfig.szPage = 0;
15721   }
15722   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
15723 }
15724
15725 /*
15726 ** Deinitialize the memory allocation subsystem.
15727 */
15728 SQLITE_PRIVATE void sqlite3MallocEnd(void){
15729   if( sqlite3GlobalConfig.m.xShutdown ){
15730     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
15731   }
15732   memset(&mem0, 0, sizeof(mem0));
15733 }
15734
15735 /*
15736 ** Return the amount of memory currently checked out.
15737 */
15738 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
15739   int n, mx;
15740   sqlite3_int64 res;
15741   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
15742   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
15743   return res;
15744 }
15745
15746 /*
15747 ** Return the maximum amount of memory that has ever been
15748 ** checked out since either the beginning of this process
15749 ** or since the most recent reset.
15750 */
15751 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
15752   int n, mx;
15753   sqlite3_int64 res;
15754   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
15755   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
15756   return res;
15757 }
15758
15759 /*
15760 ** Change the alarm callback
15761 */
15762 SQLITE_PRIVATE int sqlite3MemoryAlarm(
15763   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
15764   void *pArg,
15765   sqlite3_int64 iThreshold
15766 ){
15767   sqlite3_mutex_enter(mem0.mutex);
15768   mem0.alarmCallback = xCallback;
15769   mem0.alarmArg = pArg;
15770   mem0.alarmThreshold = iThreshold;
15771   sqlite3_mutex_leave(mem0.mutex);
15772   return SQLITE_OK;
15773 }
15774
15775 #ifndef SQLITE_OMIT_DEPRECATED
15776 /*
15777 ** Deprecated external interface.  Internal/core SQLite code
15778 ** should call sqlite3MemoryAlarm.
15779 */
15780 SQLITE_API int sqlite3_memory_alarm(
15781   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
15782   void *pArg,
15783   sqlite3_int64 iThreshold
15784 ){
15785   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
15786 }
15787 #endif
15788
15789 /*
15790 ** Trigger the alarm 
15791 */
15792 static void sqlite3MallocAlarm(int nByte){
15793   void (*xCallback)(void*,sqlite3_int64,int);
15794   sqlite3_int64 nowUsed;
15795   void *pArg;
15796   if( mem0.alarmCallback==0 ) return;
15797   xCallback = mem0.alarmCallback;
15798   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
15799   pArg = mem0.alarmArg;
15800   mem0.alarmCallback = 0;
15801   sqlite3_mutex_leave(mem0.mutex);
15802   xCallback(pArg, nowUsed, nByte);
15803   sqlite3_mutex_enter(mem0.mutex);
15804   mem0.alarmCallback = xCallback;
15805   mem0.alarmArg = pArg;
15806 }
15807
15808 /*
15809 ** Do a memory allocation with statistics and alarms.  Assume the
15810 ** lock is already held.
15811 */
15812 static int mallocWithAlarm(int n, void **pp){
15813   int nFull;
15814   void *p;
15815   assert( sqlite3_mutex_held(mem0.mutex) );
15816   nFull = sqlite3GlobalConfig.m.xRoundup(n);
15817   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
15818   if( mem0.alarmCallback!=0 ){
15819     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
15820     if( nUsed+nFull >= mem0.alarmThreshold ){
15821       sqlite3MallocAlarm(nFull);
15822     }
15823   }
15824   p = sqlite3GlobalConfig.m.xMalloc(nFull);
15825   if( p==0 && mem0.alarmCallback ){
15826     sqlite3MallocAlarm(nFull);
15827     p = sqlite3GlobalConfig.m.xMalloc(nFull);
15828   }
15829   if( p ){
15830     nFull = sqlite3MallocSize(p);
15831     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
15832   }
15833   *pp = p;
15834   return nFull;
15835 }
15836
15837 /*
15838 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
15839 ** assumes the memory subsystem has already been initialized.
15840 */
15841 SQLITE_PRIVATE void *sqlite3Malloc(int n){
15842   void *p;
15843   if( n<=0 || n>=0x7fffff00 ){
15844     /* A memory allocation of a number of bytes which is near the maximum
15845     ** signed integer value might cause an integer overflow inside of the
15846     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
15847     ** 255 bytes of overhead.  SQLite itself will never use anything near
15848     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
15849     p = 0;
15850   }else if( sqlite3GlobalConfig.bMemstat ){
15851     sqlite3_mutex_enter(mem0.mutex);
15852     mallocWithAlarm(n, &p);
15853     sqlite3_mutex_leave(mem0.mutex);
15854   }else{
15855     p = sqlite3GlobalConfig.m.xMalloc(n);
15856   }
15857   return p;
15858 }
15859
15860 /*
15861 ** This version of the memory allocation is for use by the application.
15862 ** First make sure the memory subsystem is initialized, then do the
15863 ** allocation.
15864 */
15865 SQLITE_API void *sqlite3_malloc(int n){
15866 #ifndef SQLITE_OMIT_AUTOINIT
15867   if( sqlite3_initialize() ) return 0;
15868 #endif
15869   return sqlite3Malloc(n);
15870 }
15871
15872 /*
15873 ** Each thread may only have a single outstanding allocation from
15874 ** xScratchMalloc().  We verify this constraint in the single-threaded
15875 ** case by setting scratchAllocOut to 1 when an allocation
15876 ** is outstanding clearing it when the allocation is freed.
15877 */
15878 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15879 static int scratchAllocOut = 0;
15880 #endif
15881
15882
15883 /*
15884 ** Allocate memory that is to be used and released right away.
15885 ** This routine is similar to alloca() in that it is not intended
15886 ** for situations where the memory might be held long-term.  This
15887 ** routine is intended to get memory to old large transient data
15888 ** structures that would not normally fit on the stack of an
15889 ** embedded processor.
15890 */
15891 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
15892   void *p;
15893   assert( n>0 );
15894
15895 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15896   /* Verify that no more than one scratch allocation per thread
15897   ** is outstanding at one time.  (This is only checked in the
15898   ** single-threaded case since checking in the multi-threaded case
15899   ** would be much more complicated.) */
15900   assert( scratchAllocOut==0 );
15901 #endif
15902
15903   if( sqlite3GlobalConfig.szScratch<n ){
15904     goto scratch_overflow;
15905   }else{  
15906     sqlite3_mutex_enter(mem0.mutex);
15907     if( mem0.nScratchFree==0 ){
15908       sqlite3_mutex_leave(mem0.mutex);
15909       goto scratch_overflow;
15910     }else{
15911       int i;
15912       i = mem0.aScratchFree[--mem0.nScratchFree];
15913       i *= sqlite3GlobalConfig.szScratch;
15914       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
15915       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
15916       sqlite3_mutex_leave(mem0.mutex);
15917       p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
15918       assert(  (((u8*)p - (u8*)0) & 7)==0 );
15919     }
15920   }
15921 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15922   scratchAllocOut = p!=0;
15923 #endif
15924
15925   return p;
15926
15927 scratch_overflow:
15928   if( sqlite3GlobalConfig.bMemstat ){
15929     sqlite3_mutex_enter(mem0.mutex);
15930     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
15931     n = mallocWithAlarm(n, &p);
15932     if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
15933     sqlite3_mutex_leave(mem0.mutex);
15934   }else{
15935     p = sqlite3GlobalConfig.m.xMalloc(n);
15936   }
15937 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15938   scratchAllocOut = p!=0;
15939 #endif
15940   return p;    
15941 }
15942 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
15943   if( p ){
15944
15945 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15946     /* Verify that no more than one scratch allocation per thread
15947     ** is outstanding at one time.  (This is only checked in the
15948     ** single-threaded case since checking in the multi-threaded case
15949     ** would be much more complicated.) */
15950     assert( scratchAllocOut==1 );
15951     scratchAllocOut = 0;
15952 #endif
15953
15954     if( sqlite3GlobalConfig.pScratch==0
15955            || p<sqlite3GlobalConfig.pScratch
15956            || p>=(void*)mem0.aScratchFree ){
15957       if( sqlite3GlobalConfig.bMemstat ){
15958         int iSize = sqlite3MallocSize(p);
15959         sqlite3_mutex_enter(mem0.mutex);
15960         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
15961         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
15962         sqlite3GlobalConfig.m.xFree(p);
15963         sqlite3_mutex_leave(mem0.mutex);
15964       }else{
15965         sqlite3GlobalConfig.m.xFree(p);
15966       }
15967     }else{
15968       int i;
15969       i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
15970       i /= sqlite3GlobalConfig.szScratch;
15971       assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
15972       sqlite3_mutex_enter(mem0.mutex);
15973       assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
15974       mem0.aScratchFree[mem0.nScratchFree++] = i;
15975       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
15976       sqlite3_mutex_leave(mem0.mutex);
15977     }
15978   }
15979 }
15980
15981 /*
15982 ** TRUE if p is a lookaside memory allocation from db
15983 */
15984 #ifndef SQLITE_OMIT_LOOKASIDE
15985 static int isLookaside(sqlite3 *db, void *p){
15986   return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
15987 }
15988 #else
15989 #define isLookaside(A,B) 0
15990 #endif
15991
15992 /*
15993 ** Return the size of a memory allocation previously obtained from
15994 ** sqlite3Malloc() or sqlite3_malloc().
15995 */
15996 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
15997   return sqlite3GlobalConfig.m.xSize(p);
15998 }
15999 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
16000   assert( db==0 || sqlite3_mutex_held(db->mutex) );
16001   if( isLookaside(db, p) ){
16002     return db->lookaside.sz;
16003   }else{
16004     return sqlite3GlobalConfig.m.xSize(p);
16005   }
16006 }
16007
16008 /*
16009 ** Free memory previously obtained from sqlite3Malloc().
16010 */
16011 SQLITE_API void sqlite3_free(void *p){
16012   if( p==0 ) return;
16013   if( sqlite3GlobalConfig.bMemstat ){
16014     sqlite3_mutex_enter(mem0.mutex);
16015     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
16016     sqlite3GlobalConfig.m.xFree(p);
16017     sqlite3_mutex_leave(mem0.mutex);
16018   }else{
16019     sqlite3GlobalConfig.m.xFree(p);
16020   }
16021 }
16022
16023 /*
16024 ** Free memory that might be associated with a particular database
16025 ** connection.
16026 */
16027 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
16028   assert( db==0 || sqlite3_mutex_held(db->mutex) );
16029   if( isLookaside(db, p) ){
16030     LookasideSlot *pBuf = (LookasideSlot*)p;
16031     pBuf->pNext = db->lookaside.pFree;
16032     db->lookaside.pFree = pBuf;
16033     db->lookaside.nOut--;
16034   }else{
16035     sqlite3_free(p);
16036   }
16037 }
16038
16039 /*
16040 ** Change the size of an existing memory allocation
16041 */
16042 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
16043   int nOld, nNew;
16044   void *pNew;
16045   if( pOld==0 ){
16046     return sqlite3Malloc(nBytes);
16047   }
16048   if( nBytes<=0 ){
16049     sqlite3_free(pOld);
16050     return 0;
16051   }
16052   if( nBytes>=0x7fffff00 ){
16053     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
16054     return 0;
16055   }
16056   nOld = sqlite3MallocSize(pOld);
16057   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
16058   if( nOld==nNew ){
16059     pNew = pOld;
16060   }else if( sqlite3GlobalConfig.bMemstat ){
16061     sqlite3_mutex_enter(mem0.mutex);
16062     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
16063     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
16064           mem0.alarmThreshold ){
16065       sqlite3MallocAlarm(nNew-nOld);
16066     }
16067     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16068     if( pNew==0 && mem0.alarmCallback ){
16069       sqlite3MallocAlarm(nBytes);
16070       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16071     }
16072     if( pNew ){
16073       nNew = sqlite3MallocSize(pNew);
16074       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
16075     }
16076     sqlite3_mutex_leave(mem0.mutex);
16077   }else{
16078     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16079   }
16080   return pNew;
16081 }
16082
16083 /*
16084 ** The public interface to sqlite3Realloc.  Make sure that the memory
16085 ** subsystem is initialized prior to invoking sqliteRealloc.
16086 */
16087 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
16088 #ifndef SQLITE_OMIT_AUTOINIT
16089   if( sqlite3_initialize() ) return 0;
16090 #endif
16091   return sqlite3Realloc(pOld, n);
16092 }
16093
16094
16095 /*
16096 ** Allocate and zero memory.
16097 */ 
16098 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
16099   void *p = sqlite3Malloc(n);
16100   if( p ){
16101     memset(p, 0, n);
16102   }
16103   return p;
16104 }
16105
16106 /*
16107 ** Allocate and zero memory.  If the allocation fails, make
16108 ** the mallocFailed flag in the connection pointer.
16109 */
16110 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
16111   void *p = sqlite3DbMallocRaw(db, n);
16112   if( p ){
16113     memset(p, 0, n);
16114   }
16115   return p;
16116 }
16117
16118 /*
16119 ** Allocate and zero memory.  If the allocation fails, make
16120 ** the mallocFailed flag in the connection pointer.
16121 **
16122 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
16123 ** failure on the same database connection) then always return 0.
16124 ** Hence for a particular database connection, once malloc starts
16125 ** failing, it fails consistently until mallocFailed is reset.
16126 ** This is an important assumption.  There are many places in the
16127 ** code that do things like this:
16128 **
16129 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
16130 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
16131 **         if( b ) a[10] = 9;
16132 **
16133 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
16134 ** that all prior mallocs (ex: "a") worked too.
16135 */
16136 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
16137   void *p;
16138   assert( db==0 || sqlite3_mutex_held(db->mutex) );
16139 #ifndef SQLITE_OMIT_LOOKASIDE
16140   if( db ){
16141     LookasideSlot *pBuf;
16142     if( db->mallocFailed ){
16143       return 0;
16144     }
16145     if( db->lookaside.bEnabled && n<=db->lookaside.sz
16146          && (pBuf = db->lookaside.pFree)!=0 ){
16147       db->lookaside.pFree = pBuf->pNext;
16148       db->lookaside.nOut++;
16149       if( db->lookaside.nOut>db->lookaside.mxOut ){
16150         db->lookaside.mxOut = db->lookaside.nOut;
16151       }
16152       return (void*)pBuf;
16153     }
16154   }
16155 #else
16156   if( db && db->mallocFailed ){
16157     return 0;
16158   }
16159 #endif
16160   p = sqlite3Malloc(n);
16161   if( !p && db ){
16162     db->mallocFailed = 1;
16163   }
16164   return p;
16165 }
16166
16167 /*
16168 ** Resize the block of memory pointed to by p to n bytes. If the
16169 ** resize fails, set the mallocFailed flag in the connection object.
16170 */
16171 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
16172   void *pNew = 0;
16173   assert( db!=0 );
16174   assert( sqlite3_mutex_held(db->mutex) );
16175   if( db->mallocFailed==0 ){
16176     if( p==0 ){
16177       return sqlite3DbMallocRaw(db, n);
16178     }
16179     if( isLookaside(db, p) ){
16180       if( n<=db->lookaside.sz ){
16181         return p;
16182       }
16183       pNew = sqlite3DbMallocRaw(db, n);
16184       if( pNew ){
16185         memcpy(pNew, p, db->lookaside.sz);
16186         sqlite3DbFree(db, p);
16187       }
16188     }else{
16189       pNew = sqlite3_realloc(p, n);
16190       if( !pNew ){
16191         db->mallocFailed = 1;
16192       }
16193     }
16194   }
16195   return pNew;
16196 }
16197
16198 /*
16199 ** Attempt to reallocate p.  If the reallocation fails, then free p
16200 ** and set the mallocFailed flag in the database connection.
16201 */
16202 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
16203   void *pNew;
16204   pNew = sqlite3DbRealloc(db, p, n);
16205   if( !pNew ){
16206     sqlite3DbFree(db, p);
16207   }
16208   return pNew;
16209 }
16210
16211 /*
16212 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
16213 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
16214 ** is because when memory debugging is turned on, these two functions are 
16215 ** called via macros that record the current file and line number in the
16216 ** ThreadData structure.
16217 */
16218 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
16219   char *zNew;
16220   size_t n;
16221   if( z==0 ){
16222     return 0;
16223   }
16224   n = sqlite3Strlen30(z) + 1;
16225   assert( (n&0x7fffffff)==n );
16226   zNew = sqlite3DbMallocRaw(db, (int)n);
16227   if( zNew ){
16228     memcpy(zNew, z, n);
16229   }
16230   return zNew;
16231 }
16232 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
16233   char *zNew;
16234   if( z==0 ){
16235     return 0;
16236   }
16237   assert( (n&0x7fffffff)==n );
16238   zNew = sqlite3DbMallocRaw(db, n+1);
16239   if( zNew ){
16240     memcpy(zNew, z, n);
16241     zNew[n] = 0;
16242   }
16243   return zNew;
16244 }
16245
16246 /*
16247 ** Create a string from the zFromat argument and the va_list that follows.
16248 ** Store the string in memory obtained from sqliteMalloc() and make *pz
16249 ** point to that string.
16250 */
16251 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
16252   va_list ap;
16253   char *z;
16254
16255   va_start(ap, zFormat);
16256   z = sqlite3VMPrintf(db, zFormat, ap);
16257   va_end(ap);
16258   sqlite3DbFree(db, *pz);
16259   *pz = z;
16260 }
16261
16262
16263 /*
16264 ** This function must be called before exiting any API function (i.e. 
16265 ** returning control to the user) that has called sqlite3_malloc or
16266 ** sqlite3_realloc.
16267 **
16268 ** The returned value is normally a copy of the second argument to this
16269 ** function. However, if a malloc() failure has occurred since the previous
16270 ** invocation SQLITE_NOMEM is returned instead. 
16271 **
16272 ** If the first argument, db, is not NULL and a malloc() error has occurred,
16273 ** then the connection error-code (the value returned by sqlite3_errcode())
16274 ** is set to SQLITE_NOMEM.
16275 */
16276 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
16277   /* If the db handle is not NULL, then we must hold the connection handle
16278   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
16279   ** is unsafe, as is the call to sqlite3Error().
16280   */
16281   assert( !db || sqlite3_mutex_held(db->mutex) );
16282   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
16283     sqlite3Error(db, SQLITE_NOMEM, 0);
16284     db->mallocFailed = 0;
16285     rc = SQLITE_NOMEM;
16286   }
16287   return rc & (db ? db->errMask : 0xff);
16288 }
16289
16290 /************** End of malloc.c **********************************************/
16291 /************** Begin file printf.c ******************************************/
16292 /*
16293 ** The "printf" code that follows dates from the 1980's.  It is in
16294 ** the public domain.  The original comments are included here for
16295 ** completeness.  They are very out-of-date but might be useful as
16296 ** an historical reference.  Most of the "enhancements" have been backed
16297 ** out so that the functionality is now the same as standard printf().
16298 **
16299 **************************************************************************
16300 **
16301 ** The following modules is an enhanced replacement for the "printf" subroutines
16302 ** found in the standard C library.  The following enhancements are
16303 ** supported:
16304 **
16305 **      +  Additional functions.  The standard set of "printf" functions
16306 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
16307 **         vsprintf.  This module adds the following:
16308 **
16309 **           *  snprintf -- Works like sprintf, but has an extra argument
16310 **                          which is the size of the buffer written to.
16311 **
16312 **           *  mprintf --  Similar to sprintf.  Writes output to memory
16313 **                          obtained from malloc.
16314 **
16315 **           *  xprintf --  Calls a function to dispose of output.
16316 **
16317 **           *  nprintf --  No output, but returns the number of characters
16318 **                          that would have been output by printf.
16319 **
16320 **           *  A v- version (ex: vsnprintf) of every function is also
16321 **              supplied.
16322 **
16323 **      +  A few extensions to the formatting notation are supported:
16324 **
16325 **           *  The "=" flag (similar to "-") causes the output to be
16326 **              be centered in the appropriately sized field.
16327 **
16328 **           *  The %b field outputs an integer in binary notation.
16329 **
16330 **           *  The %c field now accepts a precision.  The character output
16331 **              is repeated by the number of times the precision specifies.
16332 **
16333 **           *  The %' field works like %c, but takes as its character the
16334 **              next character of the format string, instead of the next
16335 **              argument.  For example,  printf("%.78'-")  prints 78 minus
16336 **              signs, the same as  printf("%.78c",'-').
16337 **
16338 **      +  When compiled using GCC on a SPARC, this version of printf is
16339 **         faster than the library printf for SUN OS 4.1.
16340 **
16341 **      +  All functions are fully reentrant.
16342 **
16343 */
16344
16345 /*
16346 ** Conversion types fall into various categories as defined by the
16347 ** following enumeration.
16348 */
16349 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
16350 #define etFLOAT       2 /* Floating point.  %f */
16351 #define etEXP         3 /* Exponentional notation. %e and %E */
16352 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
16353 #define etSIZE        5 /* Return number of characters processed so far. %n */
16354 #define etSTRING      6 /* Strings. %s */
16355 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
16356 #define etPERCENT     8 /* Percent symbol. %% */
16357 #define etCHARX       9 /* Characters. %c */
16358 /* The rest are extensions, not normally found in printf() */
16359 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
16360 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
16361                           NULL pointers replaced by SQL NULL.  %Q */
16362 #define etTOKEN      12 /* a pointer to a Token structure */
16363 #define etSRCLIST    13 /* a pointer to a SrcList */
16364 #define etPOINTER    14 /* The %p conversion */
16365 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
16366 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
16367
16368 #define etINVALID     0 /* Any unrecognized conversion type */
16369
16370
16371 /*
16372 ** An "etByte" is an 8-bit unsigned value.
16373 */
16374 typedef unsigned char etByte;
16375
16376 /*
16377 ** Each builtin conversion character (ex: the 'd' in "%d") is described
16378 ** by an instance of the following structure
16379 */
16380 typedef struct et_info {   /* Information about each format field */
16381   char fmttype;            /* The format field code letter */
16382   etByte base;             /* The base for radix conversion */
16383   etByte flags;            /* One or more of FLAG_ constants below */
16384   etByte type;             /* Conversion paradigm */
16385   etByte charset;          /* Offset into aDigits[] of the digits string */
16386   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
16387 } et_info;
16388
16389 /*
16390 ** Allowed values for et_info.flags
16391 */
16392 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
16393 #define FLAG_INTERN  2     /* True if for internal use only */
16394 #define FLAG_STRING  4     /* Allow infinity precision */
16395
16396
16397 /*
16398 ** The following table is searched linearly, so it is good to put the
16399 ** most frequently used conversion types first.
16400 */
16401 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
16402 static const char aPrefix[] = "-x0\000X0";
16403 static const et_info fmtinfo[] = {
16404   {  'd', 10, 1, etRADIX,      0,  0 },
16405   {  's',  0, 4, etSTRING,     0,  0 },
16406   {  'g',  0, 1, etGENERIC,    30, 0 },
16407   {  'z',  0, 4, etDYNSTRING,  0,  0 },
16408   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
16409   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
16410   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
16411   {  'c',  0, 0, etCHARX,      0,  0 },
16412   {  'o',  8, 0, etRADIX,      0,  2 },
16413   {  'u', 10, 0, etRADIX,      0,  0 },
16414   {  'x', 16, 0, etRADIX,      16, 1 },
16415   {  'X', 16, 0, etRADIX,      0,  4 },
16416 #ifndef SQLITE_OMIT_FLOATING_POINT
16417   {  'f',  0, 1, etFLOAT,      0,  0 },
16418   {  'e',  0, 1, etEXP,        30, 0 },
16419   {  'E',  0, 1, etEXP,        14, 0 },
16420   {  'G',  0, 1, etGENERIC,    14, 0 },
16421 #endif
16422   {  'i', 10, 1, etRADIX,      0,  0 },
16423   {  'n',  0, 0, etSIZE,       0,  0 },
16424   {  '%',  0, 0, etPERCENT,    0,  0 },
16425   {  'p', 16, 0, etPOINTER,    0,  1 },
16426
16427 /* All the rest have the FLAG_INTERN bit set and are thus for internal
16428 ** use only */
16429   {  'T',  0, 2, etTOKEN,      0,  0 },
16430   {  'S',  0, 2, etSRCLIST,    0,  0 },
16431   {  'r', 10, 3, etORDINAL,    0,  0 },
16432 };
16433
16434 /*
16435 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
16436 ** conversions will work.
16437 */
16438 #ifndef SQLITE_OMIT_FLOATING_POINT
16439 /*
16440 ** "*val" is a double such that 0.1 <= *val < 10.0
16441 ** Return the ascii code for the leading digit of *val, then
16442 ** multiply "*val" by 10.0 to renormalize.
16443 **
16444 ** Example:
16445 **     input:     *val = 3.14159
16446 **     output:    *val = 1.4159    function return = '3'
16447 **
16448 ** The counter *cnt is incremented each time.  After counter exceeds
16449 ** 16 (the number of significant digits in a 64-bit float) '0' is
16450 ** always returned.
16451 */
16452 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
16453   int digit;
16454   LONGDOUBLE_TYPE d;
16455   if( (*cnt)++ >= 16 ) return '0';
16456   digit = (int)*val;
16457   d = digit;
16458   digit += '0';
16459   *val = (*val - d)*10.0;
16460   return (char)digit;
16461 }
16462 #endif /* SQLITE_OMIT_FLOATING_POINT */
16463
16464 /*
16465 ** Append N space characters to the given string buffer.
16466 */
16467 static void appendSpace(StrAccum *pAccum, int N){
16468   static const char zSpaces[] = "                             ";
16469   while( N>=(int)sizeof(zSpaces)-1 ){
16470     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
16471     N -= sizeof(zSpaces)-1;
16472   }
16473   if( N>0 ){
16474     sqlite3StrAccumAppend(pAccum, zSpaces, N);
16475   }
16476 }
16477
16478 /*
16479 ** On machines with a small stack size, you can redefine the
16480 ** SQLITE_PRINT_BUF_SIZE to be less than 350.
16481 */
16482 #ifndef SQLITE_PRINT_BUF_SIZE
16483 # if defined(SQLITE_SMALL_STACK)
16484 #   define SQLITE_PRINT_BUF_SIZE 50
16485 # else
16486 #   define SQLITE_PRINT_BUF_SIZE 350
16487 # endif
16488 #endif
16489 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
16490
16491 /*
16492 ** The root program.  All variations call this core.
16493 **
16494 ** INPUTS:
16495 **   func   This is a pointer to a function taking three arguments
16496 **            1. A pointer to anything.  Same as the "arg" parameter.
16497 **            2. A pointer to the list of characters to be output
16498 **               (Note, this list is NOT null terminated.)
16499 **            3. An integer number of characters to be output.
16500 **               (Note: This number might be zero.)
16501 **
16502 **   arg    This is the pointer to anything which will be passed as the
16503 **          first argument to "func".  Use it for whatever you like.
16504 **
16505 **   fmt    This is the format string, as in the usual print.
16506 **
16507 **   ap     This is a pointer to a list of arguments.  Same as in
16508 **          vfprint.
16509 **
16510 ** OUTPUTS:
16511 **          The return value is the total number of characters sent to
16512 **          the function "func".  Returns -1 on a error.
16513 **
16514 ** Note that the order in which automatic variables are declared below
16515 ** seems to make a big difference in determining how fast this beast
16516 ** will run.
16517 */
16518 SQLITE_PRIVATE void sqlite3VXPrintf(
16519   StrAccum *pAccum,                  /* Accumulate results here */
16520   int useExtended,                   /* Allow extended %-conversions */
16521   const char *fmt,                   /* Format string */
16522   va_list ap                         /* arguments */
16523 ){
16524   int c;                     /* Next character in the format string */
16525   char *bufpt;               /* Pointer to the conversion buffer */
16526   int precision;             /* Precision of the current field */
16527   int length;                /* Length of the field */
16528   int idx;                   /* A general purpose loop counter */
16529   int width;                 /* Width of the current field */
16530   etByte flag_leftjustify;   /* True if "-" flag is present */
16531   etByte flag_plussign;      /* True if "+" flag is present */
16532   etByte flag_blanksign;     /* True if " " flag is present */
16533   etByte flag_alternateform; /* True if "#" flag is present */
16534   etByte flag_altform2;      /* True if "!" flag is present */
16535   etByte flag_zeropad;       /* True if field width constant starts with zero */
16536   etByte flag_long;          /* True if "l" flag is present */
16537   etByte flag_longlong;      /* True if the "ll" flag is present */
16538   etByte done;               /* Loop termination flag */
16539   sqlite_uint64 longvalue;   /* Value for integer types */
16540   LONGDOUBLE_TYPE realvalue; /* Value for real types */
16541   const et_info *infop;      /* Pointer to the appropriate info structure */
16542   char buf[etBUFSIZE];       /* Conversion buffer */
16543   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
16544   etByte xtype = 0;          /* Conversion paradigm */
16545   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
16546 #ifndef SQLITE_OMIT_FLOATING_POINT
16547   int  exp, e2;              /* exponent of real numbers */
16548   double rounder;            /* Used for rounding floating point values */
16549   etByte flag_dp;            /* True if decimal point should be shown */
16550   etByte flag_rtz;           /* True if trailing zeros should be removed */
16551   etByte flag_exp;           /* True to force display of the exponent */
16552   int nsd;                   /* Number of significant digits returned */
16553 #endif
16554
16555   length = 0;
16556   bufpt = 0;
16557   for(; (c=(*fmt))!=0; ++fmt){
16558     if( c!='%' ){
16559       int amt;
16560       bufpt = (char *)fmt;
16561       amt = 1;
16562       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
16563       sqlite3StrAccumAppend(pAccum, bufpt, amt);
16564       if( c==0 ) break;
16565     }
16566     if( (c=(*++fmt))==0 ){
16567       sqlite3StrAccumAppend(pAccum, "%", 1);
16568       break;
16569     }
16570     /* Find out what flags are present */
16571     flag_leftjustify = flag_plussign = flag_blanksign = 
16572      flag_alternateform = flag_altform2 = flag_zeropad = 0;
16573     done = 0;
16574     do{
16575       switch( c ){
16576         case '-':   flag_leftjustify = 1;     break;
16577         case '+':   flag_plussign = 1;        break;
16578         case ' ':   flag_blanksign = 1;       break;
16579         case '#':   flag_alternateform = 1;   break;
16580         case '!':   flag_altform2 = 1;        break;
16581         case '0':   flag_zeropad = 1;         break;
16582         default:    done = 1;                 break;
16583       }
16584     }while( !done && (c=(*++fmt))!=0 );
16585     /* Get the field width */
16586     width = 0;
16587     if( c=='*' ){
16588       width = va_arg(ap,int);
16589       if( width<0 ){
16590         flag_leftjustify = 1;
16591         width = -width;
16592       }
16593       c = *++fmt;
16594     }else{
16595       while( c>='0' && c<='9' ){
16596         width = width*10 + c - '0';
16597         c = *++fmt;
16598       }
16599     }
16600     if( width > etBUFSIZE-10 ){
16601       width = etBUFSIZE-10;
16602     }
16603     /* Get the precision */
16604     if( c=='.' ){
16605       precision = 0;
16606       c = *++fmt;
16607       if( c=='*' ){
16608         precision = va_arg(ap,int);
16609         if( precision<0 ) precision = -precision;
16610         c = *++fmt;
16611       }else{
16612         while( c>='0' && c<='9' ){
16613           precision = precision*10 + c - '0';
16614           c = *++fmt;
16615         }
16616       }
16617     }else{
16618       precision = -1;
16619     }
16620     /* Get the conversion type modifier */
16621     if( c=='l' ){
16622       flag_long = 1;
16623       c = *++fmt;
16624       if( c=='l' ){
16625         flag_longlong = 1;
16626         c = *++fmt;
16627       }else{
16628         flag_longlong = 0;
16629       }
16630     }else{
16631       flag_long = flag_longlong = 0;
16632     }
16633     /* Fetch the info entry for the field */
16634     infop = &fmtinfo[0];
16635     xtype = etINVALID;
16636     for(idx=0; idx<ArraySize(fmtinfo); idx++){
16637       if( c==fmtinfo[idx].fmttype ){
16638         infop = &fmtinfo[idx];
16639         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
16640           xtype = infop->type;
16641         }else{
16642           return;
16643         }
16644         break;
16645       }
16646     }
16647     zExtra = 0;
16648
16649
16650     /* Limit the precision to prevent overflowing buf[] during conversion */
16651     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
16652       precision = etBUFSIZE-40;
16653     }
16654
16655     /*
16656     ** At this point, variables are initialized as follows:
16657     **
16658     **   flag_alternateform          TRUE if a '#' is present.
16659     **   flag_altform2               TRUE if a '!' is present.
16660     **   flag_plussign               TRUE if a '+' is present.
16661     **   flag_leftjustify            TRUE if a '-' is present or if the
16662     **                               field width was negative.
16663     **   flag_zeropad                TRUE if the width began with 0.
16664     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
16665     **                               the conversion character.
16666     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
16667     **                               the conversion character.
16668     **   flag_blanksign              TRUE if a ' ' is present.
16669     **   width                       The specified field width.  This is
16670     **                               always non-negative.  Zero is the default.
16671     **   precision                   The specified precision.  The default
16672     **                               is -1.
16673     **   xtype                       The class of the conversion.
16674     **   infop                       Pointer to the appropriate info struct.
16675     */
16676     switch( xtype ){
16677       case etPOINTER:
16678         flag_longlong = sizeof(char*)==sizeof(i64);
16679         flag_long = sizeof(char*)==sizeof(long int);
16680         /* Fall through into the next case */
16681       case etORDINAL:
16682       case etRADIX:
16683         if( infop->flags & FLAG_SIGNED ){
16684           i64 v;
16685           if( flag_longlong ){
16686             v = va_arg(ap,i64);
16687           }else if( flag_long ){
16688             v = va_arg(ap,long int);
16689           }else{
16690             v = va_arg(ap,int);
16691           }
16692           if( v<0 ){
16693             longvalue = -v;
16694             prefix = '-';
16695           }else{
16696             longvalue = v;
16697             if( flag_plussign )        prefix = '+';
16698             else if( flag_blanksign )  prefix = ' ';
16699             else                       prefix = 0;
16700           }
16701         }else{
16702           if( flag_longlong ){
16703             longvalue = va_arg(ap,u64);
16704           }else if( flag_long ){
16705             longvalue = va_arg(ap,unsigned long int);
16706           }else{
16707             longvalue = va_arg(ap,unsigned int);
16708           }
16709           prefix = 0;
16710         }
16711         if( longvalue==0 ) flag_alternateform = 0;
16712         if( flag_zeropad && precision<width-(prefix!=0) ){
16713           precision = width-(prefix!=0);
16714         }
16715         bufpt = &buf[etBUFSIZE-1];
16716         if( xtype==etORDINAL ){
16717           static const char zOrd[] = "thstndrd";
16718           int x = (int)(longvalue % 10);
16719           if( x>=4 || (longvalue/10)%10==1 ){
16720             x = 0;
16721           }
16722           buf[etBUFSIZE-3] = zOrd[x*2];
16723           buf[etBUFSIZE-2] = zOrd[x*2+1];
16724           bufpt -= 2;
16725         }
16726         {
16727           register const char *cset;      /* Use registers for speed */
16728           register int base;
16729           cset = &aDigits[infop->charset];
16730           base = infop->base;
16731           do{                                           /* Convert to ascii */
16732             *(--bufpt) = cset[longvalue%base];
16733             longvalue = longvalue/base;
16734           }while( longvalue>0 );
16735         }
16736         length = (int)(&buf[etBUFSIZE-1]-bufpt);
16737         for(idx=precision-length; idx>0; idx--){
16738           *(--bufpt) = '0';                             /* Zero pad */
16739         }
16740         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
16741         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
16742           const char *pre;
16743           char x;
16744           pre = &aPrefix[infop->prefix];
16745           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
16746         }
16747         length = (int)(&buf[etBUFSIZE-1]-bufpt);
16748         break;
16749       case etFLOAT:
16750       case etEXP:
16751       case etGENERIC:
16752         realvalue = va_arg(ap,double);
16753 #ifndef SQLITE_OMIT_FLOATING_POINT
16754         if( precision<0 ) precision = 6;         /* Set default precision */
16755         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
16756         if( realvalue<0.0 ){
16757           realvalue = -realvalue;
16758           prefix = '-';
16759         }else{
16760           if( flag_plussign )          prefix = '+';
16761           else if( flag_blanksign )    prefix = ' ';
16762           else                         prefix = 0;
16763         }
16764         if( xtype==etGENERIC && precision>0 ) precision--;
16765 #if 0
16766         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
16767         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
16768 #else
16769         /* It makes more sense to use 0.5 */
16770         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
16771 #endif
16772         if( xtype==etFLOAT ) realvalue += rounder;
16773         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
16774         exp = 0;
16775         if( sqlite3IsNaN((double)realvalue) ){
16776           bufpt = "NaN";
16777           length = 3;
16778           break;
16779         }
16780         if( realvalue>0.0 ){
16781           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
16782           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
16783           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
16784           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
16785           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
16786           if( exp>350 ){
16787             if( prefix=='-' ){
16788               bufpt = "-Inf";
16789             }else if( prefix=='+' ){
16790               bufpt = "+Inf";
16791             }else{
16792               bufpt = "Inf";
16793             }
16794             length = sqlite3Strlen30(bufpt);
16795             break;
16796           }
16797         }
16798         bufpt = buf;
16799         /*
16800         ** If the field type is etGENERIC, then convert to either etEXP
16801         ** or etFLOAT, as appropriate.
16802         */
16803         flag_exp = xtype==etEXP;
16804         if( xtype!=etFLOAT ){
16805           realvalue += rounder;
16806           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
16807         }
16808         if( xtype==etGENERIC ){
16809           flag_rtz = !flag_alternateform;
16810           if( exp<-4 || exp>precision ){
16811             xtype = etEXP;
16812           }else{
16813             precision = precision - exp;
16814             xtype = etFLOAT;
16815           }
16816         }else{
16817           flag_rtz = 0;
16818         }
16819         if( xtype==etEXP ){
16820           e2 = 0;
16821         }else{
16822           e2 = exp;
16823         }
16824         nsd = 0;
16825         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
16826         /* The sign in front of the number */
16827         if( prefix ){
16828           *(bufpt++) = prefix;
16829         }
16830         /* Digits prior to the decimal point */
16831         if( e2<0 ){
16832           *(bufpt++) = '0';
16833         }else{
16834           for(; e2>=0; e2--){
16835             *(bufpt++) = et_getdigit(&realvalue,&nsd);
16836           }
16837         }
16838         /* The decimal point */
16839         if( flag_dp ){
16840           *(bufpt++) = '.';
16841         }
16842         /* "0" digits after the decimal point but before the first
16843         ** significant digit of the number */
16844         for(e2++; e2<0; precision--, e2++){
16845           assert( precision>0 );
16846           *(bufpt++) = '0';
16847         }
16848         /* Significant digits after the decimal point */
16849         while( (precision--)>0 ){
16850           *(bufpt++) = et_getdigit(&realvalue,&nsd);
16851         }
16852         /* Remove trailing zeros and the "." if no digits follow the "." */
16853         if( flag_rtz && flag_dp ){
16854           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
16855           assert( bufpt>buf );
16856           if( bufpt[-1]=='.' ){
16857             if( flag_altform2 ){
16858               *(bufpt++) = '0';
16859             }else{
16860               *(--bufpt) = 0;
16861             }
16862           }
16863         }
16864         /* Add the "eNNN" suffix */
16865         if( flag_exp || xtype==etEXP ){
16866           *(bufpt++) = aDigits[infop->charset];
16867           if( exp<0 ){
16868             *(bufpt++) = '-'; exp = -exp;
16869           }else{
16870             *(bufpt++) = '+';
16871           }
16872           if( exp>=100 ){
16873             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
16874             exp %= 100;
16875           }
16876           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
16877           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
16878         }
16879         *bufpt = 0;
16880
16881         /* The converted number is in buf[] and zero terminated. Output it.
16882         ** Note that the number is in the usual order, not reversed as with
16883         ** integer conversions. */
16884         length = (int)(bufpt-buf);
16885         bufpt = buf;
16886
16887         /* Special case:  Add leading zeros if the flag_zeropad flag is
16888         ** set and we are not left justified */
16889         if( flag_zeropad && !flag_leftjustify && length < width){
16890           int i;
16891           int nPad = width - length;
16892           for(i=width; i>=nPad; i--){
16893             bufpt[i] = bufpt[i-nPad];
16894           }
16895           i = prefix!=0;
16896           while( nPad-- ) bufpt[i++] = '0';
16897           length = width;
16898         }
16899 #endif
16900         break;
16901       case etSIZE:
16902         *(va_arg(ap,int*)) = pAccum->nChar;
16903         length = width = 0;
16904         break;
16905       case etPERCENT:
16906         buf[0] = '%';
16907         bufpt = buf;
16908         length = 1;
16909         break;
16910       case etCHARX:
16911         c = va_arg(ap,int);
16912         buf[0] = (char)c;
16913         if( precision>=0 ){
16914           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
16915           length = precision;
16916         }else{
16917           length =1;
16918         }
16919         bufpt = buf;
16920         break;
16921       case etSTRING:
16922       case etDYNSTRING:
16923         bufpt = va_arg(ap,char*);
16924         if( bufpt==0 ){
16925           bufpt = "";
16926         }else if( xtype==etDYNSTRING ){
16927           zExtra = bufpt;
16928         }
16929         if( precision>=0 ){
16930           for(length=0; length<precision && bufpt[length]; length++){}
16931         }else{
16932           length = sqlite3Strlen30(bufpt);
16933         }
16934         break;
16935       case etSQLESCAPE:
16936       case etSQLESCAPE2:
16937       case etSQLESCAPE3: {
16938         int i, j, k, n, isnull;
16939         int needQuote;
16940         char ch;
16941         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
16942         char *escarg = va_arg(ap,char*);
16943         isnull = escarg==0;
16944         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
16945         k = precision;
16946         for(i=n=0; (ch=escarg[i])!=0 && k!=0; i++, k--){
16947           if( ch==q )  n++;
16948         }
16949         needQuote = !isnull && xtype==etSQLESCAPE2;
16950         n += i + 1 + needQuote*2;
16951         if( n>etBUFSIZE ){
16952           bufpt = zExtra = sqlite3Malloc( n );
16953           if( bufpt==0 ){
16954             pAccum->mallocFailed = 1;
16955             return;
16956           }
16957         }else{
16958           bufpt = buf;
16959         }
16960         j = 0;
16961         if( needQuote ) bufpt[j++] = q;
16962         k = i;
16963         for(i=0; i<k; i++){
16964           bufpt[j++] = ch = escarg[i];
16965           if( ch==q ) bufpt[j++] = ch;
16966         }
16967         if( needQuote ) bufpt[j++] = q;
16968         bufpt[j] = 0;
16969         length = j;
16970         /* The precision in %q and %Q means how many input characters to
16971         ** consume, not the length of the output...
16972         ** if( precision>=0 && precision<length ) length = precision; */
16973         break;
16974       }
16975       case etTOKEN: {
16976         Token *pToken = va_arg(ap, Token*);
16977         if( pToken ){
16978           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
16979         }
16980         length = width = 0;
16981         break;
16982       }
16983       case etSRCLIST: {
16984         SrcList *pSrc = va_arg(ap, SrcList*);
16985         int k = va_arg(ap, int);
16986         struct SrcList_item *pItem = &pSrc->a[k];
16987         assert( k>=0 && k<pSrc->nSrc );
16988         if( pItem->zDatabase ){
16989           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
16990           sqlite3StrAccumAppend(pAccum, ".", 1);
16991         }
16992         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
16993         length = width = 0;
16994         break;
16995       }
16996       default: {
16997         assert( xtype==etINVALID );
16998         return;
16999       }
17000     }/* End switch over the format type */
17001     /*
17002     ** The text of the conversion is pointed to by "bufpt" and is
17003     ** "length" characters long.  The field width is "width".  Do
17004     ** the output.
17005     */
17006     if( !flag_leftjustify ){
17007       register int nspace;
17008       nspace = width-length;
17009       if( nspace>0 ){
17010         appendSpace(pAccum, nspace);
17011       }
17012     }
17013     if( length>0 ){
17014       sqlite3StrAccumAppend(pAccum, bufpt, length);
17015     }
17016     if( flag_leftjustify ){
17017       register int nspace;
17018       nspace = width-length;
17019       if( nspace>0 ){
17020         appendSpace(pAccum, nspace);
17021       }
17022     }
17023     if( zExtra ){
17024       sqlite3_free(zExtra);
17025     }
17026   }/* End for loop over the format string */
17027 } /* End of function */
17028
17029 /*
17030 ** Append N bytes of text from z to the StrAccum object.
17031 */
17032 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
17033   assert( z!=0 || N==0 );
17034   if( p->tooBig | p->mallocFailed ){
17035     testcase(p->tooBig);
17036     testcase(p->mallocFailed);
17037     return;
17038   }
17039   if( N<0 ){
17040     N = sqlite3Strlen30(z);
17041   }
17042   if( N==0 || NEVER(z==0) ){
17043     return;
17044   }
17045   if( p->nChar+N >= p->nAlloc ){
17046     char *zNew;
17047     if( !p->useMalloc ){
17048       p->tooBig = 1;
17049       N = p->nAlloc - p->nChar - 1;
17050       if( N<=0 ){
17051         return;
17052       }
17053     }else{
17054       i64 szNew = p->nChar;
17055       szNew += N + 1;
17056       if( szNew > p->mxAlloc ){
17057         sqlite3StrAccumReset(p);
17058         p->tooBig = 1;
17059         return;
17060       }else{
17061         p->nAlloc = (int)szNew;
17062       }
17063       zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
17064       if( zNew ){
17065         memcpy(zNew, p->zText, p->nChar);
17066         sqlite3StrAccumReset(p);
17067         p->zText = zNew;
17068       }else{
17069         p->mallocFailed = 1;
17070         sqlite3StrAccumReset(p);
17071         return;
17072       }
17073     }
17074   }
17075   memcpy(&p->zText[p->nChar], z, N);
17076   p->nChar += N;
17077 }
17078
17079 /*
17080 ** Finish off a string by making sure it is zero-terminated.
17081 ** Return a pointer to the resulting string.  Return a NULL
17082 ** pointer if any kind of error was encountered.
17083 */
17084 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
17085   if( p->zText ){
17086     p->zText[p->nChar] = 0;
17087     if( p->useMalloc && p->zText==p->zBase ){
17088       p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
17089       if( p->zText ){
17090         memcpy(p->zText, p->zBase, p->nChar+1);
17091       }else{
17092         p->mallocFailed = 1;
17093       }
17094     }
17095   }
17096   return p->zText;
17097 }
17098
17099 /*
17100 ** Reset an StrAccum string.  Reclaim all malloced memory.
17101 */
17102 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
17103   if( p->zText!=p->zBase ){
17104     sqlite3DbFree(p->db, p->zText);
17105   }
17106   p->zText = 0;
17107 }
17108
17109 /*
17110 ** Initialize a string accumulator
17111 */
17112 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
17113   p->zText = p->zBase = zBase;
17114   p->db = 0;
17115   p->nChar = 0;
17116   p->nAlloc = n;
17117   p->mxAlloc = mx;
17118   p->useMalloc = 1;
17119   p->tooBig = 0;
17120   p->mallocFailed = 0;
17121 }
17122
17123 /*
17124 ** Print into memory obtained from sqliteMalloc().  Use the internal
17125 ** %-conversion extensions.
17126 */
17127 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
17128   char *z;
17129   char zBase[SQLITE_PRINT_BUF_SIZE];
17130   StrAccum acc;
17131   assert( db!=0 );
17132   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
17133                       db->aLimit[SQLITE_LIMIT_LENGTH]);
17134   acc.db = db;
17135   sqlite3VXPrintf(&acc, 1, zFormat, ap);
17136   z = sqlite3StrAccumFinish(&acc);
17137   if( acc.mallocFailed ){
17138     db->mallocFailed = 1;
17139   }
17140   return z;
17141 }
17142
17143 /*
17144 ** Print into memory obtained from sqliteMalloc().  Use the internal
17145 ** %-conversion extensions.
17146 */
17147 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
17148   va_list ap;
17149   char *z;
17150   va_start(ap, zFormat);
17151   z = sqlite3VMPrintf(db, zFormat, ap);
17152   va_end(ap);
17153   return z;
17154 }
17155
17156 /*
17157 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
17158 ** the string and before returnning.  This routine is intended to be used
17159 ** to modify an existing string.  For example:
17160 **
17161 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
17162 **
17163 */
17164 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
17165   va_list ap;
17166   char *z;
17167   va_start(ap, zFormat);
17168   z = sqlite3VMPrintf(db, zFormat, ap);
17169   va_end(ap);
17170   sqlite3DbFree(db, zStr);
17171   return z;
17172 }
17173
17174 /*
17175 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
17176 ** %-conversion extensions.
17177 */
17178 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
17179   char *z;
17180   char zBase[SQLITE_PRINT_BUF_SIZE];
17181   StrAccum acc;
17182 #ifndef SQLITE_OMIT_AUTOINIT
17183   if( sqlite3_initialize() ) return 0;
17184 #endif
17185   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
17186   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17187   z = sqlite3StrAccumFinish(&acc);
17188   return z;
17189 }
17190
17191 /*
17192 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
17193 ** %-conversion extensions.
17194 */
17195 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
17196   va_list ap;
17197   char *z;
17198 #ifndef SQLITE_OMIT_AUTOINIT
17199   if( sqlite3_initialize() ) return 0;
17200 #endif
17201   va_start(ap, zFormat);
17202   z = sqlite3_vmprintf(zFormat, ap);
17203   va_end(ap);
17204   return z;
17205 }
17206
17207 /*
17208 ** sqlite3_snprintf() works like snprintf() except that it ignores the
17209 ** current locale settings.  This is important for SQLite because we
17210 ** are not able to use a "," as the decimal point in place of "." as
17211 ** specified by some locales.
17212 */
17213 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
17214   char *z;
17215   va_list ap;
17216   StrAccum acc;
17217
17218   if( n<=0 ){
17219     return zBuf;
17220   }
17221   sqlite3StrAccumInit(&acc, zBuf, n, 0);
17222   acc.useMalloc = 0;
17223   va_start(ap,zFormat);
17224   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17225   va_end(ap);
17226   z = sqlite3StrAccumFinish(&acc);
17227   return z;
17228 }
17229
17230 #if defined(SQLITE_DEBUG)
17231 /*
17232 ** A version of printf() that understands %lld.  Used for debugging.
17233 ** The printf() built into some versions of windows does not understand %lld
17234 ** and segfaults if you give it a long long int.
17235 */
17236 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
17237   va_list ap;
17238   StrAccum acc;
17239   char zBuf[500];
17240   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
17241   acc.useMalloc = 0;
17242   va_start(ap,zFormat);
17243   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17244   va_end(ap);
17245   sqlite3StrAccumFinish(&acc);
17246   fprintf(stdout,"%s", zBuf);
17247   fflush(stdout);
17248 }
17249 #endif
17250
17251 #ifndef SQLITE_OMIT_TRACE
17252 /*
17253 ** variable-argument wrapper around sqlite3VXPrintf().
17254 */
17255 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
17256   va_list ap;
17257   va_start(ap,zFormat);
17258   sqlite3VXPrintf(p, 1, zFormat, ap);
17259   va_end(ap);
17260 }
17261 #endif
17262
17263 /************** End of printf.c **********************************************/
17264 /************** Begin file random.c ******************************************/
17265 /*
17266 ** 2001 September 15
17267 **
17268 ** The author disclaims copyright to this source code.  In place of
17269 ** a legal notice, here is a blessing:
17270 **
17271 **    May you do good and not evil.
17272 **    May you find forgiveness for yourself and forgive others.
17273 **    May you share freely, never taking more than you give.
17274 **
17275 *************************************************************************
17276 ** This file contains code to implement a pseudo-random number
17277 ** generator (PRNG) for SQLite.
17278 **
17279 ** Random numbers are used by some of the database backends in order
17280 ** to generate random integer keys for tables or random filenames.
17281 */
17282
17283
17284 /* All threads share a single random number generator.
17285 ** This structure is the current state of the generator.
17286 */
17287 static SQLITE_WSD struct sqlite3PrngType {
17288   unsigned char isInit;          /* True if initialized */
17289   unsigned char i, j;            /* State variables */
17290   unsigned char s[256];          /* State variables */
17291 } sqlite3Prng;
17292
17293 /*
17294 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
17295 ** must be held while executing this routine.
17296 **
17297 ** Why not just use a library random generator like lrand48() for this?
17298 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
17299 ** good source of random numbers.  The lrand48() library function may
17300 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
17301 ** subtle problems on some systems that could cause problems.  It is hard
17302 ** to know.  To minimize the risk of problems due to bad lrand48()
17303 ** implementations, SQLite uses this random number generator based
17304 ** on RC4, which we know works very well.
17305 **
17306 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
17307 ** randomness any more.  But we will leave this code in all the same.
17308 */
17309 static u8 randomByte(void){
17310   unsigned char t;
17311
17312
17313   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
17314   ** state vector.  If writable static data is unsupported on the target,
17315   ** we have to locate the state vector at run-time.  In the more common
17316   ** case where writable static data is supported, wsdPrng can refer directly
17317   ** to the "sqlite3Prng" state vector declared above.
17318   */
17319 #ifdef SQLITE_OMIT_WSD
17320   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
17321 # define wsdPrng p[0]
17322 #else
17323 # define wsdPrng sqlite3Prng
17324 #endif
17325
17326
17327   /* Initialize the state of the random number generator once,
17328   ** the first time this routine is called.  The seed value does
17329   ** not need to contain a lot of randomness since we are not
17330   ** trying to do secure encryption or anything like that...
17331   **
17332   ** Nothing in this file or anywhere else in SQLite does any kind of
17333   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
17334   ** number generator) not as an encryption device.
17335   */
17336   if( !wsdPrng.isInit ){
17337     int i;
17338     char k[256];
17339     wsdPrng.j = 0;
17340     wsdPrng.i = 0;
17341     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
17342     for(i=0; i<256; i++){
17343       wsdPrng.s[i] = (u8)i;
17344     }
17345     for(i=0; i<256; i++){
17346       wsdPrng.j += wsdPrng.s[i] + k[i];
17347       t = wsdPrng.s[wsdPrng.j];
17348       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
17349       wsdPrng.s[i] = t;
17350     }
17351     wsdPrng.isInit = 1;
17352   }
17353
17354   /* Generate and return single random byte
17355   */
17356   wsdPrng.i++;
17357   t = wsdPrng.s[wsdPrng.i];
17358   wsdPrng.j += t;
17359   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
17360   wsdPrng.s[wsdPrng.j] = t;
17361   t += wsdPrng.s[wsdPrng.i];
17362   return wsdPrng.s[t];
17363 }
17364
17365 /*
17366 ** Return N random bytes.
17367 */
17368 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
17369   unsigned char *zBuf = pBuf;
17370 #if SQLITE_THREADSAFE
17371   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
17372 #endif
17373   sqlite3_mutex_enter(mutex);
17374   while( N-- ){
17375     *(zBuf++) = randomByte();
17376   }
17377   sqlite3_mutex_leave(mutex);
17378 }
17379
17380 #ifndef SQLITE_OMIT_BUILTIN_TEST
17381 /*
17382 ** For testing purposes, we sometimes want to preserve the state of
17383 ** PRNG and restore the PRNG to its saved state at a later time, or
17384 ** to reset the PRNG to its initial state.  These routines accomplish
17385 ** those tasks.
17386 **
17387 ** The sqlite3_test_control() interface calls these routines to
17388 ** control the PRNG.
17389 */
17390 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
17391 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
17392   memcpy(
17393     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17394     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17395     sizeof(sqlite3Prng)
17396   );
17397 }
17398 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
17399   memcpy(
17400     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17401     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17402     sizeof(sqlite3Prng)
17403   );
17404 }
17405 SQLITE_PRIVATE void sqlite3PrngResetState(void){
17406   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
17407 }
17408 #endif /* SQLITE_OMIT_BUILTIN_TEST */
17409
17410 /************** End of random.c **********************************************/
17411 /************** Begin file utf.c *********************************************/
17412 /*
17413 ** 2004 April 13
17414 **
17415 ** The author disclaims copyright to this source code.  In place of
17416 ** a legal notice, here is a blessing:
17417 **
17418 **    May you do good and not evil.
17419 **    May you find forgiveness for yourself and forgive others.
17420 **    May you share freely, never taking more than you give.
17421 **
17422 *************************************************************************
17423 ** This file contains routines used to translate between UTF-8, 
17424 ** UTF-16, UTF-16BE, and UTF-16LE.
17425 **
17426 ** Notes on UTF-8:
17427 **
17428 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
17429 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
17430 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
17431 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
17432 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
17433 **
17434 **
17435 ** Notes on UTF-16:  (with wwww+1==uuuuu)
17436 **
17437 **      Word-0               Word-1          Value
17438 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
17439 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
17440 **
17441 **
17442 ** BOM or Byte Order Mark:
17443 **     0xff 0xfe   little-endian utf-16 follows
17444 **     0xfe 0xff   big-endian utf-16 follows
17445 **
17446 */
17447 /************** Include vdbeInt.h in the middle of utf.c *********************/
17448 /************** Begin file vdbeInt.h *****************************************/
17449 /*
17450 ** 2003 September 6
17451 **
17452 ** The author disclaims copyright to this source code.  In place of
17453 ** a legal notice, here is a blessing:
17454 **
17455 **    May you do good and not evil.
17456 **    May you find forgiveness for yourself and forgive others.
17457 **    May you share freely, never taking more than you give.
17458 **
17459 *************************************************************************
17460 ** This is the header file for information that is private to the
17461 ** VDBE.  This information used to all be at the top of the single
17462 ** source code file "vdbe.c".  When that file became too big (over
17463 ** 6000 lines long) it was split up into several smaller files and
17464 ** this header information was factored out.
17465 */
17466 #ifndef _VDBEINT_H_
17467 #define _VDBEINT_H_
17468
17469 /*
17470 ** SQL is translated into a sequence of instructions to be
17471 ** executed by a virtual machine.  Each instruction is an instance
17472 ** of the following structure.
17473 */
17474 typedef struct VdbeOp Op;
17475
17476 /*
17477 ** Boolean values
17478 */
17479 typedef unsigned char Bool;
17480
17481 /*
17482 ** A cursor is a pointer into a single BTree within a database file.
17483 ** The cursor can seek to a BTree entry with a particular key, or
17484 ** loop over all entries of the Btree.  You can also insert new BTree
17485 ** entries or retrieve the key or data from the entry that the cursor
17486 ** is currently pointing to.
17487 ** 
17488 ** Every cursor that the virtual machine has open is represented by an
17489 ** instance of the following structure.
17490 **
17491 ** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
17492 ** really a single row that represents the NEW or OLD pseudo-table of
17493 ** a row trigger.  The data for the row is stored in VdbeCursor.pData and
17494 ** the rowid is in VdbeCursor.iKey.
17495 */
17496 struct VdbeCursor {
17497   BtCursor *pCursor;    /* The cursor structure of the backend */
17498   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
17499   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
17500   Bool zeroed;          /* True if zeroed out and ready for reuse */
17501   Bool rowidIsValid;    /* True if lastRowid is valid */
17502   Bool atFirst;         /* True if pointing to first entry */
17503   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
17504   Bool nullRow;         /* True if pointing to a row with no data */
17505   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
17506   Bool isTable;         /* True if a table requiring integer keys */
17507   Bool isIndex;         /* True if an index containing keys only - no data */
17508   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
17509   Btree *pBt;           /* Separate file holding temporary table */
17510   int pseudoTableReg;   /* Register holding pseudotable content. */
17511   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
17512   int nField;           /* Number of fields in the header */
17513   i64 seqCount;         /* Sequence counter */
17514   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
17515   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
17516
17517   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or 
17518   ** OP_IsUnique opcode on this cursor. */
17519   int seekResult;
17520
17521   /* Cached information about the header for the data record that the
17522   ** cursor is currently pointing to.  Only valid if cacheStatus matches
17523   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
17524   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
17525   ** the cache is out of date.
17526   **
17527   ** aRow might point to (ephemeral) data for the current row, or it might
17528   ** be NULL.
17529   */
17530   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
17531   int payloadSize;      /* Total number of bytes in the record */
17532   u32 *aType;           /* Type values for all entries in the record */
17533   u32 *aOffset;         /* Cached offsets to the start of each columns data */
17534   u8 *aRow;             /* Data for the current row, if all on one page */
17535 };
17536 typedef struct VdbeCursor VdbeCursor;
17537
17538 /*
17539 ** When a sub-program is executed (OP_Program), a structure of this type
17540 ** is allocated to store the current value of the program counter, as
17541 ** well as the current memory cell array and various other frame specific
17542 ** values stored in the Vdbe struct. When the sub-program is finished, 
17543 ** these values are copied back to the Vdbe from the VdbeFrame structure,
17544 ** restoring the state of the VM to as it was before the sub-program
17545 ** began executing.
17546 **
17547 ** Frames are stored in a linked list headed at Vdbe.pParent. Vdbe.pParent
17548 ** is the parent of the current frame, or zero if the current frame
17549 ** is the main Vdbe program.
17550 */
17551 typedef struct VdbeFrame VdbeFrame;
17552 struct VdbeFrame {
17553   Vdbe *v;                /* VM this frame belongs to */
17554   int pc;                 /* Program Counter */
17555   Op *aOp;                /* Program instructions */
17556   int nOp;                /* Size of aOp array */
17557   Mem *aMem;              /* Array of memory cells */
17558   int nMem;               /* Number of entries in aMem */
17559   VdbeCursor **apCsr;     /* Element of Vdbe cursors */
17560   u16 nCursor;            /* Number of entries in apCsr */
17561   void *token;            /* Copy of SubProgram.token */
17562   int nChildMem;          /* Number of memory cells for child frame */
17563   int nChildCsr;          /* Number of cursors for child frame */
17564   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
17565   int nChange;            /* Statement changes (Vdbe.nChanges)     */
17566   VdbeFrame *pParent;     /* Parent of this frame */
17567 };
17568
17569 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
17570
17571 /*
17572 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
17573 */
17574 #define CACHE_STALE 0
17575
17576 /*
17577 ** Internally, the vdbe manipulates nearly all SQL values as Mem
17578 ** structures. Each Mem struct may cache multiple representations (string,
17579 ** integer etc.) of the same value.  A value (and therefore Mem structure)
17580 ** has the following properties:
17581 **
17582 ** Each value has a manifest type. The manifest type of the value stored
17583 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
17584 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
17585 ** SQLITE_BLOB.
17586 */
17587 struct Mem {
17588   union {
17589     i64 i;              /* Integer value. */
17590     int nZero;          /* Used when bit MEM_Zero is set in flags */
17591     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
17592     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
17593     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
17594   } u;
17595   double r;           /* Real value */
17596   sqlite3 *db;        /* The associated database connection */
17597   char *z;            /* String or BLOB value */
17598   int n;              /* Number of characters in string value, excluding '\0' */
17599   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
17600   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
17601   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
17602   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
17603   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
17604 };
17605
17606 /* One or more of the following flags are set to indicate the validOK
17607 ** representations of the value stored in the Mem struct.
17608 **
17609 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
17610 ** No other flags may be set in this case.
17611 **
17612 ** If the MEM_Str flag is set then Mem.z points at a string representation.
17613 ** Usually this is encoded in the same unicode encoding as the main
17614 ** database (see below for exceptions). If the MEM_Term flag is also
17615 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
17616 ** flags may coexist with the MEM_Str flag.
17617 **
17618 ** Multiple of these values can appear in Mem.flags.  But only one
17619 ** at a time can appear in Mem.type.
17620 */
17621 #define MEM_Null      0x0001   /* Value is NULL */
17622 #define MEM_Str       0x0002   /* Value is a string */
17623 #define MEM_Int       0x0004   /* Value is an integer */
17624 #define MEM_Real      0x0008   /* Value is a real number */
17625 #define MEM_Blob      0x0010   /* Value is a BLOB */
17626 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
17627 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
17628 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
17629
17630 /* Whenever Mem contains a valid string or blob representation, one of
17631 ** the following flags must be set to determine the memory management
17632 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
17633 ** string is \000 or \u0000 terminated
17634 */
17635 #define MEM_Term      0x0200   /* String rep is nul terminated */
17636 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
17637 #define MEM_Static    0x0800   /* Mem.z points to a static string */
17638 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
17639 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
17640 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
17641
17642 #ifdef SQLITE_OMIT_INCRBLOB
17643   #undef MEM_Zero
17644   #define MEM_Zero 0x0000
17645 #endif
17646
17647
17648 /*
17649 ** Clear any existing type flags from a Mem and replace them with f
17650 */
17651 #define MemSetTypeFlag(p, f) \
17652    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
17653
17654
17655 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
17656 ** additional information about auxiliary information bound to arguments
17657 ** of the function.  This is used to implement the sqlite3_get_auxdata()
17658 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
17659 ** that can be associated with a constant argument to a function.  This
17660 ** allows functions such as "regexp" to compile their constant regular
17661 ** expression argument once and reused the compiled code for multiple
17662 ** invocations.
17663 */
17664 struct VdbeFunc {
17665   FuncDef *pFunc;               /* The definition of the function */
17666   int nAux;                     /* Number of entries allocated for apAux[] */
17667   struct AuxData {
17668     void *pAux;                   /* Aux data for the i-th argument */
17669     void (*xDelete)(void *);      /* Destructor for the aux data */
17670   } apAux[1];                   /* One slot for each function argument */
17671 };
17672
17673 /*
17674 ** The "context" argument for a installable function.  A pointer to an
17675 ** instance of this structure is the first argument to the routines used
17676 ** implement the SQL functions.
17677 **
17678 ** There is a typedef for this structure in sqlite.h.  So all routines,
17679 ** even the public interface to SQLite, can use a pointer to this structure.
17680 ** But this file is the only place where the internal details of this
17681 ** structure are known.
17682 **
17683 ** This structure is defined inside of vdbeInt.h because it uses substructures
17684 ** (Mem) which are only defined there.
17685 */
17686 struct sqlite3_context {
17687   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
17688   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
17689   Mem s;                /* The return value is stored here */
17690   Mem *pMem;            /* Memory cell used to store aggregate context */
17691   int isError;          /* Error code returned by the function. */
17692   CollSeq *pColl;       /* Collating sequence */
17693 };
17694
17695 /*
17696 ** A Set structure is used for quick testing to see if a value
17697 ** is part of a small set.  Sets are used to implement code like
17698 ** this:
17699 **            x.y IN ('hi','hoo','hum')
17700 */
17701 typedef struct Set Set;
17702 struct Set {
17703   Hash hash;             /* A set is just a hash table */
17704   HashElem *prev;        /* Previously accessed hash elemen */
17705 };
17706
17707 /*
17708 ** An instance of the virtual machine.  This structure contains the complete
17709 ** state of the virtual machine.
17710 **
17711 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
17712 ** is really a pointer to an instance of this structure.
17713 **
17714 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
17715 ** any virtual table method invocations made by the vdbe program. It is
17716 ** set to 2 for xDestroy method calls and 1 for all other methods. This
17717 ** variable is used for two purposes: to allow xDestroy methods to execute
17718 ** "DROP TABLE" statements and to prevent some nasty side effects of
17719 ** malloc failure when SQLite is invoked recursively by a virtual table 
17720 ** method function.
17721 */
17722 struct Vdbe {
17723   sqlite3 *db;            /* The database connection that owns this statement */
17724   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
17725   int nOp;                /* Number of instructions in the program */
17726   int nOpAlloc;           /* Number of slots allocated for aOp[] */
17727   Op *aOp;                /* Space to hold the virtual machine's program */
17728   int nLabel;             /* Number of labels used */
17729   int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
17730   int *aLabel;            /* Space to hold the labels */
17731   Mem **apArg;            /* Arguments to currently executing user function */
17732   Mem *aColName;          /* Column names to return */
17733   Mem *pResultSet;        /* Pointer to an array of results */
17734   u16 nResColumn;         /* Number of columns in one row of the result set */
17735   u16 nCursor;            /* Number of slots in apCsr[] */
17736   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
17737   u8 errorAction;         /* Recovery action to do in case of an error */
17738   u8 okVar;               /* True if azVar[] has been initialized */
17739   ynVar nVar;             /* Number of entries in aVar[] */
17740   Mem *aVar;              /* Values for the OP_Variable opcode. */
17741   char **azVar;           /* Name of variables */
17742   u32 magic;              /* Magic number for sanity checking */
17743   int nMem;               /* Number of memory locations currently allocated */
17744   Mem *aMem;              /* The memory locations */
17745   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
17746   int pc;                 /* The program counter */
17747   int rc;                 /* Value to return */
17748   char *zErrMsg;          /* Error message written here */
17749   u8 explain;             /* True if EXPLAIN present on SQL command */
17750   u8 changeCntOn;         /* True to update the change-counter */
17751   u8 expired;             /* True if the VM needs to be recompiled */
17752   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
17753   u8 inVtabMethod;        /* See comments above */
17754   u8 usesStmtJournal;     /* True if uses a statement journal */
17755   u8 readOnly;            /* True for read-only statements */
17756   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
17757   int nChange;            /* Number of db changes made since last reset */
17758   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
17759   i64 startTime;          /* Time when query started - used for profiling */
17760   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
17761   int aCounter[2];        /* Counters used by sqlite3_stmt_status() */
17762   char *zSql;             /* Text of the SQL statement that generated this */
17763   void *pFree;            /* Free this when deleting the vdbe */
17764   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
17765   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
17766   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
17767 #ifdef SQLITE_DEBUG
17768   FILE *trace;            /* Write an execution trace here, if not NULL */
17769 #endif
17770   VdbeFrame *pFrame;      /* Parent frame */
17771   int nFrame;             /* Number of frames in pFrame list */
17772   u32 expmask;            /* Binding to these vars invalidates VM */
17773 };
17774
17775 /*
17776 ** The following are allowed values for Vdbe.magic
17777 */
17778 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
17779 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
17780 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
17781 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
17782
17783 /*
17784 ** Function prototypes
17785 */
17786 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
17787 void sqliteVdbePopStack(Vdbe*,int);
17788 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
17789 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
17790 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
17791 #endif
17792 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
17793 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
17794 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
17795 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
17796 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
17797
17798 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
17799 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
17800 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
17801 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
17802 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
17803 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
17804 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
17805 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
17806 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
17807 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
17808 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
17809 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
17810 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
17811 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
17812 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
17813 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
17814 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
17815 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
17816 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
17817 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
17818 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
17819 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
17820 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
17821 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
17822 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
17823 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
17824 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
17825 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
17826 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
17827 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
17828 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
17829 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
17830 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
17831 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
17832 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
17833 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
17834 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
17835
17836 #ifndef SQLITE_OMIT_FOREIGN_KEY
17837 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
17838 #else
17839 # define sqlite3VdbeCheckFk(p,i) 0
17840 #endif
17841
17842 #ifndef SQLITE_OMIT_SHARED_CACHE
17843 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p);
17844 #else
17845 # define sqlite3VdbeMutexArrayEnter(p)
17846 #endif
17847
17848 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
17849 #ifdef SQLITE_DEBUG
17850 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
17851 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
17852 #endif
17853 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
17854
17855 #ifndef SQLITE_OMIT_INCRBLOB
17856 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
17857 #else
17858   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
17859 #endif
17860
17861 #endif /* !defined(_VDBEINT_H_) */
17862
17863 /************** End of vdbeInt.h *********************************************/
17864 /************** Continuing where we left off in utf.c ************************/
17865
17866 #ifndef SQLITE_AMALGAMATION
17867 /*
17868 ** The following constant value is used by the SQLITE_BIGENDIAN and
17869 ** SQLITE_LITTLEENDIAN macros.
17870 */
17871 SQLITE_PRIVATE const int sqlite3one = 1;
17872 #endif /* SQLITE_AMALGAMATION */
17873
17874 /*
17875 ** This lookup table is used to help decode the first byte of
17876 ** a multi-byte UTF8 character.
17877 */
17878 static const unsigned char sqlite3Utf8Trans1[] = {
17879   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17880   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
17881   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
17882   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
17883   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17884   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
17885   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17886   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
17887 };
17888
17889
17890 #define WRITE_UTF8(zOut, c) {                          \
17891   if( c<0x00080 ){                                     \
17892     *zOut++ = (u8)(c&0xFF);                            \
17893   }                                                    \
17894   else if( c<0x00800 ){                                \
17895     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
17896     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
17897   }                                                    \
17898   else if( c<0x10000 ){                                \
17899     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
17900     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
17901     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
17902   }else{                                               \
17903     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
17904     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
17905     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
17906     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
17907   }                                                    \
17908 }
17909
17910 #define WRITE_UTF16LE(zOut, c) {                                    \
17911   if( c<=0xFFFF ){                                                  \
17912     *zOut++ = (u8)(c&0x00FF);                                       \
17913     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
17914   }else{                                                            \
17915     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
17916     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
17917     *zOut++ = (u8)(c&0x00FF);                                       \
17918     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
17919   }                                                                 \
17920 }
17921
17922 #define WRITE_UTF16BE(zOut, c) {                                    \
17923   if( c<=0xFFFF ){                                                  \
17924     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
17925     *zOut++ = (u8)(c&0x00FF);                                       \
17926   }else{                                                            \
17927     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
17928     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
17929     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
17930     *zOut++ = (u8)(c&0x00FF);                                       \
17931   }                                                                 \
17932 }
17933
17934 #define READ_UTF16LE(zIn, TERM, c){                                   \
17935   c = (*zIn++);                                                       \
17936   c += ((*zIn++)<<8);                                                 \
17937   if( c>=0xD800 && c<0xE000 && TERM ){                                \
17938     int c2 = (*zIn++);                                                \
17939     c2 += ((*zIn++)<<8);                                              \
17940     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
17941   }                                                                   \
17942 }
17943
17944 #define READ_UTF16BE(zIn, TERM, c){                                   \
17945   c = ((*zIn++)<<8);                                                  \
17946   c += (*zIn++);                                                      \
17947   if( c>=0xD800 && c<0xE000 && TERM ){                                \
17948     int c2 = ((*zIn++)<<8);                                           \
17949     c2 += (*zIn++);                                                   \
17950     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
17951   }                                                                   \
17952 }
17953
17954 /*
17955 ** Translate a single UTF-8 character.  Return the unicode value.
17956 **
17957 ** During translation, assume that the byte that zTerm points
17958 ** is a 0x00.
17959 **
17960 ** Write a pointer to the next unread byte back into *pzNext.
17961 **
17962 ** Notes On Invalid UTF-8:
17963 **
17964 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
17965 **     be encoded as a multi-byte character.  Any multi-byte character that
17966 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
17967 **
17968 **  *  This routine never allows a UTF16 surrogate value to be encoded.
17969 **     If a multi-byte character attempts to encode a value between
17970 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
17971 **
17972 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
17973 **     byte of a character are interpreted as single-byte characters
17974 **     and rendered as themselves even though they are technically
17975 **     invalid characters.
17976 **
17977 **  *  This routine accepts an infinite number of different UTF8 encodings
17978 **     for unicode values 0x80 and greater.  It do not change over-length
17979 **     encodings to 0xfffd as some systems recommend.
17980 */
17981 #define READ_UTF8(zIn, zTerm, c)                           \
17982   c = *(zIn++);                                            \
17983   if( c>=0xc0 ){                                           \
17984     c = sqlite3Utf8Trans1[c-0xc0];                         \
17985     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
17986       c = (c<<6) + (0x3f & *(zIn++));                      \
17987     }                                                      \
17988     if( c<0x80                                             \
17989         || (c&0xFFFFF800)==0xD800                          \
17990         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
17991   }
17992 SQLITE_PRIVATE int sqlite3Utf8Read(
17993   const unsigned char *zIn,       /* First byte of UTF-8 character */
17994   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
17995 ){
17996   int c;
17997
17998   /* Same as READ_UTF8() above but without the zTerm parameter.
17999   ** For this routine, we assume the UTF8 string is always zero-terminated.
18000   */
18001   c = *(zIn++);
18002   if( c>=0xc0 ){
18003     c = sqlite3Utf8Trans1[c-0xc0];
18004     while( (*zIn & 0xc0)==0x80 ){
18005       c = (c<<6) + (0x3f & *(zIn++));
18006     }
18007     if( c<0x80
18008         || (c&0xFFFFF800)==0xD800
18009         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
18010   }
18011   *pzNext = zIn;
18012   return c;
18013 }
18014
18015
18016
18017
18018 /*
18019 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
18020 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
18021 */ 
18022 /* #define TRANSLATE_TRACE 1 */
18023
18024 #ifndef SQLITE_OMIT_UTF16
18025 /*
18026 ** This routine transforms the internal text encoding used by pMem to
18027 ** desiredEnc. It is an error if the string is already of the desired
18028 ** encoding, or if *pMem does not contain a string value.
18029 */
18030 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
18031   int len;                    /* Maximum length of output string in bytes */
18032   unsigned char *zOut;                  /* Output buffer */
18033   unsigned char *zIn;                   /* Input iterator */
18034   unsigned char *zTerm;                 /* End of input */
18035   unsigned char *z;                     /* Output iterator */
18036   unsigned int c;
18037
18038   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
18039   assert( pMem->flags&MEM_Str );
18040   assert( pMem->enc!=desiredEnc );
18041   assert( pMem->enc!=0 );
18042   assert( pMem->n>=0 );
18043
18044 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18045   {
18046     char zBuf[100];
18047     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18048     fprintf(stderr, "INPUT:  %s\n", zBuf);
18049   }
18050 #endif
18051
18052   /* If the translation is between UTF-16 little and big endian, then 
18053   ** all that is required is to swap the byte order. This case is handled
18054   ** differently from the others.
18055   */
18056   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
18057     u8 temp;
18058     int rc;
18059     rc = sqlite3VdbeMemMakeWriteable(pMem);
18060     if( rc!=SQLITE_OK ){
18061       assert( rc==SQLITE_NOMEM );
18062       return SQLITE_NOMEM;
18063     }
18064     zIn = (u8*)pMem->z;
18065     zTerm = &zIn[pMem->n&~1];
18066     while( zIn<zTerm ){
18067       temp = *zIn;
18068       *zIn = *(zIn+1);
18069       zIn++;
18070       *zIn++ = temp;
18071     }
18072     pMem->enc = desiredEnc;
18073     goto translate_out;
18074   }
18075
18076   /* Set len to the maximum number of bytes required in the output buffer. */
18077   if( desiredEnc==SQLITE_UTF8 ){
18078     /* When converting from UTF-16, the maximum growth results from
18079     ** translating a 2-byte character to a 4-byte UTF-8 character.
18080     ** A single byte is required for the output string
18081     ** nul-terminator.
18082     */
18083     pMem->n &= ~1;
18084     len = pMem->n * 2 + 1;
18085   }else{
18086     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
18087     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
18088     ** character. Two bytes are required in the output buffer for the
18089     ** nul-terminator.
18090     */
18091     len = pMem->n * 2 + 2;
18092   }
18093
18094   /* Set zIn to point at the start of the input buffer and zTerm to point 1
18095   ** byte past the end.
18096   **
18097   ** Variable zOut is set to point at the output buffer, space obtained
18098   ** from sqlite3_malloc().
18099   */
18100   zIn = (u8*)pMem->z;
18101   zTerm = &zIn[pMem->n];
18102   zOut = sqlite3DbMallocRaw(pMem->db, len);
18103   if( !zOut ){
18104     return SQLITE_NOMEM;
18105   }
18106   z = zOut;
18107
18108   if( pMem->enc==SQLITE_UTF8 ){
18109     if( desiredEnc==SQLITE_UTF16LE ){
18110       /* UTF-8 -> UTF-16 Little-endian */
18111       while( zIn<zTerm ){
18112         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18113         READ_UTF8(zIn, zTerm, c);
18114         WRITE_UTF16LE(z, c);
18115       }
18116     }else{
18117       assert( desiredEnc==SQLITE_UTF16BE );
18118       /* UTF-8 -> UTF-16 Big-endian */
18119       while( zIn<zTerm ){
18120         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18121         READ_UTF8(zIn, zTerm, c);
18122         WRITE_UTF16BE(z, c);
18123       }
18124     }
18125     pMem->n = (int)(z - zOut);
18126     *z++ = 0;
18127   }else{
18128     assert( desiredEnc==SQLITE_UTF8 );
18129     if( pMem->enc==SQLITE_UTF16LE ){
18130       /* UTF-16 Little-endian -> UTF-8 */
18131       while( zIn<zTerm ){
18132         READ_UTF16LE(zIn, zIn<zTerm, c); 
18133         WRITE_UTF8(z, c);
18134       }
18135     }else{
18136       /* UTF-16 Big-endian -> UTF-8 */
18137       while( zIn<zTerm ){
18138         READ_UTF16BE(zIn, zIn<zTerm, c); 
18139         WRITE_UTF8(z, c);
18140       }
18141     }
18142     pMem->n = (int)(z - zOut);
18143   }
18144   *z = 0;
18145   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
18146
18147   sqlite3VdbeMemRelease(pMem);
18148   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
18149   pMem->enc = desiredEnc;
18150   pMem->flags |= (MEM_Term|MEM_Dyn);
18151   pMem->z = (char*)zOut;
18152   pMem->zMalloc = pMem->z;
18153
18154 translate_out:
18155 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18156   {
18157     char zBuf[100];
18158     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18159     fprintf(stderr, "OUTPUT: %s\n", zBuf);
18160   }
18161 #endif
18162   return SQLITE_OK;
18163 }
18164
18165 /*
18166 ** This routine checks for a byte-order mark at the beginning of the 
18167 ** UTF-16 string stored in *pMem. If one is present, it is removed and
18168 ** the encoding of the Mem adjusted. This routine does not do any
18169 ** byte-swapping, it just sets Mem.enc appropriately.
18170 **
18171 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
18172 ** changed by this function.
18173 */
18174 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
18175   int rc = SQLITE_OK;
18176   u8 bom = 0;
18177
18178   assert( pMem->n>=0 );
18179   if( pMem->n>1 ){
18180     u8 b1 = *(u8 *)pMem->z;
18181     u8 b2 = *(((u8 *)pMem->z) + 1);
18182     if( b1==0xFE && b2==0xFF ){
18183       bom = SQLITE_UTF16BE;
18184     }
18185     if( b1==0xFF && b2==0xFE ){
18186       bom = SQLITE_UTF16LE;
18187     }
18188   }
18189   
18190   if( bom ){
18191     rc = sqlite3VdbeMemMakeWriteable(pMem);
18192     if( rc==SQLITE_OK ){
18193       pMem->n -= 2;
18194       memmove(pMem->z, &pMem->z[2], pMem->n);
18195       pMem->z[pMem->n] = '\0';
18196       pMem->z[pMem->n+1] = '\0';
18197       pMem->flags |= MEM_Term;
18198       pMem->enc = bom;
18199     }
18200   }
18201   return rc;
18202 }
18203 #endif /* SQLITE_OMIT_UTF16 */
18204
18205 /*
18206 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
18207 ** return the number of unicode characters in pZ up to (but not including)
18208 ** the first 0x00 byte. If nByte is not less than zero, return the
18209 ** number of unicode characters in the first nByte of pZ (or up to 
18210 ** the first 0x00, whichever comes first).
18211 */
18212 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
18213   int r = 0;
18214   const u8 *z = (const u8*)zIn;
18215   const u8 *zTerm;
18216   if( nByte>=0 ){
18217     zTerm = &z[nByte];
18218   }else{
18219     zTerm = (const u8*)(-1);
18220   }
18221   assert( z<=zTerm );
18222   while( *z!=0 && z<zTerm ){
18223     SQLITE_SKIP_UTF8(z);
18224     r++;
18225   }
18226   return r;
18227 }
18228
18229 /* This test function is not currently used by the automated test-suite. 
18230 ** Hence it is only available in debug builds.
18231 */
18232 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
18233 /*
18234 ** Translate UTF-8 to UTF-8.
18235 **
18236 ** This has the effect of making sure that the string is well-formed
18237 ** UTF-8.  Miscoded characters are removed.
18238 **
18239 ** The translation is done in-place (since it is impossible for the
18240 ** correct UTF-8 encoding to be longer than a malformed encoding).
18241 */
18242 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
18243   unsigned char *zOut = zIn;
18244   unsigned char *zStart = zIn;
18245   u32 c;
18246
18247   while( zIn[0] ){
18248     c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
18249     if( c!=0xfffd ){
18250       WRITE_UTF8(zOut, c);
18251     }
18252   }
18253   *zOut = 0;
18254   return (int)(zOut - zStart);
18255 }
18256 #endif
18257
18258 #ifndef SQLITE_OMIT_UTF16
18259 /*
18260 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
18261 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
18262 ** be freed by the calling function.
18263 **
18264 ** NULL is returned if there is an allocation error.
18265 */
18266 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
18267   Mem m;
18268   memset(&m, 0, sizeof(m));
18269   m.db = db;
18270   sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
18271   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
18272   if( db->mallocFailed ){
18273     sqlite3VdbeMemRelease(&m);
18274     m.z = 0;
18275   }
18276   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
18277   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
18278   return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
18279 }
18280
18281 /*
18282 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
18283 ** enc. A pointer to the new string is returned, and the value of *pnOut
18284 ** is set to the length of the returned string in bytes. The call should
18285 ** arrange to call sqlite3DbFree() on the returned pointer when it is
18286 ** no longer required.
18287 ** 
18288 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
18289 ** flag set.
18290 */
18291 #ifdef SQLITE_ENABLE_STAT2
18292 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
18293   Mem m;
18294   memset(&m, 0, sizeof(m));
18295   m.db = db;
18296   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
18297   if( sqlite3VdbeMemTranslate(&m, enc) ){
18298     assert( db->mallocFailed );
18299     return 0;
18300   }
18301   assert( m.z==m.zMalloc );
18302   *pnOut = m.n;
18303   return m.z;
18304 }
18305 #endif
18306
18307 /*
18308 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
18309 ** Return the number of bytes in the first nChar unicode characters
18310 ** in pZ.  nChar must be non-negative.
18311 */
18312 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
18313   int c;
18314   unsigned char const *z = zIn;
18315   int n = 0;
18316   
18317   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
18318     while( n<nChar ){
18319       READ_UTF16BE(z, 1, c);
18320       n++;
18321     }
18322   }else{
18323     while( n<nChar ){
18324       READ_UTF16LE(z, 1, c);
18325       n++;
18326     }
18327   }
18328   return (int)(z-(unsigned char const *)zIn);
18329 }
18330
18331 #if defined(SQLITE_TEST)
18332 /*
18333 ** This routine is called from the TCL test function "translate_selftest".
18334 ** It checks that the primitives for serializing and deserializing
18335 ** characters in each encoding are inverses of each other.
18336 */
18337 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
18338   unsigned int i, t;
18339   unsigned char zBuf[20];
18340   unsigned char *z;
18341   int n;
18342   unsigned int c;
18343
18344   for(i=0; i<0x00110000; i++){
18345     z = zBuf;
18346     WRITE_UTF8(z, i);
18347     n = (int)(z-zBuf);
18348     assert( n>0 && n<=4 );
18349     z[0] = 0;
18350     z = zBuf;
18351     c = sqlite3Utf8Read(z, (const u8**)&z);
18352     t = i;
18353     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
18354     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
18355     assert( c==t );
18356     assert( (z-zBuf)==n );
18357   }
18358   for(i=0; i<0x00110000; i++){
18359     if( i>=0xD800 && i<0xE000 ) continue;
18360     z = zBuf;
18361     WRITE_UTF16LE(z, i);
18362     n = (int)(z-zBuf);
18363     assert( n>0 && n<=4 );
18364     z[0] = 0;
18365     z = zBuf;
18366     READ_UTF16LE(z, 1, c);
18367     assert( c==i );
18368     assert( (z-zBuf)==n );
18369   }
18370   for(i=0; i<0x00110000; i++){
18371     if( i>=0xD800 && i<0xE000 ) continue;
18372     z = zBuf;
18373     WRITE_UTF16BE(z, i);
18374     n = (int)(z-zBuf);
18375     assert( n>0 && n<=4 );
18376     z[0] = 0;
18377     z = zBuf;
18378     READ_UTF16BE(z, 1, c);
18379     assert( c==i );
18380     assert( (z-zBuf)==n );
18381   }
18382 }
18383 #endif /* SQLITE_TEST */
18384 #endif /* SQLITE_OMIT_UTF16 */
18385
18386 /************** End of utf.c *************************************************/
18387 /************** Begin file util.c ********************************************/
18388 /*
18389 ** 2001 September 15
18390 **
18391 ** The author disclaims copyright to this source code.  In place of
18392 ** a legal notice, here is a blessing:
18393 **
18394 **    May you do good and not evil.
18395 **    May you find forgiveness for yourself and forgive others.
18396 **    May you share freely, never taking more than you give.
18397 **
18398 *************************************************************************
18399 ** Utility functions used throughout sqlite.
18400 **
18401 ** This file contains functions for allocating memory, comparing
18402 ** strings, and stuff like that.
18403 **
18404 */
18405 #ifdef SQLITE_HAVE_ISNAN
18406 # include <math.h>
18407 #endif
18408
18409 /*
18410 ** Routine needed to support the testcase() macro.
18411 */
18412 #ifdef SQLITE_COVERAGE_TEST
18413 SQLITE_PRIVATE void sqlite3Coverage(int x){
18414   static int dummy = 0;
18415   dummy += x;
18416 }
18417 #endif
18418
18419 /*
18420 ** Return true if the floating point value is Not a Number (NaN).
18421 **
18422 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
18423 ** Otherwise, we have our own implementation that works on most systems.
18424 */
18425 SQLITE_PRIVATE int sqlite3IsNaN(double x){
18426   int rc;   /* The value return */
18427 #if !defined(SQLITE_HAVE_ISNAN)
18428   /*
18429   ** Systems that support the isnan() library function should probably
18430   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
18431   ** found that many systems do not have a working isnan() function so
18432   ** this implementation is provided as an alternative.
18433   **
18434   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
18435   ** On the other hand, the use of -ffast-math comes with the following
18436   ** warning:
18437   **
18438   **      This option [-ffast-math] should never be turned on by any
18439   **      -O option since it can result in incorrect output for programs
18440   **      which depend on an exact implementation of IEEE or ISO 
18441   **      rules/specifications for math functions.
18442   **
18443   ** Under MSVC, this NaN test may fail if compiled with a floating-
18444   ** point precision mode other than /fp:precise.  From the MSDN 
18445   ** documentation:
18446   **
18447   **      The compiler [with /fp:precise] will properly handle comparisons 
18448   **      involving NaN. For example, x != x evaluates to true if x is NaN 
18449   **      ...
18450   */
18451 #ifdef __FAST_MATH__
18452 # error SQLite will not work correctly with the -ffast-math option of GCC.
18453 #endif
18454   volatile double y = x;
18455   volatile double z = y;
18456   rc = (y!=z);
18457 #else  /* if defined(SQLITE_HAVE_ISNAN) */
18458   rc = isnan(x);
18459 #endif /* SQLITE_HAVE_ISNAN */
18460   testcase( rc );
18461   return rc;
18462 }
18463
18464 /*
18465 ** Compute a string length that is limited to what can be stored in
18466 ** lower 30 bits of a 32-bit signed integer.
18467 **
18468 ** The value returned will never be negative.  Nor will it ever be greater
18469 ** than the actual length of the string.  For very long strings (greater
18470 ** than 1GiB) the value returned might be less than the true string length.
18471 */
18472 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
18473   const char *z2 = z;
18474   if( z==0 ) return 0;
18475   while( *z2 ){ z2++; }
18476   return 0x3fffffff & (int)(z2 - z);
18477 }
18478
18479 /*
18480 ** Set the most recent error code and error string for the sqlite
18481 ** handle "db". The error code is set to "err_code".
18482 **
18483 ** If it is not NULL, string zFormat specifies the format of the
18484 ** error string in the style of the printf functions: The following
18485 ** format characters are allowed:
18486 **
18487 **      %s      Insert a string
18488 **      %z      A string that should be freed after use
18489 **      %d      Insert an integer
18490 **      %T      Insert a token
18491 **      %S      Insert the first element of a SrcList
18492 **
18493 ** zFormat and any string tokens that follow it are assumed to be
18494 ** encoded in UTF-8.
18495 **
18496 ** To clear the most recent error for sqlite handle "db", sqlite3Error
18497 ** should be called with err_code set to SQLITE_OK and zFormat set
18498 ** to NULL.
18499 */
18500 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
18501   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
18502     db->errCode = err_code;
18503     if( zFormat ){
18504       char *z;
18505       va_list ap;
18506       va_start(ap, zFormat);
18507       z = sqlite3VMPrintf(db, zFormat, ap);
18508       va_end(ap);
18509       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
18510     }else{
18511       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
18512     }
18513   }
18514 }
18515
18516 /*
18517 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
18518 ** The following formatting characters are allowed:
18519 **
18520 **      %s      Insert a string
18521 **      %z      A string that should be freed after use
18522 **      %d      Insert an integer
18523 **      %T      Insert a token
18524 **      %S      Insert the first element of a SrcList
18525 **
18526 ** This function should be used to report any error that occurs whilst
18527 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
18528 ** last thing the sqlite3_prepare() function does is copy the error
18529 ** stored by this function into the database handle using sqlite3Error().
18530 ** Function sqlite3Error() should be used during statement execution
18531 ** (sqlite3_step() etc.).
18532 */
18533 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
18534   va_list ap;
18535   sqlite3 *db = pParse->db;
18536   pParse->nErr++;
18537   sqlite3DbFree(db, pParse->zErrMsg);
18538   va_start(ap, zFormat);
18539   pParse->zErrMsg = sqlite3VMPrintf(db, zFormat, ap);
18540   va_end(ap);
18541   pParse->rc = SQLITE_ERROR;
18542 }
18543
18544 /*
18545 ** Clear the error message in pParse, if any
18546 */
18547 SQLITE_PRIVATE void sqlite3ErrorClear(Parse *pParse){
18548   sqlite3DbFree(pParse->db, pParse->zErrMsg);
18549   pParse->zErrMsg = 0;
18550   pParse->nErr = 0;
18551 }
18552
18553 /*
18554 ** Convert an SQL-style quoted string into a normal string by removing
18555 ** the quote characters.  The conversion is done in-place.  If the
18556 ** input does not begin with a quote character, then this routine
18557 ** is a no-op.
18558 **
18559 ** The input string must be zero-terminated.  A new zero-terminator
18560 ** is added to the dequoted string.
18561 **
18562 ** The return value is -1 if no dequoting occurs or the length of the
18563 ** dequoted string, exclusive of the zero terminator, if dequoting does
18564 ** occur.
18565 **
18566 ** 2002-Feb-14: This routine is extended to remove MS-Access style
18567 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
18568 ** "a-b-c".
18569 */
18570 SQLITE_PRIVATE int sqlite3Dequote(char *z){
18571   char quote;
18572   int i, j;
18573   if( z==0 ) return -1;
18574   quote = z[0];
18575   switch( quote ){
18576     case '\'':  break;
18577     case '"':   break;
18578     case '`':   break;                /* For MySQL compatibility */
18579     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
18580     default:    return -1;
18581   }
18582   for(i=1, j=0; ALWAYS(z[i]); i++){
18583     if( z[i]==quote ){
18584       if( z[i+1]==quote ){
18585         z[j++] = quote;
18586         i++;
18587       }else{
18588         break;
18589       }
18590     }else{
18591       z[j++] = z[i];
18592     }
18593   }
18594   z[j] = 0;
18595   return j;
18596 }
18597
18598 /* Convenient short-hand */
18599 #define UpperToLower sqlite3UpperToLower
18600
18601 /*
18602 ** Some systems have stricmp().  Others have strcasecmp().  Because
18603 ** there is no consistency, we will define our own.
18604 */
18605 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
18606   register unsigned char *a, *b;
18607   a = (unsigned char *)zLeft;
18608   b = (unsigned char *)zRight;
18609   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18610   return UpperToLower[*a] - UpperToLower[*b];
18611 }
18612 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
18613   register unsigned char *a, *b;
18614   a = (unsigned char *)zLeft;
18615   b = (unsigned char *)zRight;
18616   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18617   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
18618 }
18619
18620 /*
18621 ** Return TRUE if z is a pure numeric string.  Return FALSE and leave
18622 ** *realnum unchanged if the string contains any character which is not
18623 ** part of a number.
18624 **
18625 ** If the string is pure numeric, set *realnum to TRUE if the string
18626 ** contains the '.' character or an "E+000" style exponentiation suffix.
18627 ** Otherwise set *realnum to FALSE.  Note that just becaue *realnum is
18628 ** false does not mean that the number can be successfully converted into
18629 ** an integer - it might be too big.
18630 **
18631 ** An empty string is considered non-numeric.
18632 */
18633 SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
18634   int incr = (enc==SQLITE_UTF8?1:2);
18635   if( enc==SQLITE_UTF16BE ) z++;
18636   if( *z=='-' || *z=='+' ) z += incr;
18637   if( !sqlite3Isdigit(*z) ){
18638     return 0;
18639   }
18640   z += incr;
18641   *realnum = 0;
18642   while( sqlite3Isdigit(*z) ){ z += incr; }
18643   if( *z=='.' ){
18644     z += incr;
18645     if( !sqlite3Isdigit(*z) ) return 0;
18646     while( sqlite3Isdigit(*z) ){ z += incr; }
18647     *realnum = 1;
18648   }
18649   if( *z=='e' || *z=='E' ){
18650     z += incr;
18651     if( *z=='+' || *z=='-' ) z += incr;
18652     if( !sqlite3Isdigit(*z) ) return 0;
18653     while( sqlite3Isdigit(*z) ){ z += incr; }
18654     *realnum = 1;
18655   }
18656   return *z==0;
18657 }
18658
18659 /*
18660 ** The string z[] is an ASCII representation of a real number.
18661 ** Convert this string to a double.
18662 **
18663 ** This routine assumes that z[] really is a valid number.  If it
18664 ** is not, the result is undefined.
18665 **
18666 ** This routine is used instead of the library atof() function because
18667 ** the library atof() might want to use "," as the decimal point instead
18668 ** of "." depending on how locale is set.  But that would cause problems
18669 ** for SQL.  So this routine always uses "." regardless of locale.
18670 */
18671 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
18672 #ifndef SQLITE_OMIT_FLOATING_POINT
18673   const char *zBegin = z;
18674   /* sign * significand * (10 ^ (esign * exponent)) */
18675   int sign = 1;   /* sign of significand */
18676   i64 s = 0;      /* significand */
18677   int d = 0;      /* adjust exponent for shifting decimal point */
18678   int esign = 1;  /* sign of exponent */
18679   int e = 0;      /* exponent */
18680   double result;
18681   int nDigits = 0;
18682
18683   /* skip leading spaces */
18684   while( sqlite3Isspace(*z) ) z++;
18685   /* get sign of significand */
18686   if( *z=='-' ){
18687     sign = -1;
18688     z++;
18689   }else if( *z=='+' ){
18690     z++;
18691   }
18692   /* skip leading zeroes */
18693   while( z[0]=='0' ) z++, nDigits++;
18694
18695   /* copy max significant digits to significand */
18696   while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
18697     s = s*10 + (*z - '0');
18698     z++, nDigits++;
18699   }
18700   /* skip non-significant significand digits
18701   ** (increase exponent by d to shift decimal left) */
18702   while( sqlite3Isdigit(*z) ) z++, nDigits++, d++;
18703
18704   /* if decimal point is present */
18705   if( *z=='.' ){
18706     z++;
18707     /* copy digits from after decimal to significand
18708     ** (decrease exponent by d to shift decimal right) */
18709     while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
18710       s = s*10 + (*z - '0');
18711       z++, nDigits++, d--;
18712     }
18713     /* skip non-significant digits */
18714     while( sqlite3Isdigit(*z) ) z++, nDigits++;
18715   }
18716
18717   /* if exponent is present */
18718   if( *z=='e' || *z=='E' ){
18719     z++;
18720     /* get sign of exponent */
18721     if( *z=='-' ){
18722       esign = -1;
18723       z++;
18724     }else if( *z=='+' ){
18725       z++;
18726     }
18727     /* copy digits to exponent */
18728     while( sqlite3Isdigit(*z) ){
18729       e = e*10 + (*z - '0');
18730       z++;
18731     }
18732   }
18733
18734   /* adjust exponent by d, and update sign */
18735   e = (e*esign) + d;
18736   if( e<0 ) {
18737     esign = -1;
18738     e *= -1;
18739   } else {
18740     esign = 1;
18741   }
18742
18743   /* if 0 significand */
18744   if( !s ) {
18745     /* In the IEEE 754 standard, zero is signed.
18746     ** Add the sign if we've seen at least one digit */
18747     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
18748   } else {
18749     /* attempt to reduce exponent */
18750     if( esign>0 ){
18751       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
18752     }else{
18753       while( !(s%10) && e>0 ) e--,s/=10;
18754     }
18755
18756     /* adjust the sign of significand */
18757     s = sign<0 ? -s : s;
18758
18759     /* if exponent, scale significand as appropriate
18760     ** and store in result. */
18761     if( e ){
18762       double scale = 1.0;
18763       /* attempt to handle extremely small/large numbers better */
18764       if( e>307 && e<342 ){
18765         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
18766         if( esign<0 ){
18767           result = s / scale;
18768           result /= 1.0e+308;
18769         }else{
18770           result = s * scale;
18771           result *= 1.0e+308;
18772         }
18773       }else{
18774         /* 1.0e+22 is the largest power of 10 than can be 
18775         ** represented exactly. */
18776         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
18777         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
18778         if( esign<0 ){
18779           result = s / scale;
18780         }else{
18781           result = s * scale;
18782         }
18783       }
18784     } else {
18785       result = (double)s;
18786     }
18787   }
18788
18789   /* store the result */
18790   *pResult = result;
18791
18792   /* return number of characters used */
18793   return (int)(z - zBegin);
18794 #else
18795   return sqlite3Atoi64(z, pResult);
18796 #endif /* SQLITE_OMIT_FLOATING_POINT */
18797 }
18798
18799 /*
18800 ** Compare the 19-character string zNum against the text representation
18801 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
18802 ** if zNum is less than, equal to, or greater than the string.
18803 **
18804 ** Unlike memcmp() this routine is guaranteed to return the difference
18805 ** in the values of the last digit if the only difference is in the
18806 ** last digit.  So, for example,
18807 **
18808 **      compare2pow63("9223372036854775800")
18809 **
18810 ** will return -8.
18811 */
18812 static int compare2pow63(const char *zNum){
18813   int c;
18814   c = memcmp(zNum,"922337203685477580",18)*10;
18815   if( c==0 ){
18816     c = zNum[18] - '8';
18817   }
18818   return c;
18819 }
18820
18821
18822 /*
18823 ** Return TRUE if zNum is a 64-bit signed integer and write
18824 ** the value of the integer into *pNum.  If zNum is not an integer
18825 ** or is an integer that is too large to be expressed with 64 bits,
18826 ** then return false.
18827 **
18828 ** When this routine was originally written it dealt with only
18829 ** 32-bit numbers.  At that time, it was much faster than the
18830 ** atoi() library routine in RedHat 7.2.
18831 */
18832 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
18833   i64 v = 0;
18834   int neg;
18835   int i, c;
18836   const char *zStart;
18837   while( sqlite3Isspace(*zNum) ) zNum++;
18838   if( *zNum=='-' ){
18839     neg = 1;
18840     zNum++;
18841   }else if( *zNum=='+' ){
18842     neg = 0;
18843     zNum++;
18844   }else{
18845     neg = 0;
18846   }
18847   zStart = zNum;
18848   while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
18849   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
18850     v = v*10 + c - '0';
18851   }
18852   *pNum = neg ? -v : v;
18853   if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
18854     /* zNum is empty or contains non-numeric text or is longer
18855     ** than 19 digits (thus guaranting that it is too large) */
18856     return 0;
18857   }else if( i<19 ){
18858     /* Less than 19 digits, so we know that it fits in 64 bits */
18859     return 1;
18860   }else{
18861     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
18862     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
18863     ** is 2^63. */
18864     return compare2pow63(zNum)<neg;
18865   }
18866 }
18867
18868 /*
18869 ** The string zNum represents an unsigned integer.  The zNum string
18870 ** consists of one or more digit characters and is terminated by
18871 ** a zero character.  Any stray characters in zNum result in undefined
18872 ** behavior.
18873 **
18874 ** If the unsigned integer that zNum represents will fit in a
18875 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
18876 **
18877 ** If the negFlag parameter is true, that means that zNum really represents
18878 ** a negative number.  (The leading "-" is omitted from zNum.)  This
18879 ** parameter is needed to determine a boundary case.  A string
18880 ** of "9223373036854775808" returns false if negFlag is false or true
18881 ** if negFlag is true.
18882 **
18883 ** Leading zeros are ignored.
18884 */
18885 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
18886   int i;
18887   int neg = 0;
18888
18889   assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */
18890
18891   if( negFlag ) neg = 1-neg;
18892   while( *zNum=='0' ){
18893     zNum++;   /* Skip leading zeros.  Ticket #2454 */
18894   }
18895   for(i=0; zNum[i]; i++){ assert( zNum[i]>='0' && zNum[i]<='9' ); }
18896   if( i<19 ){
18897     /* Guaranteed to fit if less than 19 digits */
18898     return 1;
18899   }else if( i>19 ){
18900     /* Guaranteed to be too big if greater than 19 digits */
18901     return 0;
18902   }else{
18903     /* Compare against 2^63. */
18904     return compare2pow63(zNum)<neg;
18905   }
18906 }
18907
18908 /*
18909 ** If zNum represents an integer that will fit in 32-bits, then set
18910 ** *pValue to that integer and return true.  Otherwise return false.
18911 **
18912 ** Any non-numeric characters that following zNum are ignored.
18913 ** This is different from sqlite3Atoi64() which requires the
18914 ** input number to be zero-terminated.
18915 */
18916 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
18917   sqlite_int64 v = 0;
18918   int i, c;
18919   int neg = 0;
18920   if( zNum[0]=='-' ){
18921     neg = 1;
18922     zNum++;
18923   }else if( zNum[0]=='+' ){
18924     zNum++;
18925   }
18926   while( zNum[0]=='0' ) zNum++;
18927   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
18928     v = v*10 + c;
18929   }
18930
18931   /* The longest decimal representation of a 32 bit integer is 10 digits:
18932   **
18933   **             1234567890
18934   **     2^31 -> 2147483648
18935   */
18936   if( i>10 ){
18937     return 0;
18938   }
18939   if( v-neg>2147483647 ){
18940     return 0;
18941   }
18942   if( neg ){
18943     v = -v;
18944   }
18945   *pValue = (int)v;
18946   return 1;
18947 }
18948
18949 /*
18950 ** The variable-length integer encoding is as follows:
18951 **
18952 ** KEY:
18953 **         A = 0xxxxxxx    7 bits of data and one flag bit
18954 **         B = 1xxxxxxx    7 bits of data and one flag bit
18955 **         C = xxxxxxxx    8 bits of data
18956 **
18957 **  7 bits - A
18958 ** 14 bits - BA
18959 ** 21 bits - BBA
18960 ** 28 bits - BBBA
18961 ** 35 bits - BBBBA
18962 ** 42 bits - BBBBBA
18963 ** 49 bits - BBBBBBA
18964 ** 56 bits - BBBBBBBA
18965 ** 64 bits - BBBBBBBBC
18966 */
18967
18968 /*
18969 ** Write a 64-bit variable-length integer to memory starting at p[0].
18970 ** The length of data write will be between 1 and 9 bytes.  The number
18971 ** of bytes written is returned.
18972 **
18973 ** A variable-length integer consists of the lower 7 bits of each byte
18974 ** for all bytes that have the 8th bit set and one byte with the 8th
18975 ** bit clear.  Except, if we get to the 9th byte, it stores the full
18976 ** 8 bits and is the last byte.
18977 */
18978 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
18979   int i, j, n;
18980   u8 buf[10];
18981   if( v & (((u64)0xff000000)<<32) ){
18982     p[8] = (u8)v;
18983     v >>= 8;
18984     for(i=7; i>=0; i--){
18985       p[i] = (u8)((v & 0x7f) | 0x80);
18986       v >>= 7;
18987     }
18988     return 9;
18989   }    
18990   n = 0;
18991   do{
18992     buf[n++] = (u8)((v & 0x7f) | 0x80);
18993     v >>= 7;
18994   }while( v!=0 );
18995   buf[0] &= 0x7f;
18996   assert( n<=9 );
18997   for(i=0, j=n-1; j>=0; j--, i++){
18998     p[i] = buf[j];
18999   }
19000   return n;
19001 }
19002
19003 /*
19004 ** This routine is a faster version of sqlite3PutVarint() that only
19005 ** works for 32-bit positive integers and which is optimized for
19006 ** the common case of small integers.  A MACRO version, putVarint32,
19007 ** is provided which inlines the single-byte case.  All code should use
19008 ** the MACRO version as this function assumes the single-byte case has
19009 ** already been handled.
19010 */
19011 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
19012 #ifndef putVarint32
19013   if( (v & ~0x7f)==0 ){
19014     p[0] = v;
19015     return 1;
19016   }
19017 #endif
19018   if( (v & ~0x3fff)==0 ){
19019     p[0] = (u8)((v>>7) | 0x80);
19020     p[1] = (u8)(v & 0x7f);
19021     return 2;
19022   }
19023   return sqlite3PutVarint(p, v);
19024 }
19025
19026 /*
19027 ** Read a 64-bit variable-length integer from memory starting at p[0].
19028 ** Return the number of bytes read.  The value is stored in *v.
19029 */
19030 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
19031   u32 a,b,s;
19032
19033   a = *p;
19034   /* a: p0 (unmasked) */
19035   if (!(a&0x80))
19036   {
19037     *v = a;
19038     return 1;
19039   }
19040
19041   p++;
19042   b = *p;
19043   /* b: p1 (unmasked) */
19044   if (!(b&0x80))
19045   {
19046     a &= 0x7f;
19047     a = a<<7;
19048     a |= b;
19049     *v = a;
19050     return 2;
19051   }
19052
19053   p++;
19054   a = a<<14;
19055   a |= *p;
19056   /* a: p0<<14 | p2 (unmasked) */
19057   if (!(a&0x80))
19058   {
19059     a &= (0x7f<<14)|(0x7f);
19060     b &= 0x7f;
19061     b = b<<7;
19062     a |= b;
19063     *v = a;
19064     return 3;
19065   }
19066
19067   /* CSE1 from below */
19068   a &= (0x7f<<14)|(0x7f);
19069   p++;
19070   b = b<<14;
19071   b |= *p;
19072   /* b: p1<<14 | p3 (unmasked) */
19073   if (!(b&0x80))
19074   {
19075     b &= (0x7f<<14)|(0x7f);
19076     /* moved CSE1 up */
19077     /* a &= (0x7f<<14)|(0x7f); */
19078     a = a<<7;
19079     a |= b;
19080     *v = a;
19081     return 4;
19082   }
19083
19084   /* a: p0<<14 | p2 (masked) */
19085   /* b: p1<<14 | p3 (unmasked) */
19086   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19087   /* moved CSE1 up */
19088   /* a &= (0x7f<<14)|(0x7f); */
19089   b &= (0x7f<<14)|(0x7f);
19090   s = a;
19091   /* s: p0<<14 | p2 (masked) */
19092
19093   p++;
19094   a = a<<14;
19095   a |= *p;
19096   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19097   if (!(a&0x80))
19098   {
19099     /* we can skip these cause they were (effectively) done above in calc'ing s */
19100     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19101     /* b &= (0x7f<<14)|(0x7f); */
19102     b = b<<7;
19103     a |= b;
19104     s = s>>18;
19105     *v = ((u64)s)<<32 | a;
19106     return 5;
19107   }
19108
19109   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19110   s = s<<7;
19111   s |= b;
19112   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19113
19114   p++;
19115   b = b<<14;
19116   b |= *p;
19117   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
19118   if (!(b&0x80))
19119   {
19120     /* we can skip this cause it was (effectively) done above in calc'ing s */
19121     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19122     a &= (0x7f<<14)|(0x7f);
19123     a = a<<7;
19124     a |= b;
19125     s = s>>18;
19126     *v = ((u64)s)<<32 | a;
19127     return 6;
19128   }
19129
19130   p++;
19131   a = a<<14;
19132   a |= *p;
19133   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
19134   if (!(a&0x80))
19135   {
19136     a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19137     b &= (0x7f<<14)|(0x7f);
19138     b = b<<7;
19139     a |= b;
19140     s = s>>11;
19141     *v = ((u64)s)<<32 | a;
19142     return 7;
19143   }
19144
19145   /* CSE2 from below */
19146   a &= (0x7f<<14)|(0x7f);
19147   p++;
19148   b = b<<14;
19149   b |= *p;
19150   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
19151   if (!(b&0x80))
19152   {
19153     b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19154     /* moved CSE2 up */
19155     /* a &= (0x7f<<14)|(0x7f); */
19156     a = a<<7;
19157     a |= b;
19158     s = s>>4;
19159     *v = ((u64)s)<<32 | a;
19160     return 8;
19161   }
19162
19163   p++;
19164   a = a<<15;
19165   a |= *p;
19166   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
19167
19168   /* moved CSE2 up */
19169   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
19170   b &= (0x7f<<14)|(0x7f);
19171   b = b<<8;
19172   a |= b;
19173
19174   s = s<<4;
19175   b = p[-4];
19176   b &= 0x7f;
19177   b = b>>3;
19178   s |= b;
19179
19180   *v = ((u64)s)<<32 | a;
19181
19182   return 9;
19183 }
19184
19185 /*
19186 ** Read a 32-bit variable-length integer from memory starting at p[0].
19187 ** Return the number of bytes read.  The value is stored in *v.
19188 **
19189 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
19190 ** integer, then set *v to 0xffffffff.
19191 **
19192 ** A MACRO version, getVarint32, is provided which inlines the 
19193 ** single-byte case.  All code should use the MACRO version as 
19194 ** this function assumes the single-byte case has already been handled.
19195 */
19196 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
19197   u32 a,b;
19198
19199   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
19200   ** by the getVarin32() macro */
19201   a = *p;
19202   /* a: p0 (unmasked) */
19203 #ifndef getVarint32
19204   if (!(a&0x80))
19205   {
19206     /* Values between 0 and 127 */
19207     *v = a;
19208     return 1;
19209   }
19210 #endif
19211
19212   /* The 2-byte case */
19213   p++;
19214   b = *p;
19215   /* b: p1 (unmasked) */
19216   if (!(b&0x80))
19217   {
19218     /* Values between 128 and 16383 */
19219     a &= 0x7f;
19220     a = a<<7;
19221     *v = a | b;
19222     return 2;
19223   }
19224
19225   /* The 3-byte case */
19226   p++;
19227   a = a<<14;
19228   a |= *p;
19229   /* a: p0<<14 | p2 (unmasked) */
19230   if (!(a&0x80))
19231   {
19232     /* Values between 16384 and 2097151 */
19233     a &= (0x7f<<14)|(0x7f);
19234     b &= 0x7f;
19235     b = b<<7;
19236     *v = a | b;
19237     return 3;
19238   }
19239
19240   /* A 32-bit varint is used to store size information in btrees.
19241   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
19242   ** A 3-byte varint is sufficient, for example, to record the size
19243   ** of a 1048569-byte BLOB or string.
19244   **
19245   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
19246   ** rare larger cases can be handled by the slower 64-bit varint
19247   ** routine.
19248   */
19249 #if 1
19250   {
19251     u64 v64;
19252     u8 n;
19253
19254     p -= 2;
19255     n = sqlite3GetVarint(p, &v64);
19256     assert( n>3 && n<=9 );
19257     if( (v64 & SQLITE_MAX_U32)!=v64 ){
19258       *v = 0xffffffff;
19259     }else{
19260       *v = (u32)v64;
19261     }
19262     return n;
19263   }
19264
19265 #else
19266   /* For following code (kept for historical record only) shows an
19267   ** unrolling for the 3- and 4-byte varint cases.  This code is
19268   ** slightly faster, but it is also larger and much harder to test.
19269   */
19270   p++;
19271   b = b<<14;
19272   b |= *p;
19273   /* b: p1<<14 | p3 (unmasked) */
19274   if (!(b&0x80))
19275   {
19276     /* Values between 2097152 and 268435455 */
19277     b &= (0x7f<<14)|(0x7f);
19278     a &= (0x7f<<14)|(0x7f);
19279     a = a<<7;
19280     *v = a | b;
19281     return 4;
19282   }
19283
19284   p++;
19285   a = a<<14;
19286   a |= *p;
19287   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19288   if (!(a&0x80))
19289   {
19290     /* Walues  between 268435456 and 34359738367 */
19291     a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19292     b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19293     b = b<<7;
19294     *v = a | b;
19295     return 5;
19296   }
19297
19298   /* We can only reach this point when reading a corrupt database
19299   ** file.  In that case we are not in any hurry.  Use the (relatively
19300   ** slow) general-purpose sqlite3GetVarint() routine to extract the
19301   ** value. */
19302   {
19303     u64 v64;
19304     u8 n;
19305
19306     p -= 4;
19307     n = sqlite3GetVarint(p, &v64);
19308     assert( n>5 && n<=9 );
19309     *v = (u32)v64;
19310     return n;
19311   }
19312 #endif
19313 }
19314
19315 /*
19316 ** Return the number of bytes that will be needed to store the given
19317 ** 64-bit integer.
19318 */
19319 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
19320   int i = 0;
19321   do{
19322     i++;
19323     v >>= 7;
19324   }while( v!=0 && ALWAYS(i<9) );
19325   return i;
19326 }
19327
19328
19329 /*
19330 ** Read or write a four-byte big-endian integer value.
19331 */
19332 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
19333   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
19334 }
19335 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
19336   p[0] = (u8)(v>>24);
19337   p[1] = (u8)(v>>16);
19338   p[2] = (u8)(v>>8);
19339   p[3] = (u8)v;
19340 }
19341
19342
19343
19344 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19345 /*
19346 ** Translate a single byte of Hex into an integer.
19347 ** This routine only works if h really is a valid hexadecimal
19348 ** character:  0..9a..fA..F
19349 */
19350 static u8 hexToInt(int h){
19351   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
19352 #ifdef SQLITE_ASCII
19353   h += 9*(1&(h>>6));
19354 #endif
19355 #ifdef SQLITE_EBCDIC
19356   h += 9*(1&~(h>>4));
19357 #endif
19358   return (u8)(h & 0xf);
19359 }
19360 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19361
19362 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19363 /*
19364 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
19365 ** value.  Return a pointer to its binary value.  Space to hold the
19366 ** binary value has been obtained from malloc and must be freed by
19367 ** the calling routine.
19368 */
19369 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
19370   char *zBlob;
19371   int i;
19372
19373   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
19374   n--;
19375   if( zBlob ){
19376     for(i=0; i<n; i+=2){
19377       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
19378     }
19379     zBlob[i/2] = 0;
19380   }
19381   return zBlob;
19382 }
19383 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19384
19385
19386 /*
19387 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
19388 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
19389 ** when this routine is called.
19390 **
19391 ** This routine is called when entering an SQLite API.  The SQLITE_MAGIC_OPEN
19392 ** value indicates that the database connection passed into the API is
19393 ** open and is not being used by another thread.  By changing the value
19394 ** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
19395 ** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
19396 ** when the API exits. 
19397 **
19398 ** This routine is a attempt to detect if two threads use the
19399 ** same sqlite* pointer at the same time.  There is a race 
19400 ** condition so it is possible that the error is not detected.
19401 ** But usually the problem will be seen.  The result will be an
19402 ** error which can be used to debug the application that is
19403 ** using SQLite incorrectly.
19404 **
19405 ** Ticket #202:  If db->magic is not a valid open value, take care not
19406 ** to modify the db structure at all.  It could be that db is a stale
19407 ** pointer.  In other words, it could be that there has been a prior
19408 ** call to sqlite3_close(db) and db has been deallocated.  And we do
19409 ** not want to write into deallocated memory.
19410 */
19411 #ifdef SQLITE_DEBUG
19412 SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3 *db){
19413   if( db->magic==SQLITE_MAGIC_OPEN ){
19414     db->magic = SQLITE_MAGIC_BUSY;
19415     assert( sqlite3_mutex_held(db->mutex) );
19416     return 0;
19417   }else if( db->magic==SQLITE_MAGIC_BUSY ){
19418     db->magic = SQLITE_MAGIC_ERROR;
19419     db->u1.isInterrupted = 1;
19420   }
19421   return 1;
19422 }
19423 #endif
19424
19425 /*
19426 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
19427 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
19428 ** when this routine is called.
19429 */
19430 #ifdef SQLITE_DEBUG
19431 SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3 *db){
19432   if( db->magic==SQLITE_MAGIC_BUSY ){
19433     db->magic = SQLITE_MAGIC_OPEN;
19434     assert( sqlite3_mutex_held(db->mutex) );
19435     return 0;
19436   }else{
19437     db->magic = SQLITE_MAGIC_ERROR;
19438     db->u1.isInterrupted = 1;
19439     return 1;
19440   }
19441 }
19442 #endif
19443
19444 /*
19445 ** Check to make sure we have a valid db pointer.  This test is not
19446 ** foolproof but it does provide some measure of protection against
19447 ** misuse of the interface such as passing in db pointers that are
19448 ** NULL or which have been previously closed.  If this routine returns
19449 ** 1 it means that the db pointer is valid and 0 if it should not be
19450 ** dereferenced for any reason.  The calling function should invoke
19451 ** SQLITE_MISUSE immediately.
19452 **
19453 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
19454 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
19455 ** open properly and is not fit for general use but which can be
19456 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
19457 */
19458 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
19459   u32 magic;
19460   if( db==0 ) return 0;
19461   magic = db->magic;
19462   if( magic!=SQLITE_MAGIC_OPEN 
19463 #ifdef SQLITE_DEBUG
19464      && magic!=SQLITE_MAGIC_BUSY
19465 #endif
19466   ){
19467     return 0;
19468   }else{
19469     return 1;
19470   }
19471 }
19472 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
19473   u32 magic;
19474   magic = db->magic;
19475   if( magic!=SQLITE_MAGIC_SICK &&
19476       magic!=SQLITE_MAGIC_OPEN &&
19477       magic!=SQLITE_MAGIC_BUSY ) return 0;
19478   return 1;
19479 }
19480
19481 /************** End of util.c ************************************************/
19482 /************** Begin file hash.c ********************************************/
19483 /*
19484 ** 2001 September 22
19485 **
19486 ** The author disclaims copyright to this source code.  In place of
19487 ** a legal notice, here is a blessing:
19488 **
19489 **    May you do good and not evil.
19490 **    May you find forgiveness for yourself and forgive others.
19491 **    May you share freely, never taking more than you give.
19492 **
19493 *************************************************************************
19494 ** This is the implementation of generic hash-tables
19495 ** used in SQLite.
19496 */
19497
19498 /* Turn bulk memory into a hash table object by initializing the
19499 ** fields of the Hash structure.
19500 **
19501 ** "pNew" is a pointer to the hash table that is to be initialized.
19502 */
19503 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
19504   assert( pNew!=0 );
19505   pNew->first = 0;
19506   pNew->count = 0;
19507   pNew->htsize = 0;
19508   pNew->ht = 0;
19509 }
19510
19511 /* Remove all entries from a hash table.  Reclaim all memory.
19512 ** Call this routine to delete a hash table or to reset a hash table
19513 ** to the empty state.
19514 */
19515 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
19516   HashElem *elem;         /* For looping over all elements of the table */
19517
19518   assert( pH!=0 );
19519   elem = pH->first;
19520   pH->first = 0;
19521   sqlite3_free(pH->ht);
19522   pH->ht = 0;
19523   pH->htsize = 0;
19524   while( elem ){
19525     HashElem *next_elem = elem->next;
19526     sqlite3_free(elem);
19527     elem = next_elem;
19528   }
19529   pH->count = 0;
19530 }
19531
19532 /*
19533 ** The hashing function.
19534 */
19535 static unsigned int strHash(const char *z, int nKey){
19536   int h = 0;
19537   assert( nKey>=0 );
19538   while( nKey > 0  ){
19539     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
19540     nKey--;
19541   }
19542   return h;
19543 }
19544
19545
19546 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
19547 ** insert pNew into the pEntry hash bucket.
19548 */
19549 static void insertElement(
19550   Hash *pH,              /* The complete hash table */
19551   struct _ht *pEntry,    /* The entry into which pNew is inserted */
19552   HashElem *pNew         /* The element to be inserted */
19553 ){
19554   HashElem *pHead;       /* First element already in pEntry */
19555   if( pEntry ){
19556     pHead = pEntry->count ? pEntry->chain : 0;
19557     pEntry->count++;
19558     pEntry->chain = pNew;
19559   }else{
19560     pHead = 0;
19561   }
19562   if( pHead ){
19563     pNew->next = pHead;
19564     pNew->prev = pHead->prev;
19565     if( pHead->prev ){ pHead->prev->next = pNew; }
19566     else             { pH->first = pNew; }
19567     pHead->prev = pNew;
19568   }else{
19569     pNew->next = pH->first;
19570     if( pH->first ){ pH->first->prev = pNew; }
19571     pNew->prev = 0;
19572     pH->first = pNew;
19573   }
19574 }
19575
19576
19577 /* Resize the hash table so that it cantains "new_size" buckets.
19578 **
19579 ** The hash table might fail to resize if sqlite3_malloc() fails or
19580 ** if the new size is the same as the prior size.
19581 ** Return TRUE if the resize occurs and false if not.
19582 */
19583 static int rehash(Hash *pH, unsigned int new_size){
19584   struct _ht *new_ht;            /* The new hash table */
19585   HashElem *elem, *next_elem;    /* For looping over existing elements */
19586
19587 #if SQLITE_MALLOC_SOFT_LIMIT>0
19588   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
19589     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
19590   }
19591   if( new_size==pH->htsize ) return 0;
19592 #endif
19593
19594   /* The inability to allocates space for a larger hash table is
19595   ** a performance hit but it is not a fatal error.  So mark the
19596   ** allocation as a benign.
19597   */
19598   sqlite3BeginBenignMalloc();
19599   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
19600   sqlite3EndBenignMalloc();
19601
19602   if( new_ht==0 ) return 0;
19603   sqlite3_free(pH->ht);
19604   pH->ht = new_ht;
19605   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
19606   memset(new_ht, 0, new_size*sizeof(struct _ht));
19607   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
19608     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
19609     next_elem = elem->next;
19610     insertElement(pH, &new_ht[h], elem);
19611   }
19612   return 1;
19613 }
19614
19615 /* This function (for internal use only) locates an element in an
19616 ** hash table that matches the given key.  The hash for this key has
19617 ** already been computed and is passed as the 4th parameter.
19618 */
19619 static HashElem *findElementGivenHash(
19620   const Hash *pH,     /* The pH to be searched */
19621   const char *pKey,   /* The key we are searching for */
19622   int nKey,           /* Bytes in key (not counting zero terminator) */
19623   unsigned int h      /* The hash for this key. */
19624 ){
19625   HashElem *elem;                /* Used to loop thru the element list */
19626   int count;                     /* Number of elements left to test */
19627
19628   if( pH->ht ){
19629     struct _ht *pEntry = &pH->ht[h];
19630     elem = pEntry->chain;
19631     count = pEntry->count;
19632   }else{
19633     elem = pH->first;
19634     count = pH->count;
19635   }
19636   while( count-- && ALWAYS(elem) ){
19637     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
19638       return elem;
19639     }
19640     elem = elem->next;
19641   }
19642   return 0;
19643 }
19644
19645 /* Remove a single entry from the hash table given a pointer to that
19646 ** element and a hash on the element's key.
19647 */
19648 static void removeElementGivenHash(
19649   Hash *pH,         /* The pH containing "elem" */
19650   HashElem* elem,   /* The element to be removed from the pH */
19651   unsigned int h    /* Hash value for the element */
19652 ){
19653   struct _ht *pEntry;
19654   if( elem->prev ){
19655     elem->prev->next = elem->next; 
19656   }else{
19657     pH->first = elem->next;
19658   }
19659   if( elem->next ){
19660     elem->next->prev = elem->prev;
19661   }
19662   if( pH->ht ){
19663     pEntry = &pH->ht[h];
19664     if( pEntry->chain==elem ){
19665       pEntry->chain = elem->next;
19666     }
19667     pEntry->count--;
19668     assert( pEntry->count>=0 );
19669   }
19670   sqlite3_free( elem );
19671   pH->count--;
19672   if( pH->count<=0 ){
19673     assert( pH->first==0 );
19674     assert( pH->count==0 );
19675     sqlite3HashClear(pH);
19676   }
19677 }
19678
19679 /* Attempt to locate an element of the hash table pH with a key
19680 ** that matches pKey,nKey.  Return the data for this element if it is
19681 ** found, or NULL if there is no match.
19682 */
19683 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
19684   HashElem *elem;    /* The element that matches key */
19685   unsigned int h;    /* A hash on key */
19686
19687   assert( pH!=0 );
19688   assert( pKey!=0 );
19689   assert( nKey>=0 );
19690   if( pH->ht ){
19691     h = strHash(pKey, nKey) % pH->htsize;
19692   }else{
19693     h = 0;
19694   }
19695   elem = findElementGivenHash(pH, pKey, nKey, h);
19696   return elem ? elem->data : 0;
19697 }
19698
19699 /* Insert an element into the hash table pH.  The key is pKey,nKey
19700 ** and the data is "data".
19701 **
19702 ** If no element exists with a matching key, then a new
19703 ** element is created and NULL is returned.
19704 **
19705 ** If another element already exists with the same key, then the
19706 ** new data replaces the old data and the old data is returned.
19707 ** The key is not copied in this instance.  If a malloc fails, then
19708 ** the new data is returned and the hash table is unchanged.
19709 **
19710 ** If the "data" parameter to this function is NULL, then the
19711 ** element corresponding to "key" is removed from the hash table.
19712 */
19713 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
19714   unsigned int h;       /* the hash of the key modulo hash table size */
19715   HashElem *elem;       /* Used to loop thru the element list */
19716   HashElem *new_elem;   /* New element added to the pH */
19717
19718   assert( pH!=0 );
19719   assert( pKey!=0 );
19720   assert( nKey>=0 );
19721   if( pH->htsize ){
19722     h = strHash(pKey, nKey) % pH->htsize;
19723   }else{
19724     h = 0;
19725   }
19726   elem = findElementGivenHash(pH,pKey,nKey,h);
19727   if( elem ){
19728     void *old_data = elem->data;
19729     if( data==0 ){
19730       removeElementGivenHash(pH,elem,h);
19731     }else{
19732       elem->data = data;
19733       elem->pKey = pKey;
19734       assert(nKey==elem->nKey);
19735     }
19736     return old_data;
19737   }
19738   if( data==0 ) return 0;
19739   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
19740   if( new_elem==0 ) return data;
19741   new_elem->pKey = pKey;
19742   new_elem->nKey = nKey;
19743   new_elem->data = data;
19744   pH->count++;
19745   if( pH->count>=10 && pH->count > 2*pH->htsize ){
19746     if( rehash(pH, pH->count*2) ){
19747       assert( pH->htsize>0 );
19748       h = strHash(pKey, nKey) % pH->htsize;
19749     }
19750   }
19751   if( pH->ht ){
19752     insertElement(pH, &pH->ht[h], new_elem);
19753   }else{
19754     insertElement(pH, 0, new_elem);
19755   }
19756   return 0;
19757 }
19758
19759 /************** End of hash.c ************************************************/
19760 /************** Begin file opcodes.c *****************************************/
19761 /* Automatically generated.  Do not edit */
19762 /* See the mkopcodec.awk script for details. */
19763 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
19764 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
19765  static const char *const azName[] = { "?",
19766      /*   1 */ "Goto",
19767      /*   2 */ "Gosub",
19768      /*   3 */ "Return",
19769      /*   4 */ "Yield",
19770      /*   5 */ "HaltIfNull",
19771      /*   6 */ "Halt",
19772      /*   7 */ "Integer",
19773      /*   8 */ "Int64",
19774      /*   9 */ "String",
19775      /*  10 */ "Null",
19776      /*  11 */ "Blob",
19777      /*  12 */ "Variable",
19778      /*  13 */ "Move",
19779      /*  14 */ "Copy",
19780      /*  15 */ "SCopy",
19781      /*  16 */ "ResultRow",
19782      /*  17 */ "CollSeq",
19783      /*  18 */ "Function",
19784      /*  19 */ "Not",
19785      /*  20 */ "AddImm",
19786      /*  21 */ "MustBeInt",
19787      /*  22 */ "RealAffinity",
19788      /*  23 */ "Permutation",
19789      /*  24 */ "Compare",
19790      /*  25 */ "Jump",
19791      /*  26 */ "If",
19792      /*  27 */ "IfNot",
19793      /*  28 */ "Column",
19794      /*  29 */ "Affinity",
19795      /*  30 */ "MakeRecord",
19796      /*  31 */ "Count",
19797      /*  32 */ "Savepoint",
19798      /*  33 */ "AutoCommit",
19799      /*  34 */ "Transaction",
19800      /*  35 */ "ReadCookie",
19801      /*  36 */ "SetCookie",
19802      /*  37 */ "VerifyCookie",
19803      /*  38 */ "OpenRead",
19804      /*  39 */ "OpenWrite",
19805      /*  40 */ "OpenEphemeral",
19806      /*  41 */ "OpenPseudo",
19807      /*  42 */ "Close",
19808      /*  43 */ "SeekLt",
19809      /*  44 */ "SeekLe",
19810      /*  45 */ "SeekGe",
19811      /*  46 */ "SeekGt",
19812      /*  47 */ "Seek",
19813      /*  48 */ "NotFound",
19814      /*  49 */ "Found",
19815      /*  50 */ "IsUnique",
19816      /*  51 */ "NotExists",
19817      /*  52 */ "Sequence",
19818      /*  53 */ "NewRowid",
19819      /*  54 */ "Insert",
19820      /*  55 */ "InsertInt",
19821      /*  56 */ "Delete",
19822      /*  57 */ "ResetCount",
19823      /*  58 */ "RowKey",
19824      /*  59 */ "RowData",
19825      /*  60 */ "Rowid",
19826      /*  61 */ "NullRow",
19827      /*  62 */ "Last",
19828      /*  63 */ "Sort",
19829      /*  64 */ "Rewind",
19830      /*  65 */ "Prev",
19831      /*  66 */ "Next",
19832      /*  67 */ "IdxInsert",
19833      /*  68 */ "Or",
19834      /*  69 */ "And",
19835      /*  70 */ "IdxDelete",
19836      /*  71 */ "IdxRowid",
19837      /*  72 */ "IdxLT",
19838      /*  73 */ "IsNull",
19839      /*  74 */ "NotNull",
19840      /*  75 */ "Ne",
19841      /*  76 */ "Eq",
19842      /*  77 */ "Gt",
19843      /*  78 */ "Le",
19844      /*  79 */ "Lt",
19845      /*  80 */ "Ge",
19846      /*  81 */ "IdxGE",
19847      /*  82 */ "BitAnd",
19848      /*  83 */ "BitOr",
19849      /*  84 */ "ShiftLeft",
19850      /*  85 */ "ShiftRight",
19851      /*  86 */ "Add",
19852      /*  87 */ "Subtract",
19853      /*  88 */ "Multiply",
19854      /*  89 */ "Divide",
19855      /*  90 */ "Remainder",
19856      /*  91 */ "Concat",
19857      /*  92 */ "Destroy",
19858      /*  93 */ "BitNot",
19859      /*  94 */ "String8",
19860      /*  95 */ "Clear",
19861      /*  96 */ "CreateIndex",
19862      /*  97 */ "CreateTable",
19863      /*  98 */ "ParseSchema",
19864      /*  99 */ "LoadAnalysis",
19865      /* 100 */ "DropTable",
19866      /* 101 */ "DropIndex",
19867      /* 102 */ "DropTrigger",
19868      /* 103 */ "IntegrityCk",
19869      /* 104 */ "RowSetAdd",
19870      /* 105 */ "RowSetRead",
19871      /* 106 */ "RowSetTest",
19872      /* 107 */ "Program",
19873      /* 108 */ "Param",
19874      /* 109 */ "FkCounter",
19875      /* 110 */ "FkIfZero",
19876      /* 111 */ "MemMax",
19877      /* 112 */ "IfPos",
19878      /* 113 */ "IfNeg",
19879      /* 114 */ "IfZero",
19880      /* 115 */ "AggStep",
19881      /* 116 */ "AggFinal",
19882      /* 117 */ "Vacuum",
19883      /* 118 */ "IncrVacuum",
19884      /* 119 */ "Expire",
19885      /* 120 */ "TableLock",
19886      /* 121 */ "VBegin",
19887      /* 122 */ "VCreate",
19888      /* 123 */ "VDestroy",
19889      /* 124 */ "VOpen",
19890      /* 125 */ "VFilter",
19891      /* 126 */ "VColumn",
19892      /* 127 */ "VNext",
19893      /* 128 */ "VRename",
19894      /* 129 */ "VUpdate",
19895      /* 130 */ "Real",
19896      /* 131 */ "Pagecount",
19897      /* 132 */ "Trace",
19898      /* 133 */ "Noop",
19899      /* 134 */ "Explain",
19900      /* 135 */ "NotUsed_135",
19901      /* 136 */ "NotUsed_136",
19902      /* 137 */ "NotUsed_137",
19903      /* 138 */ "NotUsed_138",
19904      /* 139 */ "NotUsed_139",
19905      /* 140 */ "NotUsed_140",
19906      /* 141 */ "ToText",
19907      /* 142 */ "ToBlob",
19908      /* 143 */ "ToNumeric",
19909      /* 144 */ "ToInt",
19910      /* 145 */ "ToReal",
19911   };
19912   return azName[i];
19913 }
19914 #endif
19915
19916 /************** End of opcodes.c *********************************************/
19917 /************** Begin file os_os2.c ******************************************/
19918 /*
19919 ** 2006 Feb 14
19920 **
19921 ** The author disclaims copyright to this source code.  In place of
19922 ** a legal notice, here is a blessing:
19923 **
19924 **    May you do good and not evil.
19925 **    May you find forgiveness for yourself and forgive others.
19926 **    May you share freely, never taking more than you give.
19927 **
19928 ******************************************************************************
19929 **
19930 ** This file contains code that is specific to OS/2.
19931 */
19932
19933
19934 #if SQLITE_OS_OS2
19935
19936 /*
19937 ** A Note About Memory Allocation:
19938 **
19939 ** This driver uses malloc()/free() directly rather than going through
19940 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
19941 ** are designed for use on embedded systems where memory is scarce and
19942 ** malloc failures happen frequently.  OS/2 does not typically run on
19943 ** embedded systems, and when it does the developers normally have bigger
19944 ** problems to worry about than running out of memory.  So there is not
19945 ** a compelling need to use the wrappers.
19946 **
19947 ** But there is a good reason to not use the wrappers.  If we use the
19948 ** wrappers then we will get simulated malloc() failures within this
19949 ** driver.  And that causes all kinds of problems for our tests.  We
19950 ** could enhance SQLite to deal with simulated malloc failures within
19951 ** the OS driver, but the code to deal with those failure would not
19952 ** be exercised on Linux (which does not need to malloc() in the driver)
19953 ** and so we would have difficulty writing coverage tests for that
19954 ** code.  Better to leave the code out, we think.
19955 **
19956 ** The point of this discussion is as follows:  When creating a new
19957 ** OS layer for an embedded system, if you use this file as an example,
19958 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
19959 ** desktops but not so well in embedded systems.
19960 */
19961
19962 /*
19963 ** Macros used to determine whether or not to use threads.
19964 */
19965 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
19966 # define SQLITE_OS2_THREADS 1
19967 #endif
19968
19969 /*
19970 ** Include code that is common to all os_*.c files
19971 */
19972 /************** Include os_common.h in the middle of os_os2.c ****************/
19973 /************** Begin file os_common.h ***************************************/
19974 /*
19975 ** 2004 May 22
19976 **
19977 ** The author disclaims copyright to this source code.  In place of
19978 ** a legal notice, here is a blessing:
19979 **
19980 **    May you do good and not evil.
19981 **    May you find forgiveness for yourself and forgive others.
19982 **    May you share freely, never taking more than you give.
19983 **
19984 ******************************************************************************
19985 **
19986 ** This file contains macros and a little bit of code that is common to
19987 ** all of the platform-specific files (os_*.c) and is #included into those
19988 ** files.
19989 **
19990 ** This file should be #included by the os_*.c files only.  It is not a
19991 ** general purpose header file.
19992 */
19993 #ifndef _OS_COMMON_H_
19994 #define _OS_COMMON_H_
19995
19996 /*
19997 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
19998 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
19999 ** switch.  The following code should catch this problem at compile-time.
20000 */
20001 #ifdef MEMORY_DEBUG
20002 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
20003 #endif
20004
20005 #ifdef SQLITE_DEBUG
20006 SQLITE_PRIVATE int sqlite3OSTrace = 0;
20007 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
20008 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
20009 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
20010 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
20011 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
20012 #define OSTRACE6(X,Y,Z,A,B,C) \
20013     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
20014 #define OSTRACE7(X,Y,Z,A,B,C,D) \
20015     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
20016 #else
20017 #define OSTRACE1(X)
20018 #define OSTRACE2(X,Y)
20019 #define OSTRACE3(X,Y,Z)
20020 #define OSTRACE4(X,Y,Z,A)
20021 #define OSTRACE5(X,Y,Z,A,B)
20022 #define OSTRACE6(X,Y,Z,A,B,C)
20023 #define OSTRACE7(X,Y,Z,A,B,C,D)
20024 #endif
20025
20026 /*
20027 ** Macros for performance tracing.  Normally turned off.  Only works
20028 ** on i486 hardware.
20029 */
20030 #ifdef SQLITE_PERFORMANCE_TRACE
20031
20032 /* 
20033 ** hwtime.h contains inline assembler code for implementing 
20034 ** high-performance timing routines.
20035 */
20036 /************** Include hwtime.h in the middle of os_common.h ****************/
20037 /************** Begin file hwtime.h ******************************************/
20038 /*
20039 ** 2008 May 27
20040 **
20041 ** The author disclaims copyright to this source code.  In place of
20042 ** a legal notice, here is a blessing:
20043 **
20044 **    May you do good and not evil.
20045 **    May you find forgiveness for yourself and forgive others.
20046 **    May you share freely, never taking more than you give.
20047 **
20048 ******************************************************************************
20049 **
20050 ** This file contains inline asm code for retrieving "high-performance"
20051 ** counters for x86 class CPUs.
20052 */
20053 #ifndef _HWTIME_H_
20054 #define _HWTIME_H_
20055
20056 /*
20057 ** The following routine only works on pentium-class (or newer) processors.
20058 ** It uses the RDTSC opcode to read the cycle count value out of the
20059 ** processor and returns that value.  This can be used for high-res
20060 ** profiling.
20061 */
20062 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
20063       (defined(i386) || defined(__i386__) || defined(_M_IX86))
20064
20065   #if defined(__GNUC__)
20066
20067   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20068      unsigned int lo, hi;
20069      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
20070      return (sqlite_uint64)hi << 32 | lo;
20071   }
20072
20073   #elif defined(_MSC_VER)
20074
20075   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
20076      __asm {
20077         rdtsc
20078         ret       ; return value at EDX:EAX
20079      }
20080   }
20081
20082   #endif
20083
20084 #elif (defined(__GNUC__) && defined(__x86_64__))
20085
20086   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20087       unsigned long val;
20088       __asm__ __volatile__ ("rdtsc" : "=A" (val));
20089       return val;
20090   }
20091  
20092 #elif (defined(__GNUC__) && defined(__ppc__))
20093
20094   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20095       unsigned long long retval;
20096       unsigned long junk;
20097       __asm__ __volatile__ ("\n\
20098           1:      mftbu   %1\n\
20099                   mftb    %L0\n\
20100                   mftbu   %0\n\
20101                   cmpw    %0,%1\n\
20102                   bne     1b"
20103                   : "=r" (retval), "=r" (junk));
20104       return retval;
20105   }
20106
20107 #else
20108
20109   #error Need implementation of sqlite3Hwtime() for your platform.
20110
20111   /*
20112   ** To compile without implementing sqlite3Hwtime() for your platform,
20113   ** you can remove the above #error and use the following
20114   ** stub function.  You will lose timing support for many
20115   ** of the debugging and testing utilities, but it should at
20116   ** least compile and run.
20117   */
20118 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
20119
20120 #endif
20121
20122 #endif /* !defined(_HWTIME_H_) */
20123
20124 /************** End of hwtime.h **********************************************/
20125 /************** Continuing where we left off in os_common.h ******************/
20126
20127 static sqlite_uint64 g_start;
20128 static sqlite_uint64 g_elapsed;
20129 #define TIMER_START       g_start=sqlite3Hwtime()
20130 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
20131 #define TIMER_ELAPSED     g_elapsed
20132 #else
20133 #define TIMER_START
20134 #define TIMER_END
20135 #define TIMER_ELAPSED     ((sqlite_uint64)0)
20136 #endif
20137
20138 /*
20139 ** If we compile with the SQLITE_TEST macro set, then the following block
20140 ** of code will give us the ability to simulate a disk I/O error.  This
20141 ** is used for testing the I/O recovery logic.
20142 */
20143 #ifdef SQLITE_TEST
20144 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
20145 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
20146 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
20147 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
20148 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
20149 SQLITE_API int sqlite3_diskfull_pending = 0;
20150 SQLITE_API int sqlite3_diskfull = 0;
20151 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
20152 #define SimulateIOError(CODE)  \
20153   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
20154        || sqlite3_io_error_pending-- == 1 )  \
20155               { local_ioerr(); CODE; }
20156 static void local_ioerr(){
20157   IOTRACE(("IOERR\n"));
20158   sqlite3_io_error_hit++;
20159   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
20160 }
20161 #define SimulateDiskfullError(CODE) \
20162    if( sqlite3_diskfull_pending ){ \
20163      if( sqlite3_diskfull_pending == 1 ){ \
20164        local_ioerr(); \
20165        sqlite3_diskfull = 1; \
20166        sqlite3_io_error_hit = 1; \
20167        CODE; \
20168      }else{ \
20169        sqlite3_diskfull_pending--; \
20170      } \
20171    }
20172 #else
20173 #define SimulateIOErrorBenign(X)
20174 #define SimulateIOError(A)
20175 #define SimulateDiskfullError(A)
20176 #endif
20177
20178 /*
20179 ** When testing, keep a count of the number of open files.
20180 */
20181 #ifdef SQLITE_TEST
20182 SQLITE_API int sqlite3_open_file_count = 0;
20183 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
20184 #else
20185 #define OpenCounter(X)
20186 #endif
20187
20188 #endif /* !defined(_OS_COMMON_H_) */
20189
20190 /************** End of os_common.h *******************************************/
20191 /************** Continuing where we left off in os_os2.c *********************/
20192
20193 /*
20194 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
20195 ** protability layer.
20196 */
20197 typedef struct os2File os2File;
20198 struct os2File {
20199   const sqlite3_io_methods *pMethod;  /* Always the first entry */
20200   HFILE h;                  /* Handle for accessing the file */
20201   char* pathToDel;          /* Name of file to delete on close, NULL if not */
20202   unsigned char locktype;   /* Type of lock currently held on this file */
20203 };
20204
20205 #define LOCK_TIMEOUT 10L /* the default locking timeout */
20206
20207 /*****************************************************************************
20208 ** The next group of routines implement the I/O methods specified
20209 ** by the sqlite3_io_methods object.
20210 ******************************************************************************/
20211
20212 /*
20213 ** Close a file.
20214 */
20215 static int os2Close( sqlite3_file *id ){
20216   APIRET rc = NO_ERROR;
20217   os2File *pFile;
20218   if( id && (pFile = (os2File*)id) != 0 ){
20219     OSTRACE2( "CLOSE %d\n", pFile->h );
20220     rc = DosClose( pFile->h );
20221     pFile->locktype = NO_LOCK;
20222     if( pFile->pathToDel != NULL ){
20223       rc = DosForceDelete( (PSZ)pFile->pathToDel );
20224       free( pFile->pathToDel );
20225       pFile->pathToDel = NULL;
20226     }
20227     id = 0;
20228     OpenCounter( -1 );
20229   }
20230
20231   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20232 }
20233
20234 /*
20235 ** Read data from a file into a buffer.  Return SQLITE_OK if all
20236 ** bytes were read successfully and SQLITE_IOERR if anything goes
20237 ** wrong.
20238 */
20239 static int os2Read(
20240   sqlite3_file *id,               /* File to read from */
20241   void *pBuf,                     /* Write content into this buffer */
20242   int amt,                        /* Number of bytes to read */
20243   sqlite3_int64 offset            /* Begin reading at this offset */
20244 ){
20245   ULONG fileLocation = 0L;
20246   ULONG got;
20247   os2File *pFile = (os2File*)id;
20248   assert( id!=0 );
20249   SimulateIOError( return SQLITE_IOERR_READ );
20250   OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
20251   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20252     return SQLITE_IOERR;
20253   }
20254   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
20255     return SQLITE_IOERR_READ;
20256   }
20257   if( got == (ULONG)amt )
20258     return SQLITE_OK;
20259   else {
20260     /* Unread portions of the input buffer must be zero-filled */
20261     memset(&((char*)pBuf)[got], 0, amt-got);
20262     return SQLITE_IOERR_SHORT_READ;
20263   }
20264 }
20265
20266 /*
20267 ** Write data from a buffer into a file.  Return SQLITE_OK on success
20268 ** or some other error code on failure.
20269 */
20270 static int os2Write(
20271   sqlite3_file *id,               /* File to write into */
20272   const void *pBuf,               /* The bytes to be written */
20273   int amt,                        /* Number of bytes to write */
20274   sqlite3_int64 offset            /* Offset into the file to begin writing at */
20275 ){
20276   ULONG fileLocation = 0L;
20277   APIRET rc = NO_ERROR;
20278   ULONG wrote;
20279   os2File *pFile = (os2File*)id;
20280   assert( id!=0 );
20281   SimulateIOError( return SQLITE_IOERR_WRITE );
20282   SimulateDiskfullError( return SQLITE_FULL );
20283   OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
20284   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20285     return SQLITE_IOERR;
20286   }
20287   assert( amt>0 );
20288   while( amt > 0 &&
20289          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
20290          wrote > 0
20291   ){
20292     amt -= wrote;
20293     pBuf = &((char*)pBuf)[wrote];
20294   }
20295
20296   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
20297 }
20298
20299 /*
20300 ** Truncate an open file to a specified size
20301 */
20302 static int os2Truncate( sqlite3_file *id, i64 nByte ){
20303   APIRET rc = NO_ERROR;
20304   os2File *pFile = (os2File*)id;
20305   OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
20306   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
20307   rc = DosSetFileSize( pFile->h, nByte );
20308   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
20309 }
20310
20311 #ifdef SQLITE_TEST
20312 /*
20313 ** Count the number of fullsyncs and normal syncs.  This is used to test
20314 ** that syncs and fullsyncs are occuring at the right times.
20315 */
20316 SQLITE_API int sqlite3_sync_count = 0;
20317 SQLITE_API int sqlite3_fullsync_count = 0;
20318 #endif
20319
20320 /*
20321 ** Make sure all writes to a particular file are committed to disk.
20322 */
20323 static int os2Sync( sqlite3_file *id, int flags ){
20324   os2File *pFile = (os2File*)id;
20325   OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
20326 #ifdef SQLITE_TEST
20327   if( flags & SQLITE_SYNC_FULL){
20328     sqlite3_fullsync_count++;
20329   }
20330   sqlite3_sync_count++;
20331 #endif
20332   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
20333   ** no-op
20334   */
20335 #ifdef SQLITE_NO_SYNC
20336   UNUSED_PARAMETER(pFile);
20337   return SQLITE_OK;
20338 #else
20339   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20340 #endif
20341 }
20342
20343 /*
20344 ** Determine the current size of a file in bytes
20345 */
20346 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
20347   APIRET rc = NO_ERROR;
20348   FILESTATUS3 fsts3FileInfo;
20349   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
20350   assert( id!=0 );
20351   SimulateIOError( return SQLITE_IOERR_FSTAT );
20352   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
20353   if( rc == NO_ERROR ){
20354     *pSize = fsts3FileInfo.cbFile;
20355     return SQLITE_OK;
20356   }else{
20357     return SQLITE_IOERR_FSTAT;
20358   }
20359 }
20360
20361 /*
20362 ** Acquire a reader lock.
20363 */
20364 static int getReadLock( os2File *pFile ){
20365   FILELOCK  LockArea,
20366             UnlockArea;
20367   APIRET res;
20368   memset(&LockArea, 0, sizeof(LockArea));
20369   memset(&UnlockArea, 0, sizeof(UnlockArea));
20370   LockArea.lOffset = SHARED_FIRST;
20371   LockArea.lRange = SHARED_SIZE;
20372   UnlockArea.lOffset = 0L;
20373   UnlockArea.lRange = 0L;
20374   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20375   OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
20376   return res;
20377 }
20378
20379 /*
20380 ** Undo a readlock
20381 */
20382 static int unlockReadLock( os2File *id ){
20383   FILELOCK  LockArea,
20384             UnlockArea;
20385   APIRET res;
20386   memset(&LockArea, 0, sizeof(LockArea));
20387   memset(&UnlockArea, 0, sizeof(UnlockArea));
20388   LockArea.lOffset = 0L;
20389   LockArea.lRange = 0L;
20390   UnlockArea.lOffset = SHARED_FIRST;
20391   UnlockArea.lRange = SHARED_SIZE;
20392   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20393   OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
20394   return res;
20395 }
20396
20397 /*
20398 ** Lock the file with the lock specified by parameter locktype - one
20399 ** of the following:
20400 **
20401 **     (1) SHARED_LOCK
20402 **     (2) RESERVED_LOCK
20403 **     (3) PENDING_LOCK
20404 **     (4) EXCLUSIVE_LOCK
20405 **
20406 ** Sometimes when requesting one lock state, additional lock states
20407 ** are inserted in between.  The locking might fail on one of the later
20408 ** transitions leaving the lock state different from what it started but
20409 ** still short of its goal.  The following chart shows the allowed
20410 ** transitions and the inserted intermediate states:
20411 **
20412 **    UNLOCKED -> SHARED
20413 **    SHARED -> RESERVED
20414 **    SHARED -> (PENDING) -> EXCLUSIVE
20415 **    RESERVED -> (PENDING) -> EXCLUSIVE
20416 **    PENDING -> EXCLUSIVE
20417 **
20418 ** This routine will only increase a lock.  The os2Unlock() routine
20419 ** erases all locks at once and returns us immediately to locking level 0.
20420 ** It is not possible to lower the locking level one step at a time.  You
20421 ** must go straight to locking level 0.
20422 */
20423 static int os2Lock( sqlite3_file *id, int locktype ){
20424   int rc = SQLITE_OK;       /* Return code from subroutines */
20425   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
20426   int newLocktype;       /* Set pFile->locktype to this value before exiting */
20427   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
20428   FILELOCK  LockArea,
20429             UnlockArea;
20430   os2File *pFile = (os2File*)id;
20431   memset(&LockArea, 0, sizeof(LockArea));
20432   memset(&UnlockArea, 0, sizeof(UnlockArea));
20433   assert( pFile!=0 );
20434   OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
20435
20436   /* If there is already a lock of this type or more restrictive on the
20437   ** os2File, do nothing. Don't use the end_lock: exit path, as
20438   ** sqlite3_mutex_enter() hasn't been called yet.
20439   */
20440   if( pFile->locktype>=locktype ){
20441     OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
20442     return SQLITE_OK;
20443   }
20444
20445   /* Make sure the locking sequence is correct
20446   */
20447   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
20448   assert( locktype!=PENDING_LOCK );
20449   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
20450
20451   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
20452   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
20453   ** the PENDING_LOCK byte is temporary.
20454   */
20455   newLocktype = pFile->locktype;
20456   if( pFile->locktype==NO_LOCK
20457       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
20458   ){
20459     LockArea.lOffset = PENDING_BYTE;
20460     LockArea.lRange = 1L;
20461     UnlockArea.lOffset = 0L;
20462     UnlockArea.lRange = 0L;
20463
20464     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
20465     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
20466     if( res == NO_ERROR ){
20467       gotPendingLock = 1;
20468       OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
20469     }
20470   }
20471
20472   /* Acquire a shared lock
20473   */
20474   if( locktype==SHARED_LOCK && res == NO_ERROR ){
20475     assert( pFile->locktype==NO_LOCK );
20476     res = getReadLock(pFile);
20477     if( res == NO_ERROR ){
20478       newLocktype = SHARED_LOCK;
20479     }
20480     OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
20481   }
20482
20483   /* Acquire a RESERVED lock
20484   */
20485   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
20486     assert( pFile->locktype==SHARED_LOCK );
20487     LockArea.lOffset = RESERVED_BYTE;
20488     LockArea.lRange = 1L;
20489     UnlockArea.lOffset = 0L;
20490     UnlockArea.lRange = 0L;
20491     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20492     if( res == NO_ERROR ){
20493       newLocktype = RESERVED_LOCK;
20494     }
20495     OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
20496   }
20497
20498   /* Acquire a PENDING lock
20499   */
20500   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20501     newLocktype = PENDING_LOCK;
20502     gotPendingLock = 0;
20503     OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
20504   }
20505
20506   /* Acquire an EXCLUSIVE lock
20507   */
20508   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20509     assert( pFile->locktype>=SHARED_LOCK );
20510     res = unlockReadLock(pFile);
20511     OSTRACE2( "unreadlock = %d\n", res );
20512     LockArea.lOffset = SHARED_FIRST;
20513     LockArea.lRange = SHARED_SIZE;
20514     UnlockArea.lOffset = 0L;
20515     UnlockArea.lRange = 0L;
20516     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20517     if( res == NO_ERROR ){
20518       newLocktype = EXCLUSIVE_LOCK;
20519     }else{
20520       OSTRACE2( "OS/2 error-code = %d\n", res );
20521       getReadLock(pFile);
20522     }
20523     OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
20524   }
20525
20526   /* If we are holding a PENDING lock that ought to be released, then
20527   ** release it now.
20528   */
20529   if( gotPendingLock && locktype==SHARED_LOCK ){
20530     int r;
20531     LockArea.lOffset = 0L;
20532     LockArea.lRange = 0L;
20533     UnlockArea.lOffset = PENDING_BYTE;
20534     UnlockArea.lRange = 1L;
20535     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20536     OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
20537   }
20538
20539   /* Update the state of the lock has held in the file descriptor then
20540   ** return the appropriate result code.
20541   */
20542   if( res == NO_ERROR ){
20543     rc = SQLITE_OK;
20544   }else{
20545     OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
20546               locktype, newLocktype );
20547     rc = SQLITE_BUSY;
20548   }
20549   pFile->locktype = newLocktype;
20550   OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
20551   return rc;
20552 }
20553
20554 /*
20555 ** This routine checks if there is a RESERVED lock held on the specified
20556 ** file by this or any other process. If such a lock is held, return
20557 ** non-zero, otherwise zero.
20558 */
20559 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
20560   int r = 0;
20561   os2File *pFile = (os2File*)id;
20562   assert( pFile!=0 );
20563   if( pFile->locktype>=RESERVED_LOCK ){
20564     r = 1;
20565     OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
20566   }else{
20567     FILELOCK  LockArea,
20568               UnlockArea;
20569     APIRET rc = NO_ERROR;
20570     memset(&LockArea, 0, sizeof(LockArea));
20571     memset(&UnlockArea, 0, sizeof(UnlockArea));
20572     LockArea.lOffset = RESERVED_BYTE;
20573     LockArea.lRange = 1L;
20574     UnlockArea.lOffset = 0L;
20575     UnlockArea.lRange = 0L;
20576     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20577     OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
20578     if( rc == NO_ERROR ){
20579       APIRET rcu = NO_ERROR; /* return code for unlocking */
20580       LockArea.lOffset = 0L;
20581       LockArea.lRange = 0L;
20582       UnlockArea.lOffset = RESERVED_BYTE;
20583       UnlockArea.lRange = 1L;
20584       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20585       OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
20586     }
20587     r = !(rc == NO_ERROR);
20588     OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
20589   }
20590   *pOut = r;
20591   return SQLITE_OK;
20592 }
20593
20594 /*
20595 ** Lower the locking level on file descriptor id to locktype.  locktype
20596 ** must be either NO_LOCK or SHARED_LOCK.
20597 **
20598 ** If the locking level of the file descriptor is already at or below
20599 ** the requested locking level, this routine is a no-op.
20600 **
20601 ** It is not possible for this routine to fail if the second argument
20602 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
20603 ** might return SQLITE_IOERR;
20604 */
20605 static int os2Unlock( sqlite3_file *id, int locktype ){
20606   int type;
20607   os2File *pFile = (os2File*)id;
20608   APIRET rc = SQLITE_OK;
20609   APIRET res = NO_ERROR;
20610   FILELOCK  LockArea,
20611             UnlockArea;
20612   memset(&LockArea, 0, sizeof(LockArea));
20613   memset(&UnlockArea, 0, sizeof(UnlockArea));
20614   assert( pFile!=0 );
20615   assert( locktype<=SHARED_LOCK );
20616   OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
20617   type = pFile->locktype;
20618   if( type>=EXCLUSIVE_LOCK ){
20619     LockArea.lOffset = 0L;
20620     LockArea.lRange = 0L;
20621     UnlockArea.lOffset = SHARED_FIRST;
20622     UnlockArea.lRange = SHARED_SIZE;
20623     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20624     OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
20625     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
20626       /* This should never happen.  We should always be able to
20627       ** reacquire the read lock */
20628       OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
20629       rc = SQLITE_IOERR_UNLOCK;
20630     }
20631   }
20632   if( type>=RESERVED_LOCK ){
20633     LockArea.lOffset = 0L;
20634     LockArea.lRange = 0L;
20635     UnlockArea.lOffset = RESERVED_BYTE;
20636     UnlockArea.lRange = 1L;
20637     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20638     OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
20639   }
20640   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
20641     res = unlockReadLock(pFile);
20642     OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
20643   }
20644   if( type>=PENDING_LOCK ){
20645     LockArea.lOffset = 0L;
20646     LockArea.lRange = 0L;
20647     UnlockArea.lOffset = PENDING_BYTE;
20648     UnlockArea.lRange = 1L;
20649     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20650     OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
20651   }
20652   pFile->locktype = locktype;
20653   OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
20654   return rc;
20655 }
20656
20657 /*
20658 ** Control and query of the open file handle.
20659 */
20660 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
20661   switch( op ){
20662     case SQLITE_FCNTL_LOCKSTATE: {
20663       *(int*)pArg = ((os2File*)id)->locktype;
20664       OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
20665       return SQLITE_OK;
20666     }
20667   }
20668   return SQLITE_ERROR;
20669 }
20670
20671 /*
20672 ** Return the sector size in bytes of the underlying block device for
20673 ** the specified file. This is almost always 512 bytes, but may be
20674 ** larger for some devices.
20675 **
20676 ** SQLite code assumes this function cannot fail. It also assumes that
20677 ** if two files are created in the same file-system directory (i.e.
20678 ** a database and its journal file) that the sector size will be the
20679 ** same for both.
20680 */
20681 static int os2SectorSize(sqlite3_file *id){
20682   return SQLITE_DEFAULT_SECTOR_SIZE;
20683 }
20684
20685 /*
20686 ** Return a vector of device characteristics.
20687 */
20688 static int os2DeviceCharacteristics(sqlite3_file *id){
20689   return 0;
20690 }
20691
20692
20693 /*
20694 ** Character set conversion objects used by conversion routines.
20695 */
20696 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
20697 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
20698
20699 /*
20700 ** Helper function to initialize the conversion objects from and to UTF-8.
20701 */
20702 static void initUconvObjects( void ){
20703   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
20704     ucUtf8 = NULL;
20705   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
20706     uclCp = NULL;
20707 }
20708
20709 /*
20710 ** Helper function to free the conversion objects from and to UTF-8.
20711 */
20712 static void freeUconvObjects( void ){
20713   if ( ucUtf8 )
20714     UniFreeUconvObject( ucUtf8 );
20715   if ( uclCp )
20716     UniFreeUconvObject( uclCp );
20717   ucUtf8 = NULL;
20718   uclCp = NULL;
20719 }
20720
20721 /*
20722 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
20723 ** The two-step process: first convert the incoming UTF-8 string
20724 ** into UCS-2 and then from UCS-2 to the current codepage.
20725 ** The returned char pointer has to be freed.
20726 */
20727 static char *convertUtf8PathToCp( const char *in ){
20728   UniChar tempPath[CCHMAXPATH];
20729   char *out = (char *)calloc( CCHMAXPATH, 1 );
20730
20731   if( !out )
20732     return NULL;
20733
20734   if( !ucUtf8 || !uclCp )
20735     initUconvObjects();
20736
20737   /* determine string for the conversion of UTF-8 which is CP1208 */
20738   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
20739     return out; /* if conversion fails, return the empty string */
20740
20741   /* conversion for current codepage which can be used for paths */
20742   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
20743
20744   return out;
20745 }
20746
20747 /*
20748 ** Helper function to convert filenames from local codepage to UTF-8.
20749 ** The two-step process: first convert the incoming codepage-specific
20750 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
20751 ** The returned char pointer has to be freed.
20752 **
20753 ** This function is non-static to be able to use this in shell.c and
20754 ** similar applications that take command line arguments.
20755 */
20756 char *convertCpPathToUtf8( const char *in ){
20757   UniChar tempPath[CCHMAXPATH];
20758   char *out = (char *)calloc( CCHMAXPATH, 1 );
20759
20760   if( !out )
20761     return NULL;
20762
20763   if( !ucUtf8 || !uclCp )
20764     initUconvObjects();
20765
20766   /* conversion for current codepage which can be used for paths */
20767   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
20768     return out; /* if conversion fails, return the empty string */
20769
20770   /* determine string for the conversion of UTF-8 which is CP1208 */
20771   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
20772
20773   return out;
20774 }
20775
20776 /*
20777 ** This vector defines all the methods that can operate on an
20778 ** sqlite3_file for os2.
20779 */
20780 static const sqlite3_io_methods os2IoMethod = {
20781   1,                        /* iVersion */
20782   os2Close,
20783   os2Read,
20784   os2Write,
20785   os2Truncate,
20786   os2Sync,
20787   os2FileSize,
20788   os2Lock,
20789   os2Unlock,
20790   os2CheckReservedLock,
20791   os2FileControl,
20792   os2SectorSize,
20793   os2DeviceCharacteristics
20794 };
20795
20796 /***************************************************************************
20797 ** Here ends the I/O methods that form the sqlite3_io_methods object.
20798 **
20799 ** The next block of code implements the VFS methods.
20800 ****************************************************************************/
20801
20802 /*
20803 ** Create a temporary file name in zBuf.  zBuf must be big enough to
20804 ** hold at pVfs->mxPathname characters.
20805 */
20806 static int getTempname(int nBuf, char *zBuf ){
20807   static const unsigned char zChars[] =
20808     "abcdefghijklmnopqrstuvwxyz"
20809     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
20810     "0123456789";
20811   int i, j;
20812   char zTempPathBuf[3];
20813   PSZ zTempPath = (PSZ)&zTempPathBuf;
20814   if( sqlite3_temp_directory ){
20815     zTempPath = sqlite3_temp_directory;
20816   }else{
20817     if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
20818       if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
20819         if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
20820            ULONG ulDriveNum = 0, ulDriveMap = 0;
20821            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
20822            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
20823         }
20824       }
20825     }
20826   }
20827   /* Strip off a trailing slashes or backslashes, otherwise we would get *
20828    * multiple (back)slashes which causes DosOpen() to fail.              *
20829    * Trailing spaces are not allowed, either.                            */
20830   j = sqlite3Strlen30(zTempPath);
20831   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
20832                     || zTempPath[j-1] == ' ' ) ){
20833     j--;
20834   }
20835   zTempPath[j] = '\0';
20836   if( !sqlite3_temp_directory ){
20837     char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
20838     sqlite3_snprintf( nBuf-30, zBuf,
20839                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
20840     free( zTempPathUTF );
20841   }else{
20842     sqlite3_snprintf( nBuf-30, zBuf,
20843                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
20844   }
20845   j = sqlite3Strlen30( zBuf );
20846   sqlite3_randomness( 20, &zBuf[j] );
20847   for( i = 0; i < 20; i++, j++ ){
20848     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
20849   }
20850   zBuf[j] = 0;
20851   OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
20852   return SQLITE_OK;
20853 }
20854
20855
20856 /*
20857 ** Turn a relative pathname into a full pathname.  Write the full
20858 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
20859 ** bytes in size.
20860 */
20861 static int os2FullPathname(
20862   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
20863   const char *zRelative,      /* Possibly relative input path */
20864   int nFull,                  /* Size of output buffer in bytes */
20865   char *zFull                 /* Output buffer */
20866 ){
20867   char *zRelativeCp = convertUtf8PathToCp( zRelative );
20868   char zFullCp[CCHMAXPATH] = "\0";
20869   char *zFullUTF;
20870   APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
20871                                 CCHMAXPATH );
20872   free( zRelativeCp );
20873   zFullUTF = convertCpPathToUtf8( zFullCp );
20874   sqlite3_snprintf( nFull, zFull, zFullUTF );
20875   free( zFullUTF );
20876   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20877 }
20878
20879
20880 /*
20881 ** Open a file.
20882 */
20883 static int os2Open(
20884   sqlite3_vfs *pVfs,            /* Not used */
20885   const char *zName,            /* Name of the file */
20886   sqlite3_file *id,             /* Write the SQLite file handle here */
20887   int flags,                    /* Open mode flags */
20888   int *pOutFlags                /* Status return flags */
20889 ){
20890   HFILE h;
20891   ULONG ulFileAttribute = FILE_NORMAL;
20892   ULONG ulOpenFlags = 0;
20893   ULONG ulOpenMode = 0;
20894   os2File *pFile = (os2File*)id;
20895   APIRET rc = NO_ERROR;
20896   ULONG ulAction;
20897   char *zNameCp;
20898   char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
20899
20900   /* If the second argument to this function is NULL, generate a 
20901   ** temporary file name to use 
20902   */
20903   if( !zName ){
20904     int rc = getTempname(CCHMAXPATH+1, zTmpname);
20905     if( rc!=SQLITE_OK ){
20906       return rc;
20907     }
20908     zName = zTmpname;
20909   }
20910
20911
20912   memset( pFile, 0, sizeof(*pFile) );
20913
20914   OSTRACE2( "OPEN want %d\n", flags );
20915
20916   if( flags & SQLITE_OPEN_READWRITE ){
20917     ulOpenMode |= OPEN_ACCESS_READWRITE;
20918     OSTRACE1( "OPEN read/write\n" );
20919   }else{
20920     ulOpenMode |= OPEN_ACCESS_READONLY;
20921     OSTRACE1( "OPEN read only\n" );
20922   }
20923
20924   if( flags & SQLITE_OPEN_CREATE ){
20925     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
20926     OSTRACE1( "OPEN open new/create\n" );
20927   }else{
20928     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
20929     OSTRACE1( "OPEN open existing\n" );
20930   }
20931
20932   if( flags & SQLITE_OPEN_MAIN_DB ){
20933     ulOpenMode |= OPEN_SHARE_DENYNONE;
20934     OSTRACE1( "OPEN share read/write\n" );
20935   }else{
20936     ulOpenMode |= OPEN_SHARE_DENYWRITE;
20937     OSTRACE1( "OPEN share read only\n" );
20938   }
20939
20940   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
20941     char pathUtf8[CCHMAXPATH];
20942 #ifdef NDEBUG /* when debugging we want to make sure it is deleted */
20943     ulFileAttribute = FILE_HIDDEN;
20944 #endif
20945     os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
20946     pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
20947     OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
20948   }else{
20949     pFile->pathToDel = NULL;
20950     OSTRACE1( "OPEN normal file attribute\n" );
20951   }
20952
20953   /* always open in random access mode for possibly better speed */
20954   ulOpenMode |= OPEN_FLAGS_RANDOM;
20955   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
20956   ulOpenMode |= OPEN_FLAGS_NOINHERIT;
20957
20958   zNameCp = convertUtf8PathToCp( zName );
20959   rc = DosOpen( (PSZ)zNameCp,
20960                 &h,
20961                 &ulAction,
20962                 0L,
20963                 ulFileAttribute,
20964                 ulOpenFlags,
20965                 ulOpenMode,
20966                 (PEAOP2)NULL );
20967   free( zNameCp );
20968   if( rc != NO_ERROR ){
20969     OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
20970               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
20971     if( pFile->pathToDel )
20972       free( pFile->pathToDel );
20973     pFile->pathToDel = NULL;
20974     if( flags & SQLITE_OPEN_READWRITE ){
20975       OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
20976       return os2Open( pVfs, zName, id,
20977                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
20978                       pOutFlags );
20979     }else{
20980       return SQLITE_CANTOPEN;
20981     }
20982   }
20983
20984   if( pOutFlags ){
20985     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
20986   }
20987
20988   pFile->pMethod = &os2IoMethod;
20989   pFile->h = h;
20990   OpenCounter(+1);
20991   OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
20992   return SQLITE_OK;
20993 }
20994
20995 /*
20996 ** Delete the named file.
20997 */
20998 static int os2Delete(
20999   sqlite3_vfs *pVfs,                     /* Not used on os2 */
21000   const char *zFilename,                 /* Name of file to delete */
21001   int syncDir                            /* Not used on os2 */
21002 ){
21003   APIRET rc = NO_ERROR;
21004   char *zFilenameCp = convertUtf8PathToCp( zFilename );
21005   SimulateIOError( return SQLITE_IOERR_DELETE );
21006   rc = DosDelete( (PSZ)zFilenameCp );
21007   free( zFilenameCp );
21008   OSTRACE2( "DELETE \"%s\"\n", zFilename );
21009   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
21010 }
21011
21012 /*
21013 ** Check the existance and status of a file.
21014 */
21015 static int os2Access(
21016   sqlite3_vfs *pVfs,        /* Not used on os2 */
21017   const char *zFilename,    /* Name of file to check */
21018   int flags,                /* Type of test to make on this file */
21019   int *pOut                 /* Write results here */
21020 ){
21021   FILESTATUS3 fsts3ConfigInfo;
21022   APIRET rc = NO_ERROR;
21023   char *zFilenameCp = convertUtf8PathToCp( zFilename );
21024
21025   memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
21026   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
21027                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
21028   free( zFilenameCp );
21029   OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
21030             fsts3ConfigInfo.attrFile, flags, rc );
21031   switch( flags ){
21032     case SQLITE_ACCESS_READ:
21033     case SQLITE_ACCESS_EXISTS:
21034       rc = (rc == NO_ERROR);
21035       OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
21036       break;
21037     case SQLITE_ACCESS_READWRITE:
21038       rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
21039       OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
21040       break;
21041     default:
21042       assert( !"Invalid flags argument" );
21043   }
21044   *pOut = rc;
21045   return SQLITE_OK;
21046 }
21047
21048
21049 #ifndef SQLITE_OMIT_LOAD_EXTENSION
21050 /*
21051 ** Interfaces for opening a shared library, finding entry points
21052 ** within the shared library, and closing the shared library.
21053 */
21054 /*
21055 ** Interfaces for opening a shared library, finding entry points
21056 ** within the shared library, and closing the shared library.
21057 */
21058 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
21059   UCHAR loadErr[256];
21060   HMODULE hmod;
21061   APIRET rc;
21062   char *zFilenameCp = convertUtf8PathToCp(zFilename);
21063   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
21064   free(zFilenameCp);
21065   return rc != NO_ERROR ? 0 : (void*)hmod;
21066 }
21067 /*
21068 ** A no-op since the error code is returned on the DosLoadModule call.
21069 ** os2Dlopen returns zero if DosLoadModule is not successful.
21070 */
21071 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
21072 /* no-op */
21073 }
21074 static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
21075   PFN pfn;
21076   APIRET rc;
21077   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
21078   if( rc != NO_ERROR ){
21079     /* if the symbol itself was not found, search again for the same
21080      * symbol with an extra underscore, that might be needed depending
21081      * on the calling convention */
21082     char _zSymbol[256] = "_";
21083     strncat(_zSymbol, zSymbol, 255);
21084     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
21085   }
21086   return rc != NO_ERROR ? 0 : (void*)pfn;
21087 }
21088 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
21089   DosFreeModule((HMODULE)pHandle);
21090 }
21091 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
21092   #define os2DlOpen 0
21093   #define os2DlError 0
21094   #define os2DlSym 0
21095   #define os2DlClose 0
21096 #endif
21097
21098
21099 /*
21100 ** Write up to nBuf bytes of randomness into zBuf.
21101 */
21102 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
21103   int n = 0;
21104 #if defined(SQLITE_TEST)
21105   n = nBuf;
21106   memset(zBuf, 0, nBuf);
21107 #else
21108   int sizeofULong = sizeof(ULONG);
21109   if( (int)sizeof(DATETIME) <= nBuf - n ){
21110     DATETIME x;
21111     DosGetDateTime(&x);
21112     memcpy(&zBuf[n], &x, sizeof(x));
21113     n += sizeof(x);
21114   }
21115
21116   if( sizeofULong <= nBuf - n ){
21117     PPIB ppib;
21118     DosGetInfoBlocks(NULL, &ppib);
21119     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
21120     n += sizeofULong;
21121   }
21122
21123   if( sizeofULong <= nBuf - n ){
21124     PTIB ptib;
21125     DosGetInfoBlocks(&ptib, NULL);
21126     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
21127     n += sizeofULong;
21128   }
21129
21130   /* if we still haven't filled the buffer yet the following will */
21131   /* grab everything once instead of making several calls for a single item */
21132   if( sizeofULong <= nBuf - n ){
21133     ULONG ulSysInfo[QSV_MAX];
21134     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
21135
21136     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
21137     n += sizeofULong;
21138
21139     if( sizeofULong <= nBuf - n ){
21140       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
21141       n += sizeofULong;
21142     }
21143     if( sizeofULong <= nBuf - n ){
21144       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
21145       n += sizeofULong;
21146     }
21147     if( sizeofULong <= nBuf - n ){
21148       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
21149       n += sizeofULong;
21150     }
21151     if( sizeofULong <= nBuf - n ){
21152       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
21153       n += sizeofULong;
21154     }
21155   }
21156 #endif
21157
21158   return n;
21159 }
21160
21161 /*
21162 ** Sleep for a little while.  Return the amount of time slept.
21163 ** The argument is the number of microseconds we want to sleep.
21164 ** The return value is the number of microseconds of sleep actually
21165 ** requested from the underlying operating system, a number which
21166 ** might be greater than or equal to the argument, but not less
21167 ** than the argument.
21168 */
21169 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
21170   DosSleep( (microsec/1000) );
21171   return microsec;
21172 }
21173
21174 /*
21175 ** The following variable, if set to a non-zero value, becomes the result
21176 ** returned from sqlite3OsCurrentTime().  This is used for testing.
21177 */
21178 #ifdef SQLITE_TEST
21179 SQLITE_API int sqlite3_current_time = 0;
21180 #endif
21181
21182 /*
21183 ** Find the current time (in Universal Coordinated Time).  Write the
21184 ** current time and date as a Julian Day number into *prNow and
21185 ** return 0.  Return 1 if the time and date cannot be found.
21186 */
21187 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
21188   double now;
21189   SHORT minute; /* needs to be able to cope with negative timezone offset */
21190   USHORT second, hour,
21191          day, month, year;
21192   DATETIME dt;
21193   DosGetDateTime( &dt );
21194   second = (USHORT)dt.seconds;
21195   minute = (SHORT)dt.minutes + dt.timezone;
21196   hour = (USHORT)dt.hours;
21197   day = (USHORT)dt.day;
21198   month = (USHORT)dt.month;
21199   year = (USHORT)dt.year;
21200
21201   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
21202      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
21203   /* Calculate the Julian days */
21204   now = day - 32076 +
21205     1461*(year + 4800 + (month - 14)/12)/4 +
21206     367*(month - 2 - (month - 14)/12*12)/12 -
21207     3*((year + 4900 + (month - 14)/12)/100)/4;
21208
21209   /* Add the fractional hours, mins and seconds */
21210   now += (hour + 12.0)/24.0;
21211   now += minute/1440.0;
21212   now += second/86400.0;
21213   *prNow = now;
21214 #ifdef SQLITE_TEST
21215   if( sqlite3_current_time ){
21216     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
21217   }
21218 #endif
21219   return 0;
21220 }
21221
21222 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
21223   return 0;
21224 }
21225
21226 /*
21227 ** Initialize and deinitialize the operating system interface.
21228 */
21229 SQLITE_API int sqlite3_os_init(void){
21230   static sqlite3_vfs os2Vfs = {
21231     1,                 /* iVersion */
21232     sizeof(os2File),   /* szOsFile */
21233     CCHMAXPATH,        /* mxPathname */
21234     0,                 /* pNext */
21235     "os2",             /* zName */
21236     0,                 /* pAppData */
21237
21238     os2Open,           /* xOpen */
21239     os2Delete,         /* xDelete */
21240     os2Access,         /* xAccess */
21241     os2FullPathname,   /* xFullPathname */
21242     os2DlOpen,         /* xDlOpen */
21243     os2DlError,        /* xDlError */
21244     os2DlSym,          /* xDlSym */
21245     os2DlClose,        /* xDlClose */
21246     os2Randomness,     /* xRandomness */
21247     os2Sleep,          /* xSleep */
21248     os2CurrentTime,    /* xCurrentTime */
21249     os2GetLastError    /* xGetLastError */
21250   };
21251   sqlite3_vfs_register(&os2Vfs, 1);
21252   initUconvObjects();
21253   return SQLITE_OK;
21254 }
21255 SQLITE_API int sqlite3_os_end(void){
21256   freeUconvObjects();
21257   return SQLITE_OK;
21258 }
21259
21260 #endif /* SQLITE_OS_OS2 */
21261
21262 /************** End of os_os2.c **********************************************/
21263 /************** Begin file os_unix.c *****************************************/
21264 /*
21265 ** 2004 May 22
21266 **
21267 ** The author disclaims copyright to this source code.  In place of
21268 ** a legal notice, here is a blessing:
21269 **
21270 **    May you do good and not evil.
21271 **    May you find forgiveness for yourself and forgive others.
21272 **    May you share freely, never taking more than you give.
21273 **
21274 ******************************************************************************
21275 **
21276 ** This file contains the VFS implementation for unix-like operating systems
21277 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
21278 **
21279 ** There are actually several different VFS implementations in this file.
21280 ** The differences are in the way that file locking is done.  The default
21281 ** implementation uses Posix Advisory Locks.  Alternative implementations
21282 ** use flock(), dot-files, various proprietary locking schemas, or simply
21283 ** skip locking all together.
21284 **
21285 ** This source file is organized into divisions where the logic for various
21286 ** subfunctions is contained within the appropriate division.  PLEASE
21287 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
21288 ** in the correct division and should be clearly labeled.
21289 **
21290 ** The layout of divisions is as follows:
21291 **
21292 **   *  General-purpose declarations and utility functions.
21293 **   *  Unique file ID logic used by VxWorks.
21294 **   *  Various locking primitive implementations (all except proxy locking):
21295 **      + for Posix Advisory Locks
21296 **      + for no-op locks
21297 **      + for dot-file locks
21298 **      + for flock() locking
21299 **      + for named semaphore locks (VxWorks only)
21300 **      + for AFP filesystem locks (MacOSX only)
21301 **   *  sqlite3_file methods not associated with locking.
21302 **   *  Definitions of sqlite3_io_methods objects for all locking
21303 **      methods plus "finder" functions for each locking method.
21304 **   *  sqlite3_vfs method implementations.
21305 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
21306 **   *  Definitions of sqlite3_vfs objects for all locking methods
21307 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
21308 */
21309 #if SQLITE_OS_UNIX              /* This file is used on unix only */
21310
21311 /*
21312 ** There are various methods for file locking used for concurrency
21313 ** control:
21314 **
21315 **   1. POSIX locking (the default),
21316 **   2. No locking,
21317 **   3. Dot-file locking,
21318 **   4. flock() locking,
21319 **   5. AFP locking (OSX only),
21320 **   6. Named POSIX semaphores (VXWorks only),
21321 **   7. proxy locking. (OSX only)
21322 **
21323 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
21324 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
21325 ** selection of the appropriate locking style based on the filesystem
21326 ** where the database is located.  
21327 */
21328 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
21329 #  if defined(__APPLE__)
21330 #    define SQLITE_ENABLE_LOCKING_STYLE 1
21331 #  else
21332 #    define SQLITE_ENABLE_LOCKING_STYLE 0
21333 #  endif
21334 #endif
21335
21336 /*
21337 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
21338 ** vxworks, or 0 otherwise.
21339 */
21340 #ifndef OS_VXWORKS
21341 #  if defined(__RTP__) || defined(_WRS_KERNEL)
21342 #    define OS_VXWORKS 1
21343 #  else
21344 #    define OS_VXWORKS 0
21345 #  endif
21346 #endif
21347
21348 /*
21349 ** These #defines should enable >2GB file support on Posix if the
21350 ** underlying operating system supports it.  If the OS lacks
21351 ** large file support, these should be no-ops.
21352 **
21353 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
21354 ** on the compiler command line.  This is necessary if you are compiling
21355 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
21356 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
21357 ** without this option, LFS is enable.  But LFS does not exist in the kernel
21358 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
21359 ** portability you should omit LFS.
21360 **
21361 ** The previous paragraph was written in 2005.  (This paragraph is written
21362 ** on 2008-11-28.) These days, all Linux kernels support large files, so
21363 ** you should probably leave LFS enabled.  But some embedded platforms might
21364 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
21365 */
21366 #ifndef SQLITE_DISABLE_LFS
21367 # define _LARGE_FILE       1
21368 # ifndef _FILE_OFFSET_BITS
21369 #   define _FILE_OFFSET_BITS 64
21370 # endif
21371 # define _LARGEFILE_SOURCE 1
21372 #endif
21373
21374 /*
21375 ** standard include files.
21376 */
21377 #include <sys/types.h>
21378 #include <sys/stat.h>
21379 #include <fcntl.h>
21380 #include <unistd.h>
21381 #include <sys/time.h>
21382 #include <errno.h>
21383
21384 #if SQLITE_ENABLE_LOCKING_STYLE
21385 # include <sys/ioctl.h>
21386 # if OS_VXWORKS
21387 #  include <semaphore.h>
21388 #  include <limits.h>
21389 # else
21390 #  include <sys/file.h>
21391 #  include <sys/param.h>
21392 #  include <sys/mount.h>
21393 # endif
21394 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
21395
21396 /*
21397 ** If we are to be thread-safe, include the pthreads header and define
21398 ** the SQLITE_UNIX_THREADS macro.
21399 */
21400 #if SQLITE_THREADSAFE
21401 # define SQLITE_UNIX_THREADS 1
21402 #endif
21403
21404 /*
21405 ** Default permissions when creating a new file
21406 */
21407 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
21408 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
21409 #endif
21410
21411 /*
21412  ** Default permissions when creating auto proxy dir
21413  */
21414 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
21415 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
21416 #endif
21417
21418 /*
21419 ** Maximum supported path-length.
21420 */
21421 #define MAX_PATHNAME 512
21422
21423 /*
21424 ** Only set the lastErrno if the error code is a real error and not 
21425 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
21426 */
21427 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
21428
21429
21430 /*
21431 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
21432 ** cannot be closed immediately. In these cases, instances of the following
21433 ** structure are used to store the file descriptor while waiting for an
21434 ** opportunity to either close or reuse it.
21435 */
21436 typedef struct UnixUnusedFd UnixUnusedFd;
21437 struct UnixUnusedFd {
21438   int fd;                   /* File descriptor to close */
21439   int flags;                /* Flags this file descriptor was opened with */
21440   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
21441 };
21442
21443 /*
21444 ** The unixFile structure is subclass of sqlite3_file specific to the unix
21445 ** VFS implementations.
21446 */
21447 typedef struct unixFile unixFile;
21448 struct unixFile {
21449   sqlite3_io_methods const *pMethod;  /* Always the first entry */
21450   struct unixOpenCnt *pOpen;       /* Info about all open fd's on this inode */
21451   struct unixLockInfo *pLock;      /* Info about locks on this inode */
21452   int h;                           /* The file descriptor */
21453   int dirfd;                       /* File descriptor for the directory */
21454   unsigned char locktype;          /* The type of lock held on this fd */
21455   int lastErrno;                   /* The unix errno from the last I/O error */
21456   void *lockingContext;            /* Locking style specific state */
21457   UnixUnusedFd *pUnused;           /* Pre-allocated UnixUnusedFd */
21458   int fileFlags;                   /* Miscellanous flags */
21459 #if SQLITE_ENABLE_LOCKING_STYLE
21460   int openFlags;                   /* The flags specified at open() */
21461 #endif
21462 #if SQLITE_THREADSAFE && defined(__linux__)
21463   pthread_t tid;                   /* The thread that "owns" this unixFile */
21464 #endif
21465 #if OS_VXWORKS
21466   int isDelete;                    /* Delete on close if true */
21467   struct vxworksFileId *pId;       /* Unique file ID */
21468 #endif
21469 #ifndef NDEBUG
21470   /* The next group of variables are used to track whether or not the
21471   ** transaction counter in bytes 24-27 of database files are updated
21472   ** whenever any part of the database changes.  An assertion fault will
21473   ** occur if a file is updated without also updating the transaction
21474   ** counter.  This test is made to avoid new problems similar to the
21475   ** one described by ticket #3584. 
21476   */
21477   unsigned char transCntrChng;   /* True if the transaction counter changed */
21478   unsigned char dbUpdate;        /* True if any part of database file changed */
21479   unsigned char inNormalWrite;   /* True if in a normal write operation */
21480 #endif
21481 #ifdef SQLITE_TEST
21482   /* In test mode, increase the size of this structure a bit so that 
21483   ** it is larger than the struct CrashFile defined in test6.c.
21484   */
21485   char aPadding[32];
21486 #endif
21487 };
21488
21489 /*
21490 ** The following macros define bits in unixFile.fileFlags
21491 */
21492 #define SQLITE_WHOLE_FILE_LOCKING  0x0001   /* Use whole-file locking */
21493
21494 /*
21495 ** Include code that is common to all os_*.c files
21496 */
21497 /************** Include os_common.h in the middle of os_unix.c ***************/
21498 /************** Begin file os_common.h ***************************************/
21499 /*
21500 ** 2004 May 22
21501 **
21502 ** The author disclaims copyright to this source code.  In place of
21503 ** a legal notice, here is a blessing:
21504 **
21505 **    May you do good and not evil.
21506 **    May you find forgiveness for yourself and forgive others.
21507 **    May you share freely, never taking more than you give.
21508 **
21509 ******************************************************************************
21510 **
21511 ** This file contains macros and a little bit of code that is common to
21512 ** all of the platform-specific files (os_*.c) and is #included into those
21513 ** files.
21514 **
21515 ** This file should be #included by the os_*.c files only.  It is not a
21516 ** general purpose header file.
21517 */
21518 #ifndef _OS_COMMON_H_
21519 #define _OS_COMMON_H_
21520
21521 /*
21522 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21523 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21524 ** switch.  The following code should catch this problem at compile-time.
21525 */
21526 #ifdef MEMORY_DEBUG
21527 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21528 #endif
21529
21530 #ifdef SQLITE_DEBUG
21531 SQLITE_PRIVATE int sqlite3OSTrace = 0;
21532 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
21533 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
21534 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
21535 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
21536 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
21537 #define OSTRACE6(X,Y,Z,A,B,C) \
21538     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
21539 #define OSTRACE7(X,Y,Z,A,B,C,D) \
21540     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
21541 #else
21542 #define OSTRACE1(X)
21543 #define OSTRACE2(X,Y)
21544 #define OSTRACE3(X,Y,Z)
21545 #define OSTRACE4(X,Y,Z,A)
21546 #define OSTRACE5(X,Y,Z,A,B)
21547 #define OSTRACE6(X,Y,Z,A,B,C)
21548 #define OSTRACE7(X,Y,Z,A,B,C,D)
21549 #endif
21550
21551 /*
21552 ** Macros for performance tracing.  Normally turned off.  Only works
21553 ** on i486 hardware.
21554 */
21555 #ifdef SQLITE_PERFORMANCE_TRACE
21556
21557 /* 
21558 ** hwtime.h contains inline assembler code for implementing 
21559 ** high-performance timing routines.
21560 */
21561 /************** Include hwtime.h in the middle of os_common.h ****************/
21562 /************** Begin file hwtime.h ******************************************/
21563 /*
21564 ** 2008 May 27
21565 **
21566 ** The author disclaims copyright to this source code.  In place of
21567 ** a legal notice, here is a blessing:
21568 **
21569 **    May you do good and not evil.
21570 **    May you find forgiveness for yourself and forgive others.
21571 **    May you share freely, never taking more than you give.
21572 **
21573 ******************************************************************************
21574 **
21575 ** This file contains inline asm code for retrieving "high-performance"
21576 ** counters for x86 class CPUs.
21577 */
21578 #ifndef _HWTIME_H_
21579 #define _HWTIME_H_
21580
21581 /*
21582 ** The following routine only works on pentium-class (or newer) processors.
21583 ** It uses the RDTSC opcode to read the cycle count value out of the
21584 ** processor and returns that value.  This can be used for high-res
21585 ** profiling.
21586 */
21587 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
21588       (defined(i386) || defined(__i386__) || defined(_M_IX86))
21589
21590   #if defined(__GNUC__)
21591
21592   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21593      unsigned int lo, hi;
21594      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21595      return (sqlite_uint64)hi << 32 | lo;
21596   }
21597
21598   #elif defined(_MSC_VER)
21599
21600   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21601      __asm {
21602         rdtsc
21603         ret       ; return value at EDX:EAX
21604      }
21605   }
21606
21607   #endif
21608
21609 #elif (defined(__GNUC__) && defined(__x86_64__))
21610
21611   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21612       unsigned long val;
21613       __asm__ __volatile__ ("rdtsc" : "=A" (val));
21614       return val;
21615   }
21616  
21617 #elif (defined(__GNUC__) && defined(__ppc__))
21618
21619   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21620       unsigned long long retval;
21621       unsigned long junk;
21622       __asm__ __volatile__ ("\n\
21623           1:      mftbu   %1\n\
21624                   mftb    %L0\n\
21625                   mftbu   %0\n\
21626                   cmpw    %0,%1\n\
21627                   bne     1b"
21628                   : "=r" (retval), "=r" (junk));
21629       return retval;
21630   }
21631
21632 #else
21633
21634   #error Need implementation of sqlite3Hwtime() for your platform.
21635
21636   /*
21637   ** To compile without implementing sqlite3Hwtime() for your platform,
21638   ** you can remove the above #error and use the following
21639   ** stub function.  You will lose timing support for many
21640   ** of the debugging and testing utilities, but it should at
21641   ** least compile and run.
21642   */
21643 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21644
21645 #endif
21646
21647 #endif /* !defined(_HWTIME_H_) */
21648
21649 /************** End of hwtime.h **********************************************/
21650 /************** Continuing where we left off in os_common.h ******************/
21651
21652 static sqlite_uint64 g_start;
21653 static sqlite_uint64 g_elapsed;
21654 #define TIMER_START       g_start=sqlite3Hwtime()
21655 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21656 #define TIMER_ELAPSED     g_elapsed
21657 #else
21658 #define TIMER_START
21659 #define TIMER_END
21660 #define TIMER_ELAPSED     ((sqlite_uint64)0)
21661 #endif
21662
21663 /*
21664 ** If we compile with the SQLITE_TEST macro set, then the following block
21665 ** of code will give us the ability to simulate a disk I/O error.  This
21666 ** is used for testing the I/O recovery logic.
21667 */
21668 #ifdef SQLITE_TEST
21669 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21670 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21671 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21672 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21673 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21674 SQLITE_API int sqlite3_diskfull_pending = 0;
21675 SQLITE_API int sqlite3_diskfull = 0;
21676 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21677 #define SimulateIOError(CODE)  \
21678   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21679        || sqlite3_io_error_pending-- == 1 )  \
21680               { local_ioerr(); CODE; }
21681 static void local_ioerr(){
21682   IOTRACE(("IOERR\n"));
21683   sqlite3_io_error_hit++;
21684   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21685 }
21686 #define SimulateDiskfullError(CODE) \
21687    if( sqlite3_diskfull_pending ){ \
21688      if( sqlite3_diskfull_pending == 1 ){ \
21689        local_ioerr(); \
21690        sqlite3_diskfull = 1; \
21691        sqlite3_io_error_hit = 1; \
21692        CODE; \
21693      }else{ \
21694        sqlite3_diskfull_pending--; \
21695      } \
21696    }
21697 #else
21698 #define SimulateIOErrorBenign(X)
21699 #define SimulateIOError(A)
21700 #define SimulateDiskfullError(A)
21701 #endif
21702
21703 /*
21704 ** When testing, keep a count of the number of open files.
21705 */
21706 #ifdef SQLITE_TEST
21707 SQLITE_API int sqlite3_open_file_count = 0;
21708 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
21709 #else
21710 #define OpenCounter(X)
21711 #endif
21712
21713 #endif /* !defined(_OS_COMMON_H_) */
21714
21715 /************** End of os_common.h *******************************************/
21716 /************** Continuing where we left off in os_unix.c ********************/
21717
21718 /*
21719 ** Define various macros that are missing from some systems.
21720 */
21721 #ifndef O_LARGEFILE
21722 # define O_LARGEFILE 0
21723 #endif
21724 #ifdef SQLITE_DISABLE_LFS
21725 # undef O_LARGEFILE
21726 # define O_LARGEFILE 0
21727 #endif
21728 #ifndef O_NOFOLLOW
21729 # define O_NOFOLLOW 0
21730 #endif
21731 #ifndef O_BINARY
21732 # define O_BINARY 0
21733 #endif
21734
21735 /*
21736 ** The DJGPP compiler environment looks mostly like Unix, but it
21737 ** lacks the fcntl() system call.  So redefine fcntl() to be something
21738 ** that always succeeds.  This means that locking does not occur under
21739 ** DJGPP.  But it is DOS - what did you expect?
21740 */
21741 #ifdef __DJGPP__
21742 # define fcntl(A,B,C) 0
21743 #endif
21744
21745 /*
21746 ** The threadid macro resolves to the thread-id or to 0.  Used for
21747 ** testing and debugging only.
21748 */
21749 #if SQLITE_THREADSAFE
21750 #define threadid pthread_self()
21751 #else
21752 #define threadid 0
21753 #endif
21754
21755
21756 /*
21757 ** Helper functions to obtain and relinquish the global mutex. The
21758 ** global mutex is used to protect the unixOpenCnt, unixLockInfo and
21759 ** vxworksFileId objects used by this file, all of which may be 
21760 ** shared by multiple threads.
21761 **
21762 ** Function unixMutexHeld() is used to assert() that the global mutex 
21763 ** is held when required. This function is only used as part of assert() 
21764 ** statements. e.g.
21765 **
21766 **   unixEnterMutex()
21767 **     assert( unixMutexHeld() );
21768 **   unixEnterLeave()
21769 */
21770 static void unixEnterMutex(void){
21771   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21772 }
21773 static void unixLeaveMutex(void){
21774   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21775 }
21776 #ifdef SQLITE_DEBUG
21777 static int unixMutexHeld(void) {
21778   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21779 }
21780 #endif
21781
21782
21783 #ifdef SQLITE_DEBUG
21784 /*
21785 ** Helper function for printing out trace information from debugging
21786 ** binaries. This returns the string represetation of the supplied
21787 ** integer lock-type.
21788 */
21789 static const char *locktypeName(int locktype){
21790   switch( locktype ){
21791     case NO_LOCK: return "NONE";
21792     case SHARED_LOCK: return "SHARED";
21793     case RESERVED_LOCK: return "RESERVED";
21794     case PENDING_LOCK: return "PENDING";
21795     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
21796   }
21797   return "ERROR";
21798 }
21799 #endif
21800
21801 #ifdef SQLITE_LOCK_TRACE
21802 /*
21803 ** Print out information about all locking operations.
21804 **
21805 ** This routine is used for troubleshooting locks on multithreaded
21806 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
21807 ** command-line option on the compiler.  This code is normally
21808 ** turned off.
21809 */
21810 static int lockTrace(int fd, int op, struct flock *p){
21811   char *zOpName, *zType;
21812   int s;
21813   int savedErrno;
21814   if( op==F_GETLK ){
21815     zOpName = "GETLK";
21816   }else if( op==F_SETLK ){
21817     zOpName = "SETLK";
21818   }else{
21819     s = fcntl(fd, op, p);
21820     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
21821     return s;
21822   }
21823   if( p->l_type==F_RDLCK ){
21824     zType = "RDLCK";
21825   }else if( p->l_type==F_WRLCK ){
21826     zType = "WRLCK";
21827   }else if( p->l_type==F_UNLCK ){
21828     zType = "UNLCK";
21829   }else{
21830     assert( 0 );
21831   }
21832   assert( p->l_whence==SEEK_SET );
21833   s = fcntl(fd, op, p);
21834   savedErrno = errno;
21835   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
21836      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
21837      (int)p->l_pid, s);
21838   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
21839     struct flock l2;
21840     l2 = *p;
21841     fcntl(fd, F_GETLK, &l2);
21842     if( l2.l_type==F_RDLCK ){
21843       zType = "RDLCK";
21844     }else if( l2.l_type==F_WRLCK ){
21845       zType = "WRLCK";
21846     }else if( l2.l_type==F_UNLCK ){
21847       zType = "UNLCK";
21848     }else{
21849       assert( 0 );
21850     }
21851     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
21852        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
21853   }
21854   errno = savedErrno;
21855   return s;
21856 }
21857 #define fcntl lockTrace
21858 #endif /* SQLITE_LOCK_TRACE */
21859
21860
21861
21862 /*
21863 ** This routine translates a standard POSIX errno code into something
21864 ** useful to the clients of the sqlite3 functions.  Specifically, it is
21865 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
21866 ** and a variety of "please close the file descriptor NOW" errors into 
21867 ** SQLITE_IOERR
21868 ** 
21869 ** Errors during initialization of locks, or file system support for locks,
21870 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
21871 */
21872 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
21873   switch (posixError) {
21874   case 0: 
21875     return SQLITE_OK;
21876     
21877   case EAGAIN:
21878   case ETIMEDOUT:
21879   case EBUSY:
21880   case EINTR:
21881   case ENOLCK:  
21882     /* random NFS retry error, unless during file system support 
21883      * introspection, in which it actually means what it says */
21884     return SQLITE_BUSY;
21885     
21886   case EACCES: 
21887     /* EACCES is like EAGAIN during locking operations, but not any other time*/
21888     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
21889         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
21890         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
21891         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
21892       return SQLITE_BUSY;
21893     }
21894     /* else fall through */
21895   case EPERM: 
21896     return SQLITE_PERM;
21897     
21898   case EDEADLK:
21899     return SQLITE_IOERR_BLOCKED;
21900     
21901 #if EOPNOTSUPP!=ENOTSUP
21902   case EOPNOTSUPP: 
21903     /* something went terribly awry, unless during file system support 
21904      * introspection, in which it actually means what it says */
21905 #endif
21906 #ifdef ENOTSUP
21907   case ENOTSUP: 
21908     /* invalid fd, unless during file system support introspection, in which 
21909      * it actually means what it says */
21910 #endif
21911   case EIO:
21912   case EBADF:
21913   case EINVAL:
21914   case ENOTCONN:
21915   case ENODEV:
21916   case ENXIO:
21917   case ENOENT:
21918   case ESTALE:
21919   case ENOSYS:
21920     /* these should force the client to close the file and reconnect */
21921     
21922   default: 
21923     return sqliteIOErr;
21924   }
21925 }
21926
21927
21928
21929 /******************************************************************************
21930 ****************** Begin Unique File ID Utility Used By VxWorks ***************
21931 **
21932 ** On most versions of unix, we can get a unique ID for a file by concatenating
21933 ** the device number and the inode number.  But this does not work on VxWorks.
21934 ** On VxWorks, a unique file id must be based on the canonical filename.
21935 **
21936 ** A pointer to an instance of the following structure can be used as a
21937 ** unique file ID in VxWorks.  Each instance of this structure contains
21938 ** a copy of the canonical filename.  There is also a reference count.  
21939 ** The structure is reclaimed when the number of pointers to it drops to
21940 ** zero.
21941 **
21942 ** There are never very many files open at one time and lookups are not
21943 ** a performance-critical path, so it is sufficient to put these
21944 ** structures on a linked list.
21945 */
21946 struct vxworksFileId {
21947   struct vxworksFileId *pNext;  /* Next in a list of them all */
21948   int nRef;                     /* Number of references to this one */
21949   int nName;                    /* Length of the zCanonicalName[] string */
21950   char *zCanonicalName;         /* Canonical filename */
21951 };
21952
21953 #if OS_VXWORKS
21954 /* 
21955 ** All unique filenames are held on a linked list headed by this
21956 ** variable:
21957 */
21958 static struct vxworksFileId *vxworksFileList = 0;
21959
21960 /*
21961 ** Simplify a filename into its canonical form
21962 ** by making the following changes:
21963 **
21964 **  * removing any trailing and duplicate /
21965 **  * convert /./ into just /
21966 **  * convert /A/../ where A is any simple name into just /
21967 **
21968 ** Changes are made in-place.  Return the new name length.
21969 **
21970 ** The original filename is in z[0..n-1].  Return the number of
21971 ** characters in the simplified name.
21972 */
21973 static int vxworksSimplifyName(char *z, int n){
21974   int i, j;
21975   while( n>1 && z[n-1]=='/' ){ n--; }
21976   for(i=j=0; i<n; i++){
21977     if( z[i]=='/' ){
21978       if( z[i+1]=='/' ) continue;
21979       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
21980         i += 1;
21981         continue;
21982       }
21983       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
21984         while( j>0 && z[j-1]!='/' ){ j--; }
21985         if( j>0 ){ j--; }
21986         i += 2;
21987         continue;
21988       }
21989     }
21990     z[j++] = z[i];
21991   }
21992   z[j] = 0;
21993   return j;
21994 }
21995
21996 /*
21997 ** Find a unique file ID for the given absolute pathname.  Return
21998 ** a pointer to the vxworksFileId object.  This pointer is the unique
21999 ** file ID.
22000 **
22001 ** The nRef field of the vxworksFileId object is incremented before
22002 ** the object is returned.  A new vxworksFileId object is created
22003 ** and added to the global list if necessary.
22004 **
22005 ** If a memory allocation error occurs, return NULL.
22006 */
22007 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
22008   struct vxworksFileId *pNew;         /* search key and new file ID */
22009   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
22010   int n;                              /* Length of zAbsoluteName string */
22011
22012   assert( zAbsoluteName[0]=='/' );
22013   n = (int)strlen(zAbsoluteName);
22014   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
22015   if( pNew==0 ) return 0;
22016   pNew->zCanonicalName = (char*)&pNew[1];
22017   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
22018   n = vxworksSimplifyName(pNew->zCanonicalName, n);
22019
22020   /* Search for an existing entry that matching the canonical name.
22021   ** If found, increment the reference count and return a pointer to
22022   ** the existing file ID.
22023   */
22024   unixEnterMutex();
22025   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
22026     if( pCandidate->nName==n 
22027      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
22028     ){
22029        sqlite3_free(pNew);
22030        pCandidate->nRef++;
22031        unixLeaveMutex();
22032        return pCandidate;
22033     }
22034   }
22035
22036   /* No match was found.  We will make a new file ID */
22037   pNew->nRef = 1;
22038   pNew->nName = n;
22039   pNew->pNext = vxworksFileList;
22040   vxworksFileList = pNew;
22041   unixLeaveMutex();
22042   return pNew;
22043 }
22044
22045 /*
22046 ** Decrement the reference count on a vxworksFileId object.  Free
22047 ** the object when the reference count reaches zero.
22048 */
22049 static void vxworksReleaseFileId(struct vxworksFileId *pId){
22050   unixEnterMutex();
22051   assert( pId->nRef>0 );
22052   pId->nRef--;
22053   if( pId->nRef==0 ){
22054     struct vxworksFileId **pp;
22055     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
22056     assert( *pp==pId );
22057     *pp = pId->pNext;
22058     sqlite3_free(pId);
22059   }
22060   unixLeaveMutex();
22061 }
22062 #endif /* OS_VXWORKS */
22063 /*************** End of Unique File ID Utility Used By VxWorks ****************
22064 ******************************************************************************/
22065
22066
22067 /******************************************************************************
22068 *************************** Posix Advisory Locking ****************************
22069 **
22070 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
22071 ** section 6.5.2.2 lines 483 through 490 specify that when a process
22072 ** sets or clears a lock, that operation overrides any prior locks set
22073 ** by the same process.  It does not explicitly say so, but this implies
22074 ** that it overrides locks set by the same process using a different
22075 ** file descriptor.  Consider this test case:
22076 **
22077 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
22078 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
22079 **
22080 ** Suppose ./file1 and ./file2 are really the same file (because
22081 ** one is a hard or symbolic link to the other) then if you set
22082 ** an exclusive lock on fd1, then try to get an exclusive lock
22083 ** on fd2, it works.  I would have expected the second lock to
22084 ** fail since there was already a lock on the file due to fd1.
22085 ** But not so.  Since both locks came from the same process, the
22086 ** second overrides the first, even though they were on different
22087 ** file descriptors opened on different file names.
22088 **
22089 ** This means that we cannot use POSIX locks to synchronize file access
22090 ** among competing threads of the same process.  POSIX locks will work fine
22091 ** to synchronize access for threads in separate processes, but not
22092 ** threads within the same process.
22093 **
22094 ** To work around the problem, SQLite has to manage file locks internally
22095 ** on its own.  Whenever a new database is opened, we have to find the
22096 ** specific inode of the database file (the inode is determined by the
22097 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
22098 ** and check for locks already existing on that inode.  When locks are
22099 ** created or removed, we have to look at our own internal record of the
22100 ** locks to see if another thread has previously set a lock on that same
22101 ** inode.
22102 **
22103 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
22104 ** For VxWorks, we have to use the alternative unique ID system based on
22105 ** canonical filename and implemented in the previous division.)
22106 **
22107 ** The sqlite3_file structure for POSIX is no longer just an integer file
22108 ** descriptor.  It is now a structure that holds the integer file
22109 ** descriptor and a pointer to a structure that describes the internal
22110 ** locks on the corresponding inode.  There is one locking structure
22111 ** per inode, so if the same inode is opened twice, both unixFile structures
22112 ** point to the same locking structure.  The locking structure keeps
22113 ** a reference count (so we will know when to delete it) and a "cnt"
22114 ** field that tells us its internal lock status.  cnt==0 means the
22115 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
22116 ** cnt>0 means there are cnt shared locks on the file.
22117 **
22118 ** Any attempt to lock or unlock a file first checks the locking
22119 ** structure.  The fcntl() system call is only invoked to set a 
22120 ** POSIX lock if the internal lock structure transitions between
22121 ** a locked and an unlocked state.
22122 **
22123 ** But wait:  there are yet more problems with POSIX advisory locks.
22124 **
22125 ** If you close a file descriptor that points to a file that has locks,
22126 ** all locks on that file that are owned by the current process are
22127 ** released.  To work around this problem, each unixFile structure contains
22128 ** a pointer to an unixOpenCnt structure.  There is one unixOpenCnt structure
22129 ** per open inode, which means that multiple unixFile can point to a single
22130 ** unixOpenCnt.  When an attempt is made to close an unixFile, if there are
22131 ** other unixFile open on the same inode that are holding locks, the call
22132 ** to close() the file descriptor is deferred until all of the locks clear.
22133 ** The unixOpenCnt structure keeps a list of file descriptors that need to
22134 ** be closed and that list is walked (and cleared) when the last lock
22135 ** clears.
22136 **
22137 ** Yet another problem:  LinuxThreads do not play well with posix locks.
22138 **
22139 ** Many older versions of linux use the LinuxThreads library which is
22140 ** not posix compliant.  Under LinuxThreads, a lock created by thread
22141 ** A cannot be modified or overridden by a different thread B.
22142 ** Only thread A can modify the lock.  Locking behavior is correct
22143 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
22144 ** on linux - with NPTL a lock created by thread A can override locks
22145 ** in thread B.  But there is no way to know at compile-time which
22146 ** threading library is being used.  So there is no way to know at
22147 ** compile-time whether or not thread A can override locks on thread B.
22148 ** We have to do a run-time check to discover the behavior of the
22149 ** current process.
22150 **
22151 ** On systems where thread A is unable to modify locks created by
22152 ** thread B, we have to keep track of which thread created each
22153 ** lock.  Hence there is an extra field in the key to the unixLockInfo
22154 ** structure to record this information.  And on those systems it
22155 ** is illegal to begin a transaction in one thread and finish it
22156 ** in another.  For this latter restriction, there is no work-around.
22157 ** It is a limitation of LinuxThreads.
22158 */
22159
22160 /*
22161 ** Set or check the unixFile.tid field.  This field is set when an unixFile
22162 ** is first opened.  All subsequent uses of the unixFile verify that the
22163 ** same thread is operating on the unixFile.  Some operating systems do
22164 ** not allow locks to be overridden by other threads and that restriction
22165 ** means that sqlite3* database handles cannot be moved from one thread
22166 ** to another while locks are held.
22167 **
22168 ** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
22169 ** another as long as we are running on a system that supports threads
22170 ** overriding each others locks (which is now the most common behavior)
22171 ** or if no locks are held.  But the unixFile.pLock field needs to be
22172 ** recomputed because its key includes the thread-id.  See the 
22173 ** transferOwnership() function below for additional information
22174 */
22175 #if SQLITE_THREADSAFE && defined(__linux__)
22176 # define SET_THREADID(X)   (X)->tid = pthread_self()
22177 # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
22178                             !pthread_equal((X)->tid, pthread_self()))
22179 #else
22180 # define SET_THREADID(X)
22181 # define CHECK_THREADID(X) 0
22182 #endif
22183
22184 /*
22185 ** An instance of the following structure serves as the key used
22186 ** to locate a particular unixOpenCnt structure given its inode.  This
22187 ** is the same as the unixLockKey except that the thread ID is omitted.
22188 */
22189 struct unixFileId {
22190   dev_t dev;                  /* Device number */
22191 #if OS_VXWORKS
22192   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
22193 #else
22194   ino_t ino;                  /* Inode number */
22195 #endif
22196 };
22197
22198 /*
22199 ** An instance of the following structure serves as the key used
22200 ** to locate a particular unixLockInfo structure given its inode.
22201 **
22202 ** If threads cannot override each others locks (LinuxThreads), then we
22203 ** set the unixLockKey.tid field to the thread ID.  If threads can override
22204 ** each others locks (Posix and NPTL) then tid is always set to zero.
22205 ** tid is omitted if we compile without threading support or on an OS
22206 ** other than linux.
22207 */
22208 struct unixLockKey {
22209   struct unixFileId fid;  /* Unique identifier for the file */
22210 #if SQLITE_THREADSAFE && defined(__linux__)
22211   pthread_t tid;  /* Thread ID of lock owner. Zero if not using LinuxThreads */
22212 #endif
22213 };
22214
22215 /*
22216 ** An instance of the following structure is allocated for each open
22217 ** inode.  Or, on LinuxThreads, there is one of these structures for
22218 ** each inode opened by each thread.
22219 **
22220 ** A single inode can have multiple file descriptors, so each unixFile
22221 ** structure contains a pointer to an instance of this object and this
22222 ** object keeps a count of the number of unixFile pointing to it.
22223 */
22224 struct unixLockInfo {
22225   struct unixLockKey lockKey;     /* The lookup key */
22226   int cnt;                        /* Number of SHARED locks held */
22227   int locktype;                   /* One of SHARED_LOCK, RESERVED_LOCK etc. */
22228   int nRef;                       /* Number of pointers to this structure */
22229   struct unixLockInfo *pNext;     /* List of all unixLockInfo objects */
22230   struct unixLockInfo *pPrev;     /*    .... doubly linked */
22231 };
22232
22233 /*
22234 ** An instance of the following structure is allocated for each open
22235 ** inode.  This structure keeps track of the number of locks on that
22236 ** inode.  If a close is attempted against an inode that is holding
22237 ** locks, the close is deferred until all locks clear by adding the
22238 ** file descriptor to be closed to the pending list.
22239 **
22240 ** TODO:  Consider changing this so that there is only a single file
22241 ** descriptor for each open file, even when it is opened multiple times.
22242 ** The close() system call would only occur when the last database
22243 ** using the file closes.
22244 */
22245 struct unixOpenCnt {
22246   struct unixFileId fileId;   /* The lookup key */
22247   int nRef;                   /* Number of pointers to this structure */
22248   int nLock;                  /* Number of outstanding locks */
22249   UnixUnusedFd *pUnused;      /* Unused file descriptors to close */
22250 #if OS_VXWORKS
22251   sem_t *pSem;                     /* Named POSIX semaphore */
22252   char aSemName[MAX_PATHNAME+2];   /* Name of that semaphore */
22253 #endif
22254   struct unixOpenCnt *pNext, *pPrev;   /* List of all unixOpenCnt objects */
22255 };
22256
22257 /*
22258 ** Lists of all unixLockInfo and unixOpenCnt objects.  These used to be hash
22259 ** tables.  But the number of objects is rarely more than a dozen and
22260 ** never exceeds a few thousand.  And lookup is not on a critical
22261 ** path so a simple linked list will suffice.
22262 */
22263 static struct unixLockInfo *lockList = 0;
22264 static struct unixOpenCnt *openList = 0;
22265
22266 /*
22267 ** This variable remembers whether or not threads can override each others
22268 ** locks.
22269 **
22270 **    0:  No.  Threads cannot override each others locks.  (LinuxThreads)
22271 **    1:  Yes.  Threads can override each others locks.  (Posix & NLPT)
22272 **   -1:  We don't know yet.
22273 **
22274 ** On some systems, we know at compile-time if threads can override each
22275 ** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
22276 ** will be set appropriately.  On other systems, we have to check at
22277 ** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
22278 ** undefined.
22279 **
22280 ** This variable normally has file scope only.  But during testing, we make
22281 ** it a global so that the test code can change its value in order to verify
22282 ** that the right stuff happens in either case.
22283 */
22284 #if SQLITE_THREADSAFE && defined(__linux__)
22285 #  ifndef SQLITE_THREAD_OVERRIDE_LOCK
22286 #    define SQLITE_THREAD_OVERRIDE_LOCK -1
22287 #  endif
22288 #  ifdef SQLITE_TEST
22289 int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22290 #  else
22291 static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22292 #  endif
22293 #endif
22294
22295 /*
22296 ** This structure holds information passed into individual test
22297 ** threads by the testThreadLockingBehavior() routine.
22298 */
22299 struct threadTestData {
22300   int fd;                /* File to be locked */
22301   struct flock lock;     /* The locking operation */
22302   int result;            /* Result of the locking operation */
22303 };
22304
22305 #if SQLITE_THREADSAFE && defined(__linux__)
22306 /*
22307 ** This function is used as the main routine for a thread launched by
22308 ** testThreadLockingBehavior(). It tests whether the shared-lock obtained
22309 ** by the main thread in testThreadLockingBehavior() conflicts with a
22310 ** hypothetical write-lock obtained by this thread on the same file.
22311 **
22312 ** The write-lock is not actually acquired, as this is not possible if 
22313 ** the file is open in read-only mode (see ticket #3472).
22314 */ 
22315 static void *threadLockingTest(void *pArg){
22316   struct threadTestData *pData = (struct threadTestData*)pArg;
22317   pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
22318   return pArg;
22319 }
22320 #endif /* SQLITE_THREADSAFE && defined(__linux__) */
22321
22322
22323 #if SQLITE_THREADSAFE && defined(__linux__)
22324 /*
22325 ** This procedure attempts to determine whether or not threads
22326 ** can override each others locks then sets the 
22327 ** threadsOverrideEachOthersLocks variable appropriately.
22328 */
22329 static void testThreadLockingBehavior(int fd_orig){
22330   int fd;
22331   int rc;
22332   struct threadTestData d;
22333   struct flock l;
22334   pthread_t t;
22335
22336   fd = dup(fd_orig);
22337   if( fd<0 ) return;
22338   memset(&l, 0, sizeof(l));
22339   l.l_type = F_RDLCK;
22340   l.l_len = 1;
22341   l.l_start = 0;
22342   l.l_whence = SEEK_SET;
22343   rc = fcntl(fd_orig, F_SETLK, &l);
22344   if( rc!=0 ) return;
22345   memset(&d, 0, sizeof(d));
22346   d.fd = fd;
22347   d.lock = l;
22348   d.lock.l_type = F_WRLCK;
22349   if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
22350     pthread_join(t, 0);
22351   }
22352   close(fd);
22353   if( d.result!=0 ) return;
22354   threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
22355 }
22356 #endif /* SQLITE_THREADSAFE && defined(__linux__) */
22357
22358 /*
22359 ** Release a unixLockInfo structure previously allocated by findLockInfo().
22360 **
22361 ** The mutex entered using the unixEnterMutex() function must be held
22362 ** when this function is called.
22363 */
22364 static void releaseLockInfo(struct unixLockInfo *pLock){
22365   assert( unixMutexHeld() );
22366   if( pLock ){
22367     pLock->nRef--;
22368     if( pLock->nRef==0 ){
22369       if( pLock->pPrev ){
22370         assert( pLock->pPrev->pNext==pLock );
22371         pLock->pPrev->pNext = pLock->pNext;
22372       }else{
22373         assert( lockList==pLock );
22374         lockList = pLock->pNext;
22375       }
22376       if( pLock->pNext ){
22377         assert( pLock->pNext->pPrev==pLock );
22378         pLock->pNext->pPrev = pLock->pPrev;
22379       }
22380       sqlite3_free(pLock);
22381     }
22382   }
22383 }
22384
22385 /*
22386 ** Release a unixOpenCnt structure previously allocated by findLockInfo().
22387 **
22388 ** The mutex entered using the unixEnterMutex() function must be held
22389 ** when this function is called.
22390 */
22391 static void releaseOpenCnt(struct unixOpenCnt *pOpen){
22392   assert( unixMutexHeld() );
22393   if( pOpen ){
22394     pOpen->nRef--;
22395     if( pOpen->nRef==0 ){
22396       if( pOpen->pPrev ){
22397         assert( pOpen->pPrev->pNext==pOpen );
22398         pOpen->pPrev->pNext = pOpen->pNext;
22399       }else{
22400         assert( openList==pOpen );
22401         openList = pOpen->pNext;
22402       }
22403       if( pOpen->pNext ){
22404         assert( pOpen->pNext->pPrev==pOpen );
22405         pOpen->pNext->pPrev = pOpen->pPrev;
22406       }
22407 #if SQLITE_THREADSAFE && defined(__linux__)
22408       assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
22409 #endif
22410
22411       /* If pOpen->pUnused is not null, then memory and file-descriptors
22412       ** are leaked.
22413       **
22414       ** This will only happen if, under Linuxthreads, the user has opened
22415       ** a transaction in one thread, then attempts to close the database
22416       ** handle from another thread (without first unlocking the db file).
22417       ** This is a misuse.  */
22418       sqlite3_free(pOpen);
22419     }
22420   }
22421 }
22422
22423 /*
22424 ** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
22425 ** describes that file descriptor.  Create new ones if necessary.  The
22426 ** return values might be uninitialized if an error occurs.
22427 **
22428 ** The mutex entered using the unixEnterMutex() function must be held
22429 ** when this function is called.
22430 **
22431 ** Return an appropriate error code.
22432 */
22433 static int findLockInfo(
22434   unixFile *pFile,               /* Unix file with file desc used in the key */
22435   struct unixLockInfo **ppLock,  /* Return the unixLockInfo structure here */
22436   struct unixOpenCnt **ppOpen    /* Return the unixOpenCnt structure here */
22437 ){
22438   int rc;                        /* System call return code */
22439   int fd;                        /* The file descriptor for pFile */
22440   struct unixLockKey lockKey;    /* Lookup key for the unixLockInfo structure */
22441   struct unixFileId fileId;      /* Lookup key for the unixOpenCnt struct */
22442   struct stat statbuf;           /* Low-level file information */
22443   struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
22444   struct unixOpenCnt *pOpen;     /* Candidate unixOpenCnt object */
22445
22446   assert( unixMutexHeld() );
22447
22448   /* Get low-level information about the file that we can used to
22449   ** create a unique name for the file.
22450   */
22451   fd = pFile->h;
22452   rc = fstat(fd, &statbuf);
22453   if( rc!=0 ){
22454     pFile->lastErrno = errno;
22455 #ifdef EOVERFLOW
22456     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
22457 #endif
22458     return SQLITE_IOERR;
22459   }
22460
22461 #ifdef __APPLE__
22462   /* On OS X on an msdos filesystem, the inode number is reported
22463   ** incorrectly for zero-size files.  See ticket #3260.  To work
22464   ** around this problem (we consider it a bug in OS X, not SQLite)
22465   ** we always increase the file size to 1 by writing a single byte
22466   ** prior to accessing the inode number.  The one byte written is
22467   ** an ASCII 'S' character which also happens to be the first byte
22468   ** in the header of every SQLite database.  In this way, if there
22469   ** is a race condition such that another thread has already populated
22470   ** the first page of the database, no damage is done.
22471   */
22472   if( statbuf.st_size==0 ){
22473     rc = write(fd, "S", 1);
22474     if( rc!=1 ){
22475       return SQLITE_IOERR;
22476     }
22477     rc = fstat(fd, &statbuf);
22478     if( rc!=0 ){
22479       pFile->lastErrno = errno;
22480       return SQLITE_IOERR;
22481     }
22482   }
22483 #endif
22484
22485   memset(&lockKey, 0, sizeof(lockKey));
22486   lockKey.fid.dev = statbuf.st_dev;
22487 #if OS_VXWORKS
22488   lockKey.fid.pId = pFile->pId;
22489 #else
22490   lockKey.fid.ino = statbuf.st_ino;
22491 #endif
22492 #if SQLITE_THREADSAFE && defined(__linux__)
22493   if( threadsOverrideEachOthersLocks<0 ){
22494     testThreadLockingBehavior(fd);
22495   }
22496   lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
22497 #endif
22498   fileId = lockKey.fid;
22499   if( ppLock!=0 ){
22500     pLock = lockList;
22501     while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
22502       pLock = pLock->pNext;
22503     }
22504     if( pLock==0 ){
22505       pLock = sqlite3_malloc( sizeof(*pLock) );
22506       if( pLock==0 ){
22507         rc = SQLITE_NOMEM;
22508         goto exit_findlockinfo;
22509       }
22510       memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey));
22511       pLock->nRef = 1;
22512       pLock->cnt = 0;
22513       pLock->locktype = 0;
22514       pLock->pNext = lockList;
22515       pLock->pPrev = 0;
22516       if( lockList ) lockList->pPrev = pLock;
22517       lockList = pLock;
22518     }else{
22519       pLock->nRef++;
22520     }
22521     *ppLock = pLock;
22522   }
22523   if( ppOpen!=0 ){
22524     pOpen = openList;
22525     while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
22526       pOpen = pOpen->pNext;
22527     }
22528     if( pOpen==0 ){
22529       pOpen = sqlite3_malloc( sizeof(*pOpen) );
22530       if( pOpen==0 ){
22531         releaseLockInfo(pLock);
22532         rc = SQLITE_NOMEM;
22533         goto exit_findlockinfo;
22534       }
22535       memset(pOpen, 0, sizeof(*pOpen));
22536       pOpen->fileId = fileId;
22537       pOpen->nRef = 1;
22538       pOpen->pNext = openList;
22539       if( openList ) openList->pPrev = pOpen;
22540       openList = pOpen;
22541     }else{
22542       pOpen->nRef++;
22543     }
22544     *ppOpen = pOpen;
22545   }
22546
22547 exit_findlockinfo:
22548   return rc;
22549 }
22550
22551 /*
22552 ** If we are currently in a different thread than the thread that the
22553 ** unixFile argument belongs to, then transfer ownership of the unixFile
22554 ** over to the current thread.
22555 **
22556 ** A unixFile is only owned by a thread on systems that use LinuxThreads.
22557 **
22558 ** Ownership transfer is only allowed if the unixFile is currently unlocked.
22559 ** If the unixFile is locked and an ownership is wrong, then return
22560 ** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
22561 */
22562 #if SQLITE_THREADSAFE && defined(__linux__)
22563 static int transferOwnership(unixFile *pFile){
22564   int rc;
22565   pthread_t hSelf;
22566   if( threadsOverrideEachOthersLocks ){
22567     /* Ownership transfers not needed on this system */
22568     return SQLITE_OK;
22569   }
22570   hSelf = pthread_self();
22571   if( pthread_equal(pFile->tid, hSelf) ){
22572     /* We are still in the same thread */
22573     OSTRACE1("No-transfer, same thread\n");
22574     return SQLITE_OK;
22575   }
22576   if( pFile->locktype!=NO_LOCK ){
22577     /* We cannot change ownership while we are holding a lock! */
22578     return SQLITE_MISUSE;
22579   }
22580   OSTRACE4("Transfer ownership of %d from %d to %d\n",
22581             pFile->h, pFile->tid, hSelf);
22582   pFile->tid = hSelf;
22583   if (pFile->pLock != NULL) {
22584     releaseLockInfo(pFile->pLock);
22585     rc = findLockInfo(pFile, &pFile->pLock, 0);
22586     OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
22587            locktypeName(pFile->locktype),
22588            locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
22589     return rc;
22590   } else {
22591     return SQLITE_OK;
22592   }
22593 }
22594 #else  /* if not SQLITE_THREADSAFE */
22595   /* On single-threaded builds, ownership transfer is a no-op */
22596 # define transferOwnership(X) SQLITE_OK
22597 #endif /* SQLITE_THREADSAFE */
22598
22599
22600 /*
22601 ** This routine checks if there is a RESERVED lock held on the specified
22602 ** file by this or any other process. If such a lock is held, set *pResOut
22603 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
22604 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
22605 */
22606 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
22607   int rc = SQLITE_OK;
22608   int reserved = 0;
22609   unixFile *pFile = (unixFile*)id;
22610
22611   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
22612
22613   assert( pFile );
22614   unixEnterMutex(); /* Because pFile->pLock is shared across threads */
22615
22616   /* Check if a thread in this process holds such a lock */
22617   if( pFile->pLock->locktype>SHARED_LOCK ){
22618     reserved = 1;
22619   }
22620
22621   /* Otherwise see if some other process holds it.
22622   */
22623 #ifndef __DJGPP__
22624   if( !reserved ){
22625     struct flock lock;
22626     lock.l_whence = SEEK_SET;
22627     lock.l_start = RESERVED_BYTE;
22628     lock.l_len = 1;
22629     lock.l_type = F_WRLCK;
22630     if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
22631       int tErrno = errno;
22632       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
22633       pFile->lastErrno = tErrno;
22634     } else if( lock.l_type!=F_UNLCK ){
22635       reserved = 1;
22636     }
22637   }
22638 #endif
22639   
22640   unixLeaveMutex();
22641   OSTRACE4("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved);
22642
22643   *pResOut = reserved;
22644   return rc;
22645 }
22646
22647 /*
22648 ** Perform a file locking operation on a range of bytes in a file.
22649 ** The "op" parameter should be one of F_RDLCK, F_WRLCK, or F_UNLCK.
22650 ** Return 0 on success or -1 for failure.  On failure, write the error
22651 ** code into *pErrcode.
22652 **
22653 ** If the SQLITE_WHOLE_FILE_LOCKING bit is clear, then only lock
22654 ** the range of bytes on the locking page between SHARED_FIRST and
22655 ** SHARED_SIZE.  If SQLITE_WHOLE_FILE_LOCKING is set, then lock all
22656 ** bytes from 0 up to but not including PENDING_BYTE, and all bytes
22657 ** that follow SHARED_FIRST.
22658 **
22659 ** In other words, of SQLITE_WHOLE_FILE_LOCKING if false (the historical
22660 ** default case) then only lock a small range of bytes from SHARED_FIRST
22661 ** through SHARED_FIRST+SHARED_SIZE-1.  But if SQLITE_WHOLE_FILE_LOCKING is
22662 ** true then lock every byte in the file except for PENDING_BYTE and
22663 ** RESERVED_BYTE.
22664 **
22665 ** SQLITE_WHOLE_FILE_LOCKING=true overlaps SQLITE_WHOLE_FILE_LOCKING=false
22666 ** and so the locking schemes are compatible.  One type of lock will
22667 ** effectively exclude the other type.  The reason for using the
22668 ** SQLITE_WHOLE_FILE_LOCKING=true is that by indicating the full range
22669 ** of bytes to be read or written, we give hints to NFS to help it
22670 ** maintain cache coherency.  On the other hand, whole file locking
22671 ** is slower, so we don't want to use it except for NFS.
22672 */
22673 static int rangeLock(unixFile *pFile, int op, int *pErrcode){
22674   struct flock lock;
22675   int rc;
22676   lock.l_type = op;
22677   lock.l_start = SHARED_FIRST;
22678   lock.l_whence = SEEK_SET;
22679   if( (pFile->fileFlags & SQLITE_WHOLE_FILE_LOCKING)==0 ){
22680     lock.l_len = SHARED_SIZE;
22681     rc = fcntl(pFile->h, F_SETLK, &lock);
22682     *pErrcode = errno;
22683   }else{
22684     lock.l_len = 0;
22685     rc = fcntl(pFile->h, F_SETLK, &lock);
22686     *pErrcode = errno;
22687     if( NEVER(op==F_UNLCK) || rc!=(-1) ){
22688       lock.l_start = 0;
22689       lock.l_len = PENDING_BYTE;
22690       rc = fcntl(pFile->h, F_SETLK, &lock);
22691       if( ALWAYS(op!=F_UNLCK) && rc==(-1) ){
22692         *pErrcode = errno;
22693         lock.l_type = F_UNLCK;
22694         lock.l_start = SHARED_FIRST;
22695         lock.l_len = 0;
22696         fcntl(pFile->h, F_SETLK, &lock);
22697       }
22698     }
22699   }
22700   return rc;
22701 }
22702
22703 /*
22704 ** Lock the file with the lock specified by parameter locktype - one
22705 ** of the following:
22706 **
22707 **     (1) SHARED_LOCK
22708 **     (2) RESERVED_LOCK
22709 **     (3) PENDING_LOCK
22710 **     (4) EXCLUSIVE_LOCK
22711 **
22712 ** Sometimes when requesting one lock state, additional lock states
22713 ** are inserted in between.  The locking might fail on one of the later
22714 ** transitions leaving the lock state different from what it started but
22715 ** still short of its goal.  The following chart shows the allowed
22716 ** transitions and the inserted intermediate states:
22717 **
22718 **    UNLOCKED -> SHARED
22719 **    SHARED -> RESERVED
22720 **    SHARED -> (PENDING) -> EXCLUSIVE
22721 **    RESERVED -> (PENDING) -> EXCLUSIVE
22722 **    PENDING -> EXCLUSIVE
22723 **
22724 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
22725 ** routine to lower a locking level.
22726 */
22727 static int unixLock(sqlite3_file *id, int locktype){
22728   /* The following describes the implementation of the various locks and
22729   ** lock transitions in terms of the POSIX advisory shared and exclusive
22730   ** lock primitives (called read-locks and write-locks below, to avoid
22731   ** confusion with SQLite lock names). The algorithms are complicated
22732   ** slightly in order to be compatible with windows systems simultaneously
22733   ** accessing the same database file, in case that is ever required.
22734   **
22735   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
22736   ** byte', each single bytes at well known offsets, and the 'shared byte
22737   ** range', a range of 510 bytes at a well known offset.
22738   **
22739   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
22740   ** byte'.  If this is successful, a random byte from the 'shared byte
22741   ** range' is read-locked and the lock on the 'pending byte' released.
22742   **
22743   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
22744   ** A RESERVED lock is implemented by grabbing a write-lock on the
22745   ** 'reserved byte'. 
22746   **
22747   ** A process may only obtain a PENDING lock after it has obtained a
22748   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
22749   ** on the 'pending byte'. This ensures that no new SHARED locks can be
22750   ** obtained, but existing SHARED locks are allowed to persist. A process
22751   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
22752   ** This property is used by the algorithm for rolling back a journal file
22753   ** after a crash.
22754   **
22755   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
22756   ** implemented by obtaining a write-lock on the entire 'shared byte
22757   ** range'. Since all other locks require a read-lock on one of the bytes
22758   ** within this range, this ensures that no other locks are held on the
22759   ** database. 
22760   **
22761   ** The reason a single byte cannot be used instead of the 'shared byte
22762   ** range' is that some versions of windows do not support read-locks. By
22763   ** locking a random byte from a range, concurrent SHARED locks may exist
22764   ** even if the locking primitive used is always a write-lock.
22765   */
22766   int rc = SQLITE_OK;
22767   unixFile *pFile = (unixFile*)id;
22768   struct unixLockInfo *pLock = pFile->pLock;
22769   struct flock lock;
22770   int s = 0;
22771   int tErrno;
22772
22773   assert( pFile );
22774   OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
22775       locktypeName(locktype), locktypeName(pFile->locktype),
22776       locktypeName(pLock->locktype), pLock->cnt , getpid());
22777
22778   /* If there is already a lock of this type or more restrictive on the
22779   ** unixFile, do nothing. Don't use the end_lock: exit path, as
22780   ** unixEnterMutex() hasn't been called yet.
22781   */
22782   if( pFile->locktype>=locktype ){
22783     OSTRACE3("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
22784             locktypeName(locktype));
22785     return SQLITE_OK;
22786   }
22787
22788   /* Make sure the locking sequence is correct.
22789   **  (1) We never move from unlocked to anything higher than shared lock.
22790   **  (2) SQLite never explicitly requests a pendig lock.
22791   **  (3) A shared lock is always held when a reserve lock is requested.
22792   */
22793   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22794   assert( locktype!=PENDING_LOCK );
22795   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22796
22797   /* This mutex is needed because pFile->pLock is shared across threads
22798   */
22799   unixEnterMutex();
22800
22801   /* Make sure the current thread owns the pFile.
22802   */
22803   rc = transferOwnership(pFile);
22804   if( rc!=SQLITE_OK ){
22805     unixLeaveMutex();
22806     return rc;
22807   }
22808   pLock = pFile->pLock;
22809
22810   /* If some thread using this PID has a lock via a different unixFile*
22811   ** handle that precludes the requested lock, return BUSY.
22812   */
22813   if( (pFile->locktype!=pLock->locktype && 
22814           (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
22815   ){
22816     rc = SQLITE_BUSY;
22817     goto end_lock;
22818   }
22819
22820   /* If a SHARED lock is requested, and some thread using this PID already
22821   ** has a SHARED or RESERVED lock, then increment reference counts and
22822   ** return SQLITE_OK.
22823   */
22824   if( locktype==SHARED_LOCK && 
22825       (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
22826     assert( locktype==SHARED_LOCK );
22827     assert( pFile->locktype==0 );
22828     assert( pLock->cnt>0 );
22829     pFile->locktype = SHARED_LOCK;
22830     pLock->cnt++;
22831     pFile->pOpen->nLock++;
22832     goto end_lock;
22833   }
22834
22835
22836   /* A PENDING lock is needed before acquiring a SHARED lock and before
22837   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
22838   ** be released.
22839   */
22840   lock.l_len = 1L;
22841   lock.l_whence = SEEK_SET;
22842   if( locktype==SHARED_LOCK 
22843       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
22844   ){
22845     lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
22846     lock.l_start = PENDING_BYTE;
22847     s = fcntl(pFile->h, F_SETLK, &lock);
22848     if( s==(-1) ){
22849       tErrno = errno;
22850       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
22851       if( IS_LOCK_ERROR(rc) ){
22852         pFile->lastErrno = tErrno;
22853       }
22854       goto end_lock;
22855     }
22856   }
22857
22858
22859   /* If control gets to this point, then actually go ahead and make
22860   ** operating system calls for the specified lock.
22861   */
22862   if( locktype==SHARED_LOCK ){
22863     assert( pLock->cnt==0 );
22864     assert( pLock->locktype==0 );
22865
22866     /* Now get the read-lock */
22867     s = rangeLock(pFile, F_RDLCK, &tErrno);
22868
22869     /* Drop the temporary PENDING lock */
22870     lock.l_start = PENDING_BYTE;
22871     lock.l_len = 1L;
22872     lock.l_type = F_UNLCK;
22873     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
22874       if( s != -1 ){
22875         /* This could happen with a network mount */
22876         tErrno = errno; 
22877         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
22878         if( IS_LOCK_ERROR(rc) ){
22879           pFile->lastErrno = tErrno;
22880         }
22881         goto end_lock;
22882       }
22883     }
22884     if( s==(-1) ){
22885       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
22886       if( IS_LOCK_ERROR(rc) ){
22887         pFile->lastErrno = tErrno;
22888       }
22889     }else{
22890       pFile->locktype = SHARED_LOCK;
22891       pFile->pOpen->nLock++;
22892       pLock->cnt = 1;
22893     }
22894   }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
22895     /* We are trying for an exclusive lock but another thread in this
22896     ** same process is still holding a shared lock. */
22897     rc = SQLITE_BUSY;
22898   }else{
22899     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
22900     ** assumed that there is a SHARED or greater lock on the file
22901     ** already.
22902     */
22903     assert( 0!=pFile->locktype );
22904     lock.l_type = F_WRLCK;
22905     switch( locktype ){
22906       case RESERVED_LOCK:
22907         lock.l_start = RESERVED_BYTE;
22908         s = fcntl(pFile->h, F_SETLK, &lock);
22909         tErrno = errno;
22910         break;
22911       case EXCLUSIVE_LOCK:
22912         s = rangeLock(pFile, F_WRLCK, &tErrno);
22913         break;
22914       default:
22915         assert(0);
22916     }
22917     if( s==(-1) ){
22918       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
22919       if( IS_LOCK_ERROR(rc) ){
22920         pFile->lastErrno = tErrno;
22921       }
22922     }
22923   }
22924   
22925
22926 #ifndef NDEBUG
22927   /* Set up the transaction-counter change checking flags when
22928   ** transitioning from a SHARED to a RESERVED lock.  The change
22929   ** from SHARED to RESERVED marks the beginning of a normal
22930   ** write operation (not a hot journal rollback).
22931   */
22932   if( rc==SQLITE_OK
22933    && pFile->locktype<=SHARED_LOCK
22934    && locktype==RESERVED_LOCK
22935   ){
22936     pFile->transCntrChng = 0;
22937     pFile->dbUpdate = 0;
22938     pFile->inNormalWrite = 1;
22939   }
22940 #endif
22941
22942
22943   if( rc==SQLITE_OK ){
22944     pFile->locktype = locktype;
22945     pLock->locktype = locktype;
22946   }else if( locktype==EXCLUSIVE_LOCK ){
22947     pFile->locktype = PENDING_LOCK;
22948     pLock->locktype = PENDING_LOCK;
22949   }
22950
22951 end_lock:
22952   unixLeaveMutex();
22953   OSTRACE4("LOCK    %d %s %s (unix)\n", pFile->h, locktypeName(locktype), 
22954       rc==SQLITE_OK ? "ok" : "failed");
22955   return rc;
22956 }
22957
22958 /*
22959 ** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
22960 ** If all such file descriptors are closed without error, the list is
22961 ** cleared and SQLITE_OK returned.
22962 **
22963 ** Otherwise, if an error occurs, then successfully closed file descriptor
22964 ** entries are removed from the list, and SQLITE_IOERR_CLOSE returned. 
22965 ** not deleted and SQLITE_IOERR_CLOSE returned.
22966 */ 
22967 static int closePendingFds(unixFile *pFile){
22968   int rc = SQLITE_OK;
22969   struct unixOpenCnt *pOpen = pFile->pOpen;
22970   UnixUnusedFd *pError = 0;
22971   UnixUnusedFd *p;
22972   UnixUnusedFd *pNext;
22973   for(p=pOpen->pUnused; p; p=pNext){
22974     pNext = p->pNext;
22975     if( close(p->fd) ){
22976       pFile->lastErrno = errno;
22977       rc = SQLITE_IOERR_CLOSE;
22978       p->pNext = pError;
22979       pError = p;
22980     }else{
22981       sqlite3_free(p);
22982     }
22983   }
22984   pOpen->pUnused = pError;
22985   return rc;
22986 }
22987
22988 /*
22989 ** Add the file descriptor used by file handle pFile to the corresponding
22990 ** pUnused list.
22991 */
22992 static void setPendingFd(unixFile *pFile){
22993   struct unixOpenCnt *pOpen = pFile->pOpen;
22994   UnixUnusedFd *p = pFile->pUnused;
22995   p->pNext = pOpen->pUnused;
22996   pOpen->pUnused = p;
22997   pFile->h = -1;
22998   pFile->pUnused = 0;
22999 }
23000
23001 /*
23002 ** Lower the locking level on file descriptor pFile to locktype.  locktype
23003 ** must be either NO_LOCK or SHARED_LOCK.
23004 **
23005 ** If the locking level of the file descriptor is already at or below
23006 ** the requested locking level, this routine is a no-op.
23007 */
23008 static int unixUnlock(sqlite3_file *id, int locktype){
23009   unixFile *pFile = (unixFile*)id; /* The open file */
23010   struct unixLockInfo *pLock;      /* Structure describing current lock state */
23011   struct flock lock;               /* Information passed into fcntl() */
23012   int rc = SQLITE_OK;              /* Return code from this interface */
23013   int h;                           /* The underlying file descriptor */
23014   int tErrno;                      /* Error code from system call errors */
23015
23016   assert( pFile );
23017   OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, locktype,
23018       pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
23019
23020   assert( locktype<=SHARED_LOCK );
23021   if( pFile->locktype<=locktype ){
23022     return SQLITE_OK;
23023   }
23024   if( CHECK_THREADID(pFile) ){
23025     return SQLITE_MISUSE;
23026   }
23027   unixEnterMutex();
23028   h = pFile->h;
23029   pLock = pFile->pLock;
23030   assert( pLock->cnt!=0 );
23031   if( pFile->locktype>SHARED_LOCK ){
23032     assert( pLock->locktype==pFile->locktype );
23033     SimulateIOErrorBenign(1);
23034     SimulateIOError( h=(-1) )
23035     SimulateIOErrorBenign(0);
23036
23037 #ifndef NDEBUG
23038     /* When reducing a lock such that other processes can start
23039     ** reading the database file again, make sure that the
23040     ** transaction counter was updated if any part of the database
23041     ** file changed.  If the transaction counter is not updated,
23042     ** other connections to the same file might not realize that
23043     ** the file has changed and hence might not know to flush their
23044     ** cache.  The use of a stale cache can lead to database corruption.
23045     */
23046     assert( pFile->inNormalWrite==0
23047          || pFile->dbUpdate==0
23048          || pFile->transCntrChng==1 );
23049     pFile->inNormalWrite = 0;
23050 #endif
23051
23052
23053     if( locktype==SHARED_LOCK ){
23054       if( rangeLock(pFile, F_RDLCK, &tErrno)==(-1) ){
23055         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23056         if( IS_LOCK_ERROR(rc) ){
23057           pFile->lastErrno = tErrno;
23058         }
23059         goto end_unlock;
23060       }
23061     }
23062     lock.l_type = F_UNLCK;
23063     lock.l_whence = SEEK_SET;
23064     lock.l_start = PENDING_BYTE;
23065     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
23066     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23067       pLock->locktype = SHARED_LOCK;
23068     }else{
23069       tErrno = errno;
23070       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23071       if( IS_LOCK_ERROR(rc) ){
23072         pFile->lastErrno = tErrno;
23073       }
23074       goto end_unlock;
23075     }
23076   }
23077   if( locktype==NO_LOCK ){
23078     struct unixOpenCnt *pOpen;
23079
23080     /* Decrement the shared lock counter.  Release the lock using an
23081     ** OS call only when all threads in this same process have released
23082     ** the lock.
23083     */
23084     pLock->cnt--;
23085     if( pLock->cnt==0 ){
23086       lock.l_type = F_UNLCK;
23087       lock.l_whence = SEEK_SET;
23088       lock.l_start = lock.l_len = 0L;
23089       SimulateIOErrorBenign(1);
23090       SimulateIOError( h=(-1) )
23091       SimulateIOErrorBenign(0);
23092       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23093         pLock->locktype = NO_LOCK;
23094       }else{
23095         tErrno = errno;
23096         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23097         if( IS_LOCK_ERROR(rc) ){
23098           pFile->lastErrno = tErrno;
23099         }
23100         pLock->locktype = NO_LOCK;
23101         pFile->locktype = NO_LOCK;
23102       }
23103     }
23104
23105     /* Decrement the count of locks against this same file.  When the
23106     ** count reaches zero, close any other file descriptors whose close
23107     ** was deferred because of outstanding locks.
23108     */
23109     pOpen = pFile->pOpen;
23110     pOpen->nLock--;
23111     assert( pOpen->nLock>=0 );
23112     if( pOpen->nLock==0 ){
23113       int rc2 = closePendingFds(pFile);
23114       if( rc==SQLITE_OK ){
23115         rc = rc2;
23116       }
23117     }
23118   }
23119         
23120 end_unlock:
23121   unixLeaveMutex();
23122   if( rc==SQLITE_OK ) pFile->locktype = locktype;
23123   return rc;
23124 }
23125
23126 /*
23127 ** This function performs the parts of the "close file" operation 
23128 ** common to all locking schemes. It closes the directory and file
23129 ** handles, if they are valid, and sets all fields of the unixFile
23130 ** structure to 0.
23131 **
23132 ** It is *not* necessary to hold the mutex when this routine is called,
23133 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
23134 ** vxworksReleaseFileId() routine.
23135 */
23136 static int closeUnixFile(sqlite3_file *id){
23137   unixFile *pFile = (unixFile*)id;
23138   if( pFile ){
23139     if( pFile->dirfd>=0 ){
23140       int err = close(pFile->dirfd);
23141       if( err ){
23142         pFile->lastErrno = errno;
23143         return SQLITE_IOERR_DIR_CLOSE;
23144       }else{
23145         pFile->dirfd=-1;
23146       }
23147     }
23148     if( pFile->h>=0 ){
23149       int err = close(pFile->h);
23150       if( err ){
23151         pFile->lastErrno = errno;
23152         return SQLITE_IOERR_CLOSE;
23153       }
23154     }
23155 #if OS_VXWORKS
23156     if( pFile->pId ){
23157       if( pFile->isDelete ){
23158         unlink(pFile->pId->zCanonicalName);
23159       }
23160       vxworksReleaseFileId(pFile->pId);
23161       pFile->pId = 0;
23162     }
23163 #endif
23164     OSTRACE2("CLOSE   %-3d\n", pFile->h);
23165     OpenCounter(-1);
23166     sqlite3_free(pFile->pUnused);
23167     memset(pFile, 0, sizeof(unixFile));
23168   }
23169   return SQLITE_OK;
23170 }
23171
23172 /*
23173 ** Close a file.
23174 */
23175 static int unixClose(sqlite3_file *id){
23176   int rc = SQLITE_OK;
23177   if( id ){
23178     unixFile *pFile = (unixFile *)id;
23179     unixUnlock(id, NO_LOCK);
23180     unixEnterMutex();
23181     if( pFile->pOpen && pFile->pOpen->nLock ){
23182       /* If there are outstanding locks, do not actually close the file just
23183       ** yet because that would clear those locks.  Instead, add the file
23184       ** descriptor to pOpen->pUnused list.  It will be automatically closed 
23185       ** when the last lock is cleared.
23186       */
23187       setPendingFd(pFile);
23188     }
23189     releaseLockInfo(pFile->pLock);
23190     releaseOpenCnt(pFile->pOpen);
23191     rc = closeUnixFile(id);
23192     unixLeaveMutex();
23193   }
23194   return rc;
23195 }
23196
23197 /************** End of the posix advisory lock implementation *****************
23198 ******************************************************************************/
23199
23200 /******************************************************************************
23201 ****************************** No-op Locking **********************************
23202 **
23203 ** Of the various locking implementations available, this is by far the
23204 ** simplest:  locking is ignored.  No attempt is made to lock the database
23205 ** file for reading or writing.
23206 **
23207 ** This locking mode is appropriate for use on read-only databases
23208 ** (ex: databases that are burned into CD-ROM, for example.)  It can
23209 ** also be used if the application employs some external mechanism to
23210 ** prevent simultaneous access of the same database by two or more
23211 ** database connections.  But there is a serious risk of database
23212 ** corruption if this locking mode is used in situations where multiple
23213 ** database connections are accessing the same database file at the same
23214 ** time and one or more of those connections are writing.
23215 */
23216
23217 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
23218   UNUSED_PARAMETER(NotUsed);
23219   *pResOut = 0;
23220   return SQLITE_OK;
23221 }
23222 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
23223   UNUSED_PARAMETER2(NotUsed, NotUsed2);
23224   return SQLITE_OK;
23225 }
23226 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
23227   UNUSED_PARAMETER2(NotUsed, NotUsed2);
23228   return SQLITE_OK;
23229 }
23230
23231 /*
23232 ** Close the file.
23233 */
23234 static int nolockClose(sqlite3_file *id) {
23235   return closeUnixFile(id);
23236 }
23237
23238 /******************* End of the no-op lock implementation *********************
23239 ******************************************************************************/
23240
23241 /******************************************************************************
23242 ************************* Begin dot-file Locking ******************************
23243 **
23244 ** The dotfile locking implementation uses the existance of separate lock
23245 ** files in order to control access to the database.  This works on just
23246 ** about every filesystem imaginable.  But there are serious downsides:
23247 **
23248 **    (1)  There is zero concurrency.  A single reader blocks all other
23249 **         connections from reading or writing the database.
23250 **
23251 **    (2)  An application crash or power loss can leave stale lock files
23252 **         sitting around that need to be cleared manually.
23253 **
23254 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
23255 ** other locking strategy is available.
23256 **
23257 ** Dotfile locking works by creating a file in the same directory as the
23258 ** database and with the same name but with a ".lock" extension added.
23259 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
23260 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
23261 */
23262
23263 /*
23264 ** The file suffix added to the data base filename in order to create the
23265 ** lock file.
23266 */
23267 #define DOTLOCK_SUFFIX ".lock"
23268
23269 /*
23270 ** This routine checks if there is a RESERVED lock held on the specified
23271 ** file by this or any other process. If such a lock is held, set *pResOut
23272 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23273 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23274 **
23275 ** In dotfile locking, either a lock exists or it does not.  So in this
23276 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
23277 ** is held on the file and false if the file is unlocked.
23278 */
23279 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
23280   int rc = SQLITE_OK;
23281   int reserved = 0;
23282   unixFile *pFile = (unixFile*)id;
23283
23284   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23285   
23286   assert( pFile );
23287
23288   /* Check if a thread in this process holds such a lock */
23289   if( pFile->locktype>SHARED_LOCK ){
23290     /* Either this connection or some other connection in the same process
23291     ** holds a lock on the file.  No need to check further. */
23292     reserved = 1;
23293   }else{
23294     /* The lock is held if and only if the lockfile exists */
23295     const char *zLockFile = (const char*)pFile->lockingContext;
23296     reserved = access(zLockFile, 0)==0;
23297   }
23298   OSTRACE4("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved);
23299   *pResOut = reserved;
23300   return rc;
23301 }
23302
23303 /*
23304 ** Lock the file with the lock specified by parameter locktype - one
23305 ** of the following:
23306 **
23307 **     (1) SHARED_LOCK
23308 **     (2) RESERVED_LOCK
23309 **     (3) PENDING_LOCK
23310 **     (4) EXCLUSIVE_LOCK
23311 **
23312 ** Sometimes when requesting one lock state, additional lock states
23313 ** are inserted in between.  The locking might fail on one of the later
23314 ** transitions leaving the lock state different from what it started but
23315 ** still short of its goal.  The following chart shows the allowed
23316 ** transitions and the inserted intermediate states:
23317 **
23318 **    UNLOCKED -> SHARED
23319 **    SHARED -> RESERVED
23320 **    SHARED -> (PENDING) -> EXCLUSIVE
23321 **    RESERVED -> (PENDING) -> EXCLUSIVE
23322 **    PENDING -> EXCLUSIVE
23323 **
23324 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23325 ** routine to lower a locking level.
23326 **
23327 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
23328 ** But we track the other locking levels internally.
23329 */
23330 static int dotlockLock(sqlite3_file *id, int locktype) {
23331   unixFile *pFile = (unixFile*)id;
23332   int fd;
23333   char *zLockFile = (char *)pFile->lockingContext;
23334   int rc = SQLITE_OK;
23335
23336
23337   /* If we have any lock, then the lock file already exists.  All we have
23338   ** to do is adjust our internal record of the lock level.
23339   */
23340   if( pFile->locktype > NO_LOCK ){
23341     pFile->locktype = locktype;
23342 #if !OS_VXWORKS
23343     /* Always update the timestamp on the old file */
23344     utimes(zLockFile, NULL);
23345 #endif
23346     return SQLITE_OK;
23347   }
23348   
23349   /* grab an exclusive lock */
23350   fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
23351   if( fd<0 ){
23352     /* failed to open/create the file, someone else may have stolen the lock */
23353     int tErrno = errno;
23354     if( EEXIST == tErrno ){
23355       rc = SQLITE_BUSY;
23356     } else {
23357       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23358       if( IS_LOCK_ERROR(rc) ){
23359         pFile->lastErrno = tErrno;
23360       }
23361     }
23362     return rc;
23363   } 
23364   if( close(fd) ){
23365     pFile->lastErrno = errno;
23366     rc = SQLITE_IOERR_CLOSE;
23367   }
23368   
23369   /* got it, set the type and return ok */
23370   pFile->locktype = locktype;
23371   return rc;
23372 }
23373
23374 /*
23375 ** Lower the locking level on file descriptor pFile to locktype.  locktype
23376 ** must be either NO_LOCK or SHARED_LOCK.
23377 **
23378 ** If the locking level of the file descriptor is already at or below
23379 ** the requested locking level, this routine is a no-op.
23380 **
23381 ** When the locking level reaches NO_LOCK, delete the lock file.
23382 */
23383 static int dotlockUnlock(sqlite3_file *id, int locktype) {
23384   unixFile *pFile = (unixFile*)id;
23385   char *zLockFile = (char *)pFile->lockingContext;
23386
23387   assert( pFile );
23388   OSTRACE5("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, locktype,
23389            pFile->locktype, getpid());
23390   assert( locktype<=SHARED_LOCK );
23391   
23392   /* no-op if possible */
23393   if( pFile->locktype==locktype ){
23394     return SQLITE_OK;
23395   }
23396
23397   /* To downgrade to shared, simply update our internal notion of the
23398   ** lock state.  No need to mess with the file on disk.
23399   */
23400   if( locktype==SHARED_LOCK ){
23401     pFile->locktype = SHARED_LOCK;
23402     return SQLITE_OK;
23403   }
23404   
23405   /* To fully unlock the database, delete the lock file */
23406   assert( locktype==NO_LOCK );
23407   if( unlink(zLockFile) ){
23408     int rc = 0;
23409     int tErrno = errno;
23410     if( ENOENT != tErrno ){
23411       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23412     }
23413     if( IS_LOCK_ERROR(rc) ){
23414       pFile->lastErrno = tErrno;
23415     }
23416     return rc; 
23417   }
23418   pFile->locktype = NO_LOCK;
23419   return SQLITE_OK;
23420 }
23421
23422 /*
23423 ** Close a file.  Make sure the lock has been released before closing.
23424 */
23425 static int dotlockClose(sqlite3_file *id) {
23426   int rc;
23427   if( id ){
23428     unixFile *pFile = (unixFile*)id;
23429     dotlockUnlock(id, NO_LOCK);
23430     sqlite3_free(pFile->lockingContext);
23431   }
23432   rc = closeUnixFile(id);
23433   return rc;
23434 }
23435 /****************** End of the dot-file lock implementation *******************
23436 ******************************************************************************/
23437
23438 /******************************************************************************
23439 ************************** Begin flock Locking ********************************
23440 **
23441 ** Use the flock() system call to do file locking.
23442 **
23443 ** flock() locking is like dot-file locking in that the various
23444 ** fine-grain locking levels supported by SQLite are collapsed into
23445 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
23446 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
23447 ** still works when you do this, but concurrency is reduced since
23448 ** only a single process can be reading the database at a time.
23449 **
23450 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
23451 ** compiling for VXWORKS.
23452 */
23453 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
23454
23455 /*
23456 ** This routine checks if there is a RESERVED lock held on the specified
23457 ** file by this or any other process. If such a lock is held, set *pResOut
23458 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23459 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23460 */
23461 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
23462   int rc = SQLITE_OK;
23463   int reserved = 0;
23464   unixFile *pFile = (unixFile*)id;
23465   
23466   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23467   
23468   assert( pFile );
23469   
23470   /* Check if a thread in this process holds such a lock */
23471   if( pFile->locktype>SHARED_LOCK ){
23472     reserved = 1;
23473   }
23474   
23475   /* Otherwise see if some other process holds it. */
23476   if( !reserved ){
23477     /* attempt to get the lock */
23478     int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
23479     if( !lrc ){
23480       /* got the lock, unlock it */
23481       lrc = flock(pFile->h, LOCK_UN);
23482       if ( lrc ) {
23483         int tErrno = errno;
23484         /* unlock failed with an error */
23485         lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
23486         if( IS_LOCK_ERROR(lrc) ){
23487           pFile->lastErrno = tErrno;
23488           rc = lrc;
23489         }
23490       }
23491     } else {
23492       int tErrno = errno;
23493       reserved = 1;
23494       /* someone else might have it reserved */
23495       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
23496       if( IS_LOCK_ERROR(lrc) ){
23497         pFile->lastErrno = tErrno;
23498         rc = lrc;
23499       }
23500     }
23501   }
23502   OSTRACE4("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved);
23503
23504 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
23505   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
23506     rc = SQLITE_OK;
23507     reserved=1;
23508   }
23509 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
23510   *pResOut = reserved;
23511   return rc;
23512 }
23513
23514 /*
23515 ** Lock the file with the lock specified by parameter locktype - one
23516 ** of the following:
23517 **
23518 **     (1) SHARED_LOCK
23519 **     (2) RESERVED_LOCK
23520 **     (3) PENDING_LOCK
23521 **     (4) EXCLUSIVE_LOCK
23522 **
23523 ** Sometimes when requesting one lock state, additional lock states
23524 ** are inserted in between.  The locking might fail on one of the later
23525 ** transitions leaving the lock state different from what it started but
23526 ** still short of its goal.  The following chart shows the allowed
23527 ** transitions and the inserted intermediate states:
23528 **
23529 **    UNLOCKED -> SHARED
23530 **    SHARED -> RESERVED
23531 **    SHARED -> (PENDING) -> EXCLUSIVE
23532 **    RESERVED -> (PENDING) -> EXCLUSIVE
23533 **    PENDING -> EXCLUSIVE
23534 **
23535 ** flock() only really support EXCLUSIVE locks.  We track intermediate
23536 ** lock states in the sqlite3_file structure, but all locks SHARED or
23537 ** above are really EXCLUSIVE locks and exclude all other processes from
23538 ** access the file.
23539 **
23540 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23541 ** routine to lower a locking level.
23542 */
23543 static int flockLock(sqlite3_file *id, int locktype) {
23544   int rc = SQLITE_OK;
23545   unixFile *pFile = (unixFile*)id;
23546
23547   assert( pFile );
23548
23549   /* if we already have a lock, it is exclusive.  
23550   ** Just adjust level and punt on outta here. */
23551   if (pFile->locktype > NO_LOCK) {
23552     pFile->locktype = locktype;
23553     return SQLITE_OK;
23554   }
23555   
23556   /* grab an exclusive lock */
23557   
23558   if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
23559     int tErrno = errno;
23560     /* didn't get, must be busy */
23561     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23562     if( IS_LOCK_ERROR(rc) ){
23563       pFile->lastErrno = tErrno;
23564     }
23565   } else {
23566     /* got it, set the type and return ok */
23567     pFile->locktype = locktype;
23568   }
23569   OSTRACE4("LOCK    %d %s %s (flock)\n", pFile->h, locktypeName(locktype), 
23570            rc==SQLITE_OK ? "ok" : "failed");
23571 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
23572   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
23573     rc = SQLITE_BUSY;
23574   }
23575 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
23576   return rc;
23577 }
23578
23579
23580 /*
23581 ** Lower the locking level on file descriptor pFile to locktype.  locktype
23582 ** must be either NO_LOCK or SHARED_LOCK.
23583 **
23584 ** If the locking level of the file descriptor is already at or below
23585 ** the requested locking level, this routine is a no-op.
23586 */
23587 static int flockUnlock(sqlite3_file *id, int locktype) {
23588   unixFile *pFile = (unixFile*)id;
23589   
23590   assert( pFile );
23591   OSTRACE5("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, locktype,
23592            pFile->locktype, getpid());
23593   assert( locktype<=SHARED_LOCK );
23594   
23595   /* no-op if possible */
23596   if( pFile->locktype==locktype ){
23597     return SQLITE_OK;
23598   }
23599   
23600   /* shared can just be set because we always have an exclusive */
23601   if (locktype==SHARED_LOCK) {
23602     pFile->locktype = locktype;
23603     return SQLITE_OK;
23604   }
23605   
23606   /* no, really, unlock. */
23607   int rc = flock(pFile->h, LOCK_UN);
23608   if (rc) {
23609     int r, tErrno = errno;
23610     r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23611     if( IS_LOCK_ERROR(r) ){
23612       pFile->lastErrno = tErrno;
23613     }
23614 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
23615     if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
23616       r = SQLITE_BUSY;
23617     }
23618 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
23619     
23620     return r;
23621   } else {
23622     pFile->locktype = NO_LOCK;
23623     return SQLITE_OK;
23624   }
23625 }
23626
23627 /*
23628 ** Close a file.
23629 */
23630 static int flockClose(sqlite3_file *id) {
23631   if( id ){
23632     flockUnlock(id, NO_LOCK);
23633   }
23634   return closeUnixFile(id);
23635 }
23636
23637 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
23638
23639 /******************* End of the flock lock implementation *********************
23640 ******************************************************************************/
23641
23642 /******************************************************************************
23643 ************************ Begin Named Semaphore Locking ************************
23644 **
23645 ** Named semaphore locking is only supported on VxWorks.
23646 **
23647 ** Semaphore locking is like dot-lock and flock in that it really only
23648 ** supports EXCLUSIVE locking.  Only a single process can read or write
23649 ** the database file at a time.  This reduces potential concurrency, but
23650 ** makes the lock implementation much easier.
23651 */
23652 #if OS_VXWORKS
23653
23654 /*
23655 ** This routine checks if there is a RESERVED lock held on the specified
23656 ** file by this or any other process. If such a lock is held, set *pResOut
23657 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23658 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23659 */
23660 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
23661   int rc = SQLITE_OK;
23662   int reserved = 0;
23663   unixFile *pFile = (unixFile*)id;
23664
23665   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23666   
23667   assert( pFile );
23668
23669   /* Check if a thread in this process holds such a lock */
23670   if( pFile->locktype>SHARED_LOCK ){
23671     reserved = 1;
23672   }
23673   
23674   /* Otherwise see if some other process holds it. */
23675   if( !reserved ){
23676     sem_t *pSem = pFile->pOpen->pSem;
23677     struct stat statBuf;
23678
23679     if( sem_trywait(pSem)==-1 ){
23680       int tErrno = errno;
23681       if( EAGAIN != tErrno ){
23682         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23683         pFile->lastErrno = tErrno;
23684       } else {
23685         /* someone else has the lock when we are in NO_LOCK */
23686         reserved = (pFile->locktype < SHARED_LOCK);
23687       }
23688     }else{
23689       /* we could have it if we want it */
23690       sem_post(pSem);
23691     }
23692   }
23693   OSTRACE4("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved);
23694
23695   *pResOut = reserved;
23696   return rc;
23697 }
23698
23699 /*
23700 ** Lock the file with the lock specified by parameter locktype - one
23701 ** of the following:
23702 **
23703 **     (1) SHARED_LOCK
23704 **     (2) RESERVED_LOCK
23705 **     (3) PENDING_LOCK
23706 **     (4) EXCLUSIVE_LOCK
23707 **
23708 ** Sometimes when requesting one lock state, additional lock states
23709 ** are inserted in between.  The locking might fail on one of the later
23710 ** transitions leaving the lock state different from what it started but
23711 ** still short of its goal.  The following chart shows the allowed
23712 ** transitions and the inserted intermediate states:
23713 **
23714 **    UNLOCKED -> SHARED
23715 **    SHARED -> RESERVED
23716 **    SHARED -> (PENDING) -> EXCLUSIVE
23717 **    RESERVED -> (PENDING) -> EXCLUSIVE
23718 **    PENDING -> EXCLUSIVE
23719 **
23720 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
23721 ** lock states in the sqlite3_file structure, but all locks SHARED or
23722 ** above are really EXCLUSIVE locks and exclude all other processes from
23723 ** access the file.
23724 **
23725 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23726 ** routine to lower a locking level.
23727 */
23728 static int semLock(sqlite3_file *id, int locktype) {
23729   unixFile *pFile = (unixFile*)id;
23730   int fd;
23731   sem_t *pSem = pFile->pOpen->pSem;
23732   int rc = SQLITE_OK;
23733
23734   /* if we already have a lock, it is exclusive.  
23735   ** Just adjust level and punt on outta here. */
23736   if (pFile->locktype > NO_LOCK) {
23737     pFile->locktype = locktype;
23738     rc = SQLITE_OK;
23739     goto sem_end_lock;
23740   }
23741   
23742   /* lock semaphore now but bail out when already locked. */
23743   if( sem_trywait(pSem)==-1 ){
23744     rc = SQLITE_BUSY;
23745     goto sem_end_lock;
23746   }
23747
23748   /* got it, set the type and return ok */
23749   pFile->locktype = locktype;
23750
23751  sem_end_lock:
23752   return rc;
23753 }
23754
23755 /*
23756 ** Lower the locking level on file descriptor pFile to locktype.  locktype
23757 ** must be either NO_LOCK or SHARED_LOCK.
23758 **
23759 ** If the locking level of the file descriptor is already at or below
23760 ** the requested locking level, this routine is a no-op.
23761 */
23762 static int semUnlock(sqlite3_file *id, int locktype) {
23763   unixFile *pFile = (unixFile*)id;
23764   sem_t *pSem = pFile->pOpen->pSem;
23765
23766   assert( pFile );
23767   assert( pSem );
23768   OSTRACE5("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, locktype,
23769            pFile->locktype, getpid());
23770   assert( locktype<=SHARED_LOCK );
23771   
23772   /* no-op if possible */
23773   if( pFile->locktype==locktype ){
23774     return SQLITE_OK;
23775   }
23776   
23777   /* shared can just be set because we always have an exclusive */
23778   if (locktype==SHARED_LOCK) {
23779     pFile->locktype = locktype;
23780     return SQLITE_OK;
23781   }
23782   
23783   /* no, really unlock. */
23784   if ( sem_post(pSem)==-1 ) {
23785     int rc, tErrno = errno;
23786     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23787     if( IS_LOCK_ERROR(rc) ){
23788       pFile->lastErrno = tErrno;
23789     }
23790     return rc; 
23791   }
23792   pFile->locktype = NO_LOCK;
23793   return SQLITE_OK;
23794 }
23795
23796 /*
23797  ** Close a file.
23798  */
23799 static int semClose(sqlite3_file *id) {
23800   if( id ){
23801     unixFile *pFile = (unixFile*)id;
23802     semUnlock(id, NO_LOCK);
23803     assert( pFile );
23804     unixEnterMutex();
23805     releaseLockInfo(pFile->pLock);
23806     releaseOpenCnt(pFile->pOpen);
23807     unixLeaveMutex();
23808     closeUnixFile(id);
23809   }
23810   return SQLITE_OK;
23811 }
23812
23813 #endif /* OS_VXWORKS */
23814 /*
23815 ** Named semaphore locking is only available on VxWorks.
23816 **
23817 *************** End of the named semaphore lock implementation ****************
23818 ******************************************************************************/
23819
23820
23821 /******************************************************************************
23822 *************************** Begin AFP Locking *********************************
23823 **
23824 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
23825 ** on Apple Macintosh computers - both OS9 and OSX.
23826 **
23827 ** Third-party implementations of AFP are available.  But this code here
23828 ** only works on OSX.
23829 */
23830
23831 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
23832 /*
23833 ** The afpLockingContext structure contains all afp lock specific state
23834 */
23835 typedef struct afpLockingContext afpLockingContext;
23836 struct afpLockingContext {
23837   unsigned long long sharedByte;
23838   const char *dbPath;             /* Name of the open file */
23839 };
23840
23841 struct ByteRangeLockPB2
23842 {
23843   unsigned long long offset;        /* offset to first byte to lock */
23844   unsigned long long length;        /* nbr of bytes to lock */
23845   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
23846   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
23847   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
23848   int fd;                           /* file desc to assoc this lock with */
23849 };
23850
23851 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
23852
23853 /*
23854 ** This is a utility for setting or clearing a bit-range lock on an
23855 ** AFP filesystem.
23856 ** 
23857 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
23858 */
23859 static int afpSetLock(
23860   const char *path,              /* Name of the file to be locked or unlocked */
23861   unixFile *pFile,               /* Open file descriptor on path */
23862   unsigned long long offset,     /* First byte to be locked */
23863   unsigned long long length,     /* Number of bytes to lock */
23864   int setLockFlag                /* True to set lock.  False to clear lock */
23865 ){
23866   struct ByteRangeLockPB2 pb;
23867   int err;
23868   
23869   pb.unLockFlag = setLockFlag ? 0 : 1;
23870   pb.startEndFlag = 0;
23871   pb.offset = offset;
23872   pb.length = length; 
23873   pb.fd = pFile->h;
23874   
23875   OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
23876     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
23877     offset, length);
23878   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
23879   if ( err==-1 ) {
23880     int rc;
23881     int tErrno = errno;
23882     OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
23883              path, tErrno, strerror(tErrno));
23884 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
23885     rc = SQLITE_BUSY;
23886 #else
23887     rc = sqliteErrorFromPosixError(tErrno,
23888                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
23889 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
23890     if( IS_LOCK_ERROR(rc) ){
23891       pFile->lastErrno = tErrno;
23892     }
23893     return rc;
23894   } else {
23895     return SQLITE_OK;
23896   }
23897 }
23898
23899 /*
23900 ** This routine checks if there is a RESERVED lock held on the specified
23901 ** file by this or any other process. If such a lock is held, set *pResOut
23902 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23903 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23904 */
23905 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
23906   int rc = SQLITE_OK;
23907   int reserved = 0;
23908   unixFile *pFile = (unixFile*)id;
23909   
23910   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23911   
23912   assert( pFile );
23913   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23914   
23915   /* Check if a thread in this process holds such a lock */
23916   if( pFile->locktype>SHARED_LOCK ){
23917     reserved = 1;
23918   }
23919   
23920   /* Otherwise see if some other process holds it.
23921    */
23922   if( !reserved ){
23923     /* lock the RESERVED byte */
23924     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
23925     if( SQLITE_OK==lrc ){
23926       /* if we succeeded in taking the reserved lock, unlock it to restore
23927       ** the original state */
23928       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
23929     } else {
23930       /* if we failed to get the lock then someone else must have it */
23931       reserved = 1;
23932     }
23933     if( IS_LOCK_ERROR(lrc) ){
23934       rc=lrc;
23935     }
23936   }
23937   
23938   OSTRACE4("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved);
23939   
23940   *pResOut = reserved;
23941   return rc;
23942 }
23943
23944 /*
23945 ** Lock the file with the lock specified by parameter locktype - one
23946 ** of the following:
23947 **
23948 **     (1) SHARED_LOCK
23949 **     (2) RESERVED_LOCK
23950 **     (3) PENDING_LOCK
23951 **     (4) EXCLUSIVE_LOCK
23952 **
23953 ** Sometimes when requesting one lock state, additional lock states
23954 ** are inserted in between.  The locking might fail on one of the later
23955 ** transitions leaving the lock state different from what it started but
23956 ** still short of its goal.  The following chart shows the allowed
23957 ** transitions and the inserted intermediate states:
23958 **
23959 **    UNLOCKED -> SHARED
23960 **    SHARED -> RESERVED
23961 **    SHARED -> (PENDING) -> EXCLUSIVE
23962 **    RESERVED -> (PENDING) -> EXCLUSIVE
23963 **    PENDING -> EXCLUSIVE
23964 **
23965 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23966 ** routine to lower a locking level.
23967 */
23968 static int afpLock(sqlite3_file *id, int locktype){
23969   int rc = SQLITE_OK;
23970   unixFile *pFile = (unixFile*)id;
23971   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23972   
23973   assert( pFile );
23974   OSTRACE5("LOCK    %d %s was %s pid=%d (afp)\n", pFile->h,
23975          locktypeName(locktype), locktypeName(pFile->locktype), getpid());
23976
23977   /* If there is already a lock of this type or more restrictive on the
23978   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
23979   ** unixEnterMutex() hasn't been called yet.
23980   */
23981   if( pFile->locktype>=locktype ){
23982     OSTRACE3("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
23983            locktypeName(locktype));
23984     return SQLITE_OK;
23985   }
23986
23987   /* Make sure the locking sequence is correct
23988   */
23989   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
23990   assert( locktype!=PENDING_LOCK );
23991   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
23992   
23993   /* This mutex is needed because pFile->pLock is shared across threads
23994   */
23995   unixEnterMutex();
23996
23997   /* Make sure the current thread owns the pFile.
23998   */
23999   rc = transferOwnership(pFile);
24000   if( rc!=SQLITE_OK ){
24001     unixLeaveMutex();
24002     return rc;
24003   }
24004     
24005   /* A PENDING lock is needed before acquiring a SHARED lock and before
24006   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24007   ** be released.
24008   */
24009   if( locktype==SHARED_LOCK 
24010       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
24011   ){
24012     int failed;
24013     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
24014     if (failed) {
24015       rc = failed;
24016       goto afp_end_lock;
24017     }
24018   }
24019   
24020   /* If control gets to this point, then actually go ahead and make
24021   ** operating system calls for the specified lock.
24022   */
24023   if( locktype==SHARED_LOCK ){
24024     int lk, lrc1, lrc2;
24025     int lrc1Errno = 0;
24026     
24027     /* Now get the read-lock SHARED_LOCK */
24028     /* note that the quality of the randomness doesn't matter that much */
24029     lk = random(); 
24030     context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
24031     lrc1 = afpSetLock(context->dbPath, pFile, 
24032           SHARED_FIRST+context->sharedByte, 1, 1);
24033     if( IS_LOCK_ERROR(lrc1) ){
24034       lrc1Errno = pFile->lastErrno;
24035     }
24036     /* Drop the temporary PENDING lock */
24037     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
24038     
24039     if( IS_LOCK_ERROR(lrc1) ) {
24040       pFile->lastErrno = lrc1Errno;
24041       rc = lrc1;
24042       goto afp_end_lock;
24043     } else if( IS_LOCK_ERROR(lrc2) ){
24044       rc = lrc2;
24045       goto afp_end_lock;
24046     } else if( lrc1 != SQLITE_OK ) {
24047       rc = lrc1;
24048     } else {
24049       pFile->locktype = SHARED_LOCK;
24050       pFile->pOpen->nLock++;
24051     }
24052   }else{
24053     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24054     ** assumed that there is a SHARED or greater lock on the file
24055     ** already.
24056     */
24057     int failed = 0;
24058     assert( 0!=pFile->locktype );
24059     if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
24060         /* Acquire a RESERVED lock */
24061         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
24062     }
24063     if (!failed && locktype == EXCLUSIVE_LOCK) {
24064       /* Acquire an EXCLUSIVE lock */
24065         
24066       /* Remove the shared lock before trying the range.  we'll need to 
24067       ** reestablish the shared lock if we can't get the  afpUnlock
24068       */
24069       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
24070                          context->sharedByte, 1, 0)) ){
24071         int failed2 = SQLITE_OK;
24072         /* now attemmpt to get the exclusive lock range */
24073         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
24074                                SHARED_SIZE, 1);
24075         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
24076                        SHARED_FIRST + context->sharedByte, 1, 1)) ){
24077           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
24078           ** a critical I/O error
24079           */
24080           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
24081                SQLITE_IOERR_LOCK;
24082           goto afp_end_lock;
24083         } 
24084       }else{
24085         rc = failed; 
24086       }
24087     }
24088     if( failed ){
24089       rc = failed;
24090     }
24091   }
24092   
24093   if( rc==SQLITE_OK ){
24094     pFile->locktype = locktype;
24095   }else if( locktype==EXCLUSIVE_LOCK ){
24096     pFile->locktype = PENDING_LOCK;
24097   }
24098   
24099 afp_end_lock:
24100   unixLeaveMutex();
24101   OSTRACE4("LOCK    %d %s %s (afp)\n", pFile->h, locktypeName(locktype), 
24102          rc==SQLITE_OK ? "ok" : "failed");
24103   return rc;
24104 }
24105
24106 /*
24107 ** Lower the locking level on file descriptor pFile to locktype.  locktype
24108 ** must be either NO_LOCK or SHARED_LOCK.
24109 **
24110 ** If the locking level of the file descriptor is already at or below
24111 ** the requested locking level, this routine is a no-op.
24112 */
24113 static int afpUnlock(sqlite3_file *id, int locktype) {
24114   int rc = SQLITE_OK;
24115   unixFile *pFile = (unixFile*)id;
24116   afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
24117
24118   assert( pFile );
24119   OSTRACE5("UNLOCK  %d %d was %d pid=%d (afp)\n", pFile->h, locktype,
24120          pFile->locktype, getpid());
24121
24122   assert( locktype<=SHARED_LOCK );
24123   if( pFile->locktype<=locktype ){
24124     return SQLITE_OK;
24125   }
24126   if( CHECK_THREADID(pFile) ){
24127     return SQLITE_MISUSE;
24128   }
24129   unixEnterMutex();
24130   if( pFile->locktype>SHARED_LOCK ){
24131     
24132     if( pFile->locktype==EXCLUSIVE_LOCK ){
24133       rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
24134       if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
24135         /* only re-establish the shared lock if necessary */
24136         int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
24137         rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
24138       }
24139     }
24140     if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
24141       rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
24142     } 
24143     if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
24144       rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
24145     }
24146   }else if( locktype==NO_LOCK ){
24147     /* clear the shared lock */
24148     int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
24149     rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
24150   }
24151
24152   if( rc==SQLITE_OK ){
24153     if( locktype==NO_LOCK ){
24154       struct unixOpenCnt *pOpen = pFile->pOpen;
24155       pOpen->nLock--;
24156       assert( pOpen->nLock>=0 );
24157       if( pOpen->nLock==0 ){
24158         rc = closePendingFds(pFile);
24159       }
24160     }
24161   }
24162   unixLeaveMutex();
24163   if( rc==SQLITE_OK ){
24164     pFile->locktype = locktype;
24165   }
24166   return rc;
24167 }
24168
24169 /*
24170 ** Close a file & cleanup AFP specific locking context 
24171 */
24172 static int afpClose(sqlite3_file *id) {
24173   if( id ){
24174     unixFile *pFile = (unixFile*)id;
24175     afpUnlock(id, NO_LOCK);
24176     unixEnterMutex();
24177     if( pFile->pOpen && pFile->pOpen->nLock ){
24178       /* If there are outstanding locks, do not actually close the file just
24179       ** yet because that would clear those locks.  Instead, add the file
24180       ** descriptor to pOpen->aPending.  It will be automatically closed when
24181       ** the last lock is cleared.
24182       */
24183       setPendingFd(pFile);
24184     }
24185     releaseOpenCnt(pFile->pOpen);
24186     sqlite3_free(pFile->lockingContext);
24187     closeUnixFile(id);
24188     unixLeaveMutex();
24189   }
24190   return SQLITE_OK;
24191 }
24192
24193 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24194 /*
24195 ** The code above is the AFP lock implementation.  The code is specific
24196 ** to MacOSX and does not work on other unix platforms.  No alternative
24197 ** is available.  If you don't compile for a mac, then the "unix-afp"
24198 ** VFS is not available.
24199 **
24200 ********************* End of the AFP lock implementation **********************
24201 ******************************************************************************/
24202
24203
24204 /******************************************************************************
24205 **************** Non-locking sqlite3_file methods *****************************
24206 **
24207 ** The next division contains implementations for all methods of the 
24208 ** sqlite3_file object other than the locking methods.  The locking
24209 ** methods were defined in divisions above (one locking method per
24210 ** division).  Those methods that are common to all locking modes
24211 ** are gather together into this division.
24212 */
24213
24214 /*
24215 ** Seek to the offset passed as the second argument, then read cnt 
24216 ** bytes into pBuf. Return the number of bytes actually read.
24217 **
24218 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
24219 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
24220 ** one system to another.  Since SQLite does not define USE_PREAD
24221 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
24222 ** See tickets #2741 and #2681.
24223 **
24224 ** To avoid stomping the errno value on a failed read the lastErrno value
24225 ** is set before returning.
24226 */
24227 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
24228   int got;
24229   i64 newOffset;
24230   TIMER_START;
24231 #if defined(USE_PREAD)
24232   got = pread(id->h, pBuf, cnt, offset);
24233   SimulateIOError( got = -1 );
24234 #elif defined(USE_PREAD64)
24235   got = pread64(id->h, pBuf, cnt, offset);
24236   SimulateIOError( got = -1 );
24237 #else
24238   newOffset = lseek(id->h, offset, SEEK_SET);
24239   SimulateIOError( newOffset-- );
24240   if( newOffset!=offset ){
24241     if( newOffset == -1 ){
24242       ((unixFile*)id)->lastErrno = errno;
24243     }else{
24244       ((unixFile*)id)->lastErrno = 0;                   
24245     }
24246     return -1;
24247   }
24248   got = read(id->h, pBuf, cnt);
24249 #endif
24250   TIMER_END;
24251   if( got<0 ){
24252     ((unixFile*)id)->lastErrno = errno;
24253   }
24254   OSTRACE5("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
24255   return got;
24256 }
24257
24258 /*
24259 ** Read data from a file into a buffer.  Return SQLITE_OK if all
24260 ** bytes were read successfully and SQLITE_IOERR if anything goes
24261 ** wrong.
24262 */
24263 static int unixRead(
24264   sqlite3_file *id, 
24265   void *pBuf, 
24266   int amt,
24267   sqlite3_int64 offset
24268 ){
24269   unixFile *pFile = (unixFile *)id;
24270   int got;
24271   assert( id );
24272
24273   /* If this is a database file (not a journal, master-journal or temp
24274   ** file), the bytes in the locking range should never be read or written. */
24275   assert( pFile->pUnused==0
24276        || offset>=PENDING_BYTE+512
24277        || offset+amt<=PENDING_BYTE 
24278   );
24279
24280   got = seekAndRead(pFile, offset, pBuf, amt);
24281   if( got==amt ){
24282     return SQLITE_OK;
24283   }else if( got<0 ){
24284     /* lastErrno set by seekAndRead */
24285     return SQLITE_IOERR_READ;
24286   }else{
24287     pFile->lastErrno = 0; /* not a system error */
24288     /* Unread parts of the buffer must be zero-filled */
24289     memset(&((char*)pBuf)[got], 0, amt-got);
24290     return SQLITE_IOERR_SHORT_READ;
24291   }
24292 }
24293
24294 /*
24295 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
24296 ** Return the number of bytes actually read.  Update the offset.
24297 **
24298 ** To avoid stomping the errno value on a failed write the lastErrno value
24299 ** is set before returning.
24300 */
24301 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
24302   int got;
24303   i64 newOffset;
24304   TIMER_START;
24305 #if defined(USE_PREAD)
24306   got = pwrite(id->h, pBuf, cnt, offset);
24307 #elif defined(USE_PREAD64)
24308   got = pwrite64(id->h, pBuf, cnt, offset);
24309 #else
24310   newOffset = lseek(id->h, offset, SEEK_SET);
24311   if( newOffset!=offset ){
24312     if( newOffset == -1 ){
24313       ((unixFile*)id)->lastErrno = errno;
24314     }else{
24315       ((unixFile*)id)->lastErrno = 0;                   
24316     }
24317     return -1;
24318   }
24319   got = write(id->h, pBuf, cnt);
24320 #endif
24321   TIMER_END;
24322   if( got<0 ){
24323     ((unixFile*)id)->lastErrno = errno;
24324   }
24325
24326   OSTRACE5("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
24327   return got;
24328 }
24329
24330
24331 /*
24332 ** Write data from a buffer into a file.  Return SQLITE_OK on success
24333 ** or some other error code on failure.
24334 */
24335 static int unixWrite(
24336   sqlite3_file *id, 
24337   const void *pBuf, 
24338   int amt,
24339   sqlite3_int64 offset 
24340 ){
24341   unixFile *pFile = (unixFile*)id;
24342   int wrote = 0;
24343   assert( id );
24344   assert( amt>0 );
24345
24346   /* If this is a database file (not a journal, master-journal or temp
24347   ** file), the bytes in the locking range should never be read or written. */
24348   assert( pFile->pUnused==0
24349        || offset>=PENDING_BYTE+512
24350        || offset+amt<=PENDING_BYTE 
24351   );
24352
24353 #ifndef NDEBUG
24354   /* If we are doing a normal write to a database file (as opposed to
24355   ** doing a hot-journal rollback or a write to some file other than a
24356   ** normal database file) then record the fact that the database
24357   ** has changed.  If the transaction counter is modified, record that
24358   ** fact too.
24359   */
24360   if( pFile->inNormalWrite ){
24361     pFile->dbUpdate = 1;  /* The database has been modified */
24362     if( offset<=24 && offset+amt>=27 ){
24363       int rc;
24364       char oldCntr[4];
24365       SimulateIOErrorBenign(1);
24366       rc = seekAndRead(pFile, 24, oldCntr, 4);
24367       SimulateIOErrorBenign(0);
24368       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
24369         pFile->transCntrChng = 1;  /* The transaction counter has changed */
24370       }
24371     }
24372   }
24373 #endif
24374
24375   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
24376     amt -= wrote;
24377     offset += wrote;
24378     pBuf = &((char*)pBuf)[wrote];
24379   }
24380   SimulateIOError(( wrote=(-1), amt=1 ));
24381   SimulateDiskfullError(( wrote=0, amt=1 ));
24382   if( amt>0 ){
24383     if( wrote<0 ){
24384       /* lastErrno set by seekAndWrite */
24385       return SQLITE_IOERR_WRITE;
24386     }else{
24387       pFile->lastErrno = 0; /* not a system error */
24388       return SQLITE_FULL;
24389     }
24390   }
24391   return SQLITE_OK;
24392 }
24393
24394 #ifdef SQLITE_TEST
24395 /*
24396 ** Count the number of fullsyncs and normal syncs.  This is used to test
24397 ** that syncs and fullsyncs are occurring at the right times.
24398 */
24399 SQLITE_API int sqlite3_sync_count = 0;
24400 SQLITE_API int sqlite3_fullsync_count = 0;
24401 #endif
24402
24403 /*
24404 ** We do not trust systems to provide a working fdatasync().  Some do.
24405 ** Others do no.  To be safe, we will stick with the (slower) fsync().
24406 ** If you know that your system does support fdatasync() correctly,
24407 ** then simply compile with -Dfdatasync=fdatasync
24408 */
24409 #if !defined(fdatasync) && !defined(__linux__)
24410 # define fdatasync fsync
24411 #endif
24412
24413 /*
24414 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
24415 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
24416 ** only available on Mac OS X.  But that could change.
24417 */
24418 #ifdef F_FULLFSYNC
24419 # define HAVE_FULLFSYNC 1
24420 #else
24421 # define HAVE_FULLFSYNC 0
24422 #endif
24423
24424
24425 /*
24426 ** The fsync() system call does not work as advertised on many
24427 ** unix systems.  The following procedure is an attempt to make
24428 ** it work better.
24429 **
24430 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
24431 ** for testing when we want to run through the test suite quickly.
24432 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
24433 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
24434 ** or power failure will likely corrupt the database file.
24435 **
24436 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
24437 ** The idea behind dataOnly is that it should only write the file content
24438 ** to disk, not the inode.  We only set dataOnly if the file size is 
24439 ** unchanged since the file size is part of the inode.  However, 
24440 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
24441 ** file size has changed.  The only real difference between fdatasync()
24442 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
24443 ** inode if the mtime or owner or other inode attributes have changed.
24444 ** We only care about the file size, not the other file attributes, so
24445 ** as far as SQLite is concerned, an fdatasync() is always adequate.
24446 ** So, we always use fdatasync() if it is available, regardless of
24447 ** the value of the dataOnly flag.
24448 */
24449 static int full_fsync(int fd, int fullSync, int dataOnly){
24450   int rc;
24451
24452   /* The following "ifdef/elif/else/" block has the same structure as
24453   ** the one below. It is replicated here solely to avoid cluttering 
24454   ** up the real code with the UNUSED_PARAMETER() macros.
24455   */
24456 #ifdef SQLITE_NO_SYNC
24457   UNUSED_PARAMETER(fd);
24458   UNUSED_PARAMETER(fullSync);
24459   UNUSED_PARAMETER(dataOnly);
24460 #elif HAVE_FULLFSYNC
24461   UNUSED_PARAMETER(dataOnly);
24462 #else
24463   UNUSED_PARAMETER(fullSync);
24464   UNUSED_PARAMETER(dataOnly);
24465 #endif
24466
24467   /* Record the number of times that we do a normal fsync() and 
24468   ** FULLSYNC.  This is used during testing to verify that this procedure
24469   ** gets called with the correct arguments.
24470   */
24471 #ifdef SQLITE_TEST
24472   if( fullSync ) sqlite3_fullsync_count++;
24473   sqlite3_sync_count++;
24474 #endif
24475
24476   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
24477   ** no-op
24478   */
24479 #ifdef SQLITE_NO_SYNC
24480   rc = SQLITE_OK;
24481 #elif HAVE_FULLFSYNC
24482   if( fullSync ){
24483     rc = fcntl(fd, F_FULLFSYNC, 0);
24484   }else{
24485     rc = 1;
24486   }
24487   /* If the FULLFSYNC failed, fall back to attempting an fsync().
24488   ** It shouldn't be possible for fullfsync to fail on the local 
24489   ** file system (on OSX), so failure indicates that FULLFSYNC
24490   ** isn't supported for this file system. So, attempt an fsync 
24491   ** and (for now) ignore the overhead of a superfluous fcntl call.  
24492   ** It'd be better to detect fullfsync support once and avoid 
24493   ** the fcntl call every time sync is called.
24494   */
24495   if( rc ) rc = fsync(fd);
24496
24497 #else 
24498   rc = fdatasync(fd);
24499 #if OS_VXWORKS
24500   if( rc==-1 && errno==ENOTSUP ){
24501     rc = fsync(fd);
24502   }
24503 #endif /* OS_VXWORKS */
24504 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
24505
24506   if( OS_VXWORKS && rc!= -1 ){
24507     rc = 0;
24508   }
24509   return rc;
24510 }
24511
24512 /*
24513 ** Make sure all writes to a particular file are committed to disk.
24514 **
24515 ** If dataOnly==0 then both the file itself and its metadata (file
24516 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
24517 ** file data is synced.
24518 **
24519 ** Under Unix, also make sure that the directory entry for the file
24520 ** has been created by fsync-ing the directory that contains the file.
24521 ** If we do not do this and we encounter a power failure, the directory
24522 ** entry for the journal might not exist after we reboot.  The next
24523 ** SQLite to access the file will not know that the journal exists (because
24524 ** the directory entry for the journal was never created) and the transaction
24525 ** will not roll back - possibly leading to database corruption.
24526 */
24527 static int unixSync(sqlite3_file *id, int flags){
24528   int rc;
24529   unixFile *pFile = (unixFile*)id;
24530
24531   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
24532   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
24533
24534   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
24535   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
24536       || (flags&0x0F)==SQLITE_SYNC_FULL
24537   );
24538
24539   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
24540   ** line is to test that doing so does not cause any problems.
24541   */
24542   SimulateDiskfullError( return SQLITE_FULL );
24543
24544   assert( pFile );
24545   OSTRACE2("SYNC    %-3d\n", pFile->h);
24546   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
24547   SimulateIOError( rc=1 );
24548   if( rc ){
24549     pFile->lastErrno = errno;
24550     return SQLITE_IOERR_FSYNC;
24551   }
24552   if( pFile->dirfd>=0 ){
24553     int err;
24554     OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
24555             HAVE_FULLFSYNC, isFullsync);
24556 #ifndef SQLITE_DISABLE_DIRSYNC
24557     /* The directory sync is only attempted if full_fsync is
24558     ** turned off or unavailable.  If a full_fsync occurred above,
24559     ** then the directory sync is superfluous.
24560     */
24561     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
24562        /*
24563        ** We have received multiple reports of fsync() returning
24564        ** errors when applied to directories on certain file systems.
24565        ** A failed directory sync is not a big deal.  So it seems
24566        ** better to ignore the error.  Ticket #1657
24567        */
24568        /* pFile->lastErrno = errno; */
24569        /* return SQLITE_IOERR; */
24570     }
24571 #endif
24572     err = close(pFile->dirfd); /* Only need to sync once, so close the */
24573     if( err==0 ){              /* directory when we are done */
24574       pFile->dirfd = -1;
24575     }else{
24576       pFile->lastErrno = errno;
24577       rc = SQLITE_IOERR_DIR_CLOSE;
24578     }
24579   }
24580   return rc;
24581 }
24582
24583 /*
24584 ** Truncate an open file to a specified size
24585 */
24586 static int unixTruncate(sqlite3_file *id, i64 nByte){
24587   int rc;
24588   assert( id );
24589   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
24590   rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
24591   if( rc ){
24592     ((unixFile*)id)->lastErrno = errno;
24593     return SQLITE_IOERR_TRUNCATE;
24594   }else{
24595 #ifndef NDEBUG
24596     /* If we are doing a normal write to a database file (as opposed to
24597     ** doing a hot-journal rollback or a write to some file other than a
24598     ** normal database file) and we truncate the file to zero length,
24599     ** that effectively updates the change counter.  This might happen
24600     ** when restoring a database using the backup API from a zero-length
24601     ** source.
24602     */
24603     if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
24604       ((unixFile*)id)->transCntrChng = 1;
24605     }
24606 #endif
24607
24608     return SQLITE_OK;
24609   }
24610 }
24611
24612 /*
24613 ** Determine the current size of a file in bytes
24614 */
24615 static int unixFileSize(sqlite3_file *id, i64 *pSize){
24616   int rc;
24617   struct stat buf;
24618   assert( id );
24619   rc = fstat(((unixFile*)id)->h, &buf);
24620   SimulateIOError( rc=1 );
24621   if( rc!=0 ){
24622     ((unixFile*)id)->lastErrno = errno;
24623     return SQLITE_IOERR_FSTAT;
24624   }
24625   *pSize = buf.st_size;
24626
24627   /* When opening a zero-size database, the findLockInfo() procedure
24628   ** writes a single byte into that file in order to work around a bug
24629   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
24630   ** layers, we need to report this file size as zero even though it is
24631   ** really 1.   Ticket #3260.
24632   */
24633   if( *pSize==1 ) *pSize = 0;
24634
24635
24636   return SQLITE_OK;
24637 }
24638
24639 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
24640 /*
24641 ** Handler for proxy-locking file-control verbs.  Defined below in the
24642 ** proxying locking division.
24643 */
24644 static int proxyFileControl(sqlite3_file*,int,void*);
24645 #endif
24646
24647
24648 /*
24649 ** Information and control of an open file handle.
24650 */
24651 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
24652   switch( op ){
24653     case SQLITE_FCNTL_LOCKSTATE: {
24654       *(int*)pArg = ((unixFile*)id)->locktype;
24655       return SQLITE_OK;
24656     }
24657     case SQLITE_LAST_ERRNO: {
24658       *(int*)pArg = ((unixFile*)id)->lastErrno;
24659       return SQLITE_OK;
24660     }
24661 #ifndef NDEBUG
24662     /* The pager calls this method to signal that it has done
24663     ** a rollback and that the database is therefore unchanged and
24664     ** it hence it is OK for the transaction change counter to be
24665     ** unchanged.
24666     */
24667     case SQLITE_FCNTL_DB_UNCHANGED: {
24668       ((unixFile*)id)->dbUpdate = 0;
24669       return SQLITE_OK;
24670     }
24671 #endif
24672 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
24673     case SQLITE_SET_LOCKPROXYFILE:
24674     case SQLITE_GET_LOCKPROXYFILE: {
24675       return proxyFileControl(id,op,pArg);
24676     }
24677 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
24678   }
24679   return SQLITE_ERROR;
24680 }
24681
24682 /*
24683 ** Return the sector size in bytes of the underlying block device for
24684 ** the specified file. This is almost always 512 bytes, but may be
24685 ** larger for some devices.
24686 **
24687 ** SQLite code assumes this function cannot fail. It also assumes that
24688 ** if two files are created in the same file-system directory (i.e.
24689 ** a database and its journal file) that the sector size will be the
24690 ** same for both.
24691 */
24692 static int unixSectorSize(sqlite3_file *NotUsed){
24693   UNUSED_PARAMETER(NotUsed);
24694   return SQLITE_DEFAULT_SECTOR_SIZE;
24695 }
24696
24697 /*
24698 ** Return the device characteristics for the file. This is always 0 for unix.
24699 */
24700 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
24701   UNUSED_PARAMETER(NotUsed);
24702   return 0;
24703 }
24704
24705 /*
24706 ** Here ends the implementation of all sqlite3_file methods.
24707 **
24708 ********************** End sqlite3_file Methods *******************************
24709 ******************************************************************************/
24710
24711 /*
24712 ** This division contains definitions of sqlite3_io_methods objects that
24713 ** implement various file locking strategies.  It also contains definitions
24714 ** of "finder" functions.  A finder-function is used to locate the appropriate
24715 ** sqlite3_io_methods object for a particular database file.  The pAppData
24716 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
24717 ** the correct finder-function for that VFS.
24718 **
24719 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
24720 ** object.  The only interesting finder-function is autolockIoFinder, which
24721 ** looks at the filesystem type and tries to guess the best locking
24722 ** strategy from that.
24723 **
24724 ** For finder-funtion F, two objects are created:
24725 **
24726 **    (1) The real finder-function named "FImpt()".
24727 **
24728 **    (2) A constant pointer to this function named just "F".
24729 **
24730 **
24731 ** A pointer to the F pointer is used as the pAppData value for VFS
24732 ** objects.  We have to do this instead of letting pAppData point
24733 ** directly at the finder-function since C90 rules prevent a void*
24734 ** from be cast into a function pointer.
24735 **
24736 **
24737 ** Each instance of this macro generates two objects:
24738 **
24739 **   *  A constant sqlite3_io_methods object call METHOD that has locking
24740 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
24741 **
24742 **   *  An I/O method finder function called FINDER that returns a pointer
24743 **      to the METHOD object in the previous bullet.
24744 */
24745 #define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK)               \
24746 static const sqlite3_io_methods METHOD = {                                   \
24747    1,                          /* iVersion */                                \
24748    CLOSE,                      /* xClose */                                  \
24749    unixRead,                   /* xRead */                                   \
24750    unixWrite,                  /* xWrite */                                  \
24751    unixTruncate,               /* xTruncate */                               \
24752    unixSync,                   /* xSync */                                   \
24753    unixFileSize,               /* xFileSize */                               \
24754    LOCK,                       /* xLock */                                   \
24755    UNLOCK,                     /* xUnlock */                                 \
24756    CKLOCK,                     /* xCheckReservedLock */                      \
24757    unixFileControl,            /* xFileControl */                            \
24758    unixSectorSize,             /* xSectorSize */                             \
24759    unixDeviceCharacteristics   /* xDeviceCapabilities */                     \
24760 };                                                                           \
24761 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
24762   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
24763   return &METHOD;                                                            \
24764 }                                                                            \
24765 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
24766     = FINDER##Impl;
24767
24768 /*
24769 ** Here are all of the sqlite3_io_methods objects for each of the
24770 ** locking strategies.  Functions that return pointers to these methods
24771 ** are also created.
24772 */
24773 IOMETHODS(
24774   posixIoFinder,            /* Finder function name */
24775   posixIoMethods,           /* sqlite3_io_methods object name */
24776   unixClose,                /* xClose method */
24777   unixLock,                 /* xLock method */
24778   unixUnlock,               /* xUnlock method */
24779   unixCheckReservedLock     /* xCheckReservedLock method */
24780 )
24781 IOMETHODS(
24782   nolockIoFinder,           /* Finder function name */
24783   nolockIoMethods,          /* sqlite3_io_methods object name */
24784   nolockClose,              /* xClose method */
24785   nolockLock,               /* xLock method */
24786   nolockUnlock,             /* xUnlock method */
24787   nolockCheckReservedLock   /* xCheckReservedLock method */
24788 )
24789 IOMETHODS(
24790   dotlockIoFinder,          /* Finder function name */
24791   dotlockIoMethods,         /* sqlite3_io_methods object name */
24792   dotlockClose,             /* xClose method */
24793   dotlockLock,              /* xLock method */
24794   dotlockUnlock,            /* xUnlock method */
24795   dotlockCheckReservedLock  /* xCheckReservedLock method */
24796 )
24797
24798 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
24799 IOMETHODS(
24800   flockIoFinder,            /* Finder function name */
24801   flockIoMethods,           /* sqlite3_io_methods object name */
24802   flockClose,               /* xClose method */
24803   flockLock,                /* xLock method */
24804   flockUnlock,              /* xUnlock method */
24805   flockCheckReservedLock    /* xCheckReservedLock method */
24806 )
24807 #endif
24808
24809 #if OS_VXWORKS
24810 IOMETHODS(
24811   semIoFinder,              /* Finder function name */
24812   semIoMethods,             /* sqlite3_io_methods object name */
24813   semClose,                 /* xClose method */
24814   semLock,                  /* xLock method */
24815   semUnlock,                /* xUnlock method */
24816   semCheckReservedLock      /* xCheckReservedLock method */
24817 )
24818 #endif
24819
24820 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24821 IOMETHODS(
24822   afpIoFinder,              /* Finder function name */
24823   afpIoMethods,             /* sqlite3_io_methods object name */
24824   afpClose,                 /* xClose method */
24825   afpLock,                  /* xLock method */
24826   afpUnlock,                /* xUnlock method */
24827   afpCheckReservedLock      /* xCheckReservedLock method */
24828 )
24829 #endif
24830
24831 /*
24832 ** The "Whole File Locking" finder returns the same set of methods as
24833 ** the posix locking finder.  But it also sets the SQLITE_WHOLE_FILE_LOCKING
24834 ** flag to force the posix advisory locks to cover the whole file instead
24835 ** of just a small span of bytes near the 1GiB boundary.  Whole File Locking
24836 ** is useful on NFS-mounted files since it helps NFS to maintain cache
24837 ** coherency.  But it is a detriment to other filesystems since it runs
24838 ** slower.
24839 */
24840 static const sqlite3_io_methods *posixWflIoFinderImpl(const char*z, unixFile*p){
24841   UNUSED_PARAMETER(z);
24842   p->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
24843   return &posixIoMethods;
24844 }
24845 static const sqlite3_io_methods 
24846   *(*const posixWflIoFinder)(const char*,unixFile *p) = posixWflIoFinderImpl;
24847
24848 /*
24849 ** The proxy locking method is a "super-method" in the sense that it
24850 ** opens secondary file descriptors for the conch and lock files and
24851 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
24852 ** secondary files.  For this reason, the division that implements
24853 ** proxy locking is located much further down in the file.  But we need
24854 ** to go ahead and define the sqlite3_io_methods and finder function
24855 ** for proxy locking here.  So we forward declare the I/O methods.
24856 */
24857 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24858 static int proxyClose(sqlite3_file*);
24859 static int proxyLock(sqlite3_file*, int);
24860 static int proxyUnlock(sqlite3_file*, int);
24861 static int proxyCheckReservedLock(sqlite3_file*, int*);
24862 IOMETHODS(
24863   proxyIoFinder,            /* Finder function name */
24864   proxyIoMethods,           /* sqlite3_io_methods object name */
24865   proxyClose,               /* xClose method */
24866   proxyLock,                /* xLock method */
24867   proxyUnlock,              /* xUnlock method */
24868   proxyCheckReservedLock    /* xCheckReservedLock method */
24869 )
24870 #endif
24871
24872
24873 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24874 /* 
24875 ** This "finder" function attempts to determine the best locking strategy 
24876 ** for the database file "filePath".  It then returns the sqlite3_io_methods
24877 ** object that implements that strategy.
24878 **
24879 ** This is for MacOSX only.
24880 */
24881 static const sqlite3_io_methods *autolockIoFinderImpl(
24882   const char *filePath,    /* name of the database file */
24883   unixFile *pNew           /* open file object for the database file */
24884 ){
24885   static const struct Mapping {
24886     const char *zFilesystem;              /* Filesystem type name */
24887     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
24888   } aMap[] = {
24889     { "hfs",    &posixIoMethods },
24890     { "ufs",    &posixIoMethods },
24891     { "afpfs",  &afpIoMethods },
24892 #ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
24893     { "smbfs",  &afpIoMethods },
24894 #else
24895     { "smbfs",  &flockIoMethods },
24896 #endif
24897     { "webdav", &nolockIoMethods },
24898     { 0, 0 }
24899   };
24900   int i;
24901   struct statfs fsInfo;
24902   struct flock lockInfo;
24903
24904   if( !filePath ){
24905     /* If filePath==NULL that means we are dealing with a transient file
24906     ** that does not need to be locked. */
24907     return &nolockIoMethods;
24908   }
24909   if( statfs(filePath, &fsInfo) != -1 ){
24910     if( fsInfo.f_flags & MNT_RDONLY ){
24911       return &nolockIoMethods;
24912     }
24913     for(i=0; aMap[i].zFilesystem; i++){
24914       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
24915         return aMap[i].pMethods;
24916       }
24917     }
24918   }
24919
24920   /* Default case. Handles, amongst others, "nfs".
24921   ** Test byte-range lock using fcntl(). If the call succeeds, 
24922   ** assume that the file-system supports POSIX style locks. 
24923   */
24924   lockInfo.l_len = 1;
24925   lockInfo.l_start = 0;
24926   lockInfo.l_whence = SEEK_SET;
24927   lockInfo.l_type = F_RDLCK;
24928   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
24929     pNew->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
24930     return &posixIoMethods;
24931   }else{
24932     return &dotlockIoMethods;
24933   }
24934 }
24935 static const sqlite3_io_methods 
24936   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
24937
24938 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24939
24940 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
24941 /* 
24942 ** This "finder" function attempts to determine the best locking strategy 
24943 ** for the database file "filePath".  It then returns the sqlite3_io_methods
24944 ** object that implements that strategy.
24945 **
24946 ** This is for VXWorks only.
24947 */
24948 static const sqlite3_io_methods *autolockIoFinderImpl(
24949   const char *filePath,    /* name of the database file */
24950   unixFile *pNew           /* the open file object */
24951 ){
24952   struct flock lockInfo;
24953
24954   if( !filePath ){
24955     /* If filePath==NULL that means we are dealing with a transient file
24956     ** that does not need to be locked. */
24957     return &nolockIoMethods;
24958   }
24959
24960   /* Test if fcntl() is supported and use POSIX style locks.
24961   ** Otherwise fall back to the named semaphore method.
24962   */
24963   lockInfo.l_len = 1;
24964   lockInfo.l_start = 0;
24965   lockInfo.l_whence = SEEK_SET;
24966   lockInfo.l_type = F_RDLCK;
24967   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
24968     return &posixIoMethods;
24969   }else{
24970     return &semIoMethods;
24971   }
24972 }
24973 static const sqlite3_io_methods 
24974   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
24975
24976 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
24977
24978 /*
24979 ** An abstract type for a pointer to a IO method finder function:
24980 */
24981 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
24982
24983
24984 /****************************************************************************
24985 **************************** sqlite3_vfs methods ****************************
24986 **
24987 ** This division contains the implementation of methods on the
24988 ** sqlite3_vfs object.
24989 */
24990
24991 /*
24992 ** Initialize the contents of the unixFile structure pointed to by pId.
24993 */
24994 static int fillInUnixFile(
24995   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
24996   int h,                  /* Open file descriptor of file being opened */
24997   int dirfd,              /* Directory file descriptor */
24998   sqlite3_file *pId,      /* Write to the unixFile structure here */
24999   const char *zFilename,  /* Name of the file being opened */
25000   int noLock,             /* Omit locking if true */
25001   int isDelete            /* Delete on close if true */
25002 ){
25003   const sqlite3_io_methods *pLockingStyle;
25004   unixFile *pNew = (unixFile *)pId;
25005   int rc = SQLITE_OK;
25006
25007   assert( pNew->pLock==NULL );
25008   assert( pNew->pOpen==NULL );
25009
25010   /* Parameter isDelete is only used on vxworks. Express this explicitly 
25011   ** here to prevent compiler warnings about unused parameters.
25012   */
25013   UNUSED_PARAMETER(isDelete);
25014
25015   OSTRACE3("OPEN    %-3d %s\n", h, zFilename);    
25016   pNew->h = h;
25017   pNew->dirfd = dirfd;
25018   SET_THREADID(pNew);
25019   pNew->fileFlags = 0;
25020
25021 #if OS_VXWORKS
25022   pNew->pId = vxworksFindFileId(zFilename);
25023   if( pNew->pId==0 ){
25024     noLock = 1;
25025     rc = SQLITE_NOMEM;
25026   }
25027 #endif
25028
25029   if( noLock ){
25030     pLockingStyle = &nolockIoMethods;
25031   }else{
25032     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
25033 #if SQLITE_ENABLE_LOCKING_STYLE
25034     /* Cache zFilename in the locking context (AFP and dotlock override) for
25035     ** proxyLock activation is possible (remote proxy is based on db name)
25036     ** zFilename remains valid until file is closed, to support */
25037     pNew->lockingContext = (void*)zFilename;
25038 #endif
25039   }
25040
25041   if( pLockingStyle == &posixIoMethods ){
25042     unixEnterMutex();
25043     rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
25044     if( rc!=SQLITE_OK ){
25045       /* If an error occured in findLockInfo(), close the file descriptor
25046       ** immediately, before releasing the mutex. findLockInfo() may fail
25047       ** in two scenarios:
25048       **
25049       **   (a) A call to fstat() failed.
25050       **   (b) A malloc failed.
25051       **
25052       ** Scenario (b) may only occur if the process is holding no other
25053       ** file descriptors open on the same file. If there were other file
25054       ** descriptors on this file, then no malloc would be required by
25055       ** findLockInfo(). If this is the case, it is quite safe to close
25056       ** handle h - as it is guaranteed that no posix locks will be released
25057       ** by doing so.
25058       **
25059       ** If scenario (a) caused the error then things are not so safe. The
25060       ** implicit assumption here is that if fstat() fails, things are in
25061       ** such bad shape that dropping a lock or two doesn't matter much.
25062       */
25063       close(h);
25064       h = -1;
25065     }
25066     unixLeaveMutex();
25067   }
25068
25069 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25070   else if( pLockingStyle == &afpIoMethods ){
25071     /* AFP locking uses the file path so it needs to be included in
25072     ** the afpLockingContext.
25073     */
25074     afpLockingContext *pCtx;
25075     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
25076     if( pCtx==0 ){
25077       rc = SQLITE_NOMEM;
25078     }else{
25079       /* NB: zFilename exists and remains valid until the file is closed
25080       ** according to requirement F11141.  So we do not need to make a
25081       ** copy of the filename. */
25082       pCtx->dbPath = zFilename;
25083       srandomdev();
25084       unixEnterMutex();
25085       rc = findLockInfo(pNew, NULL, &pNew->pOpen);
25086       unixLeaveMutex();        
25087     }
25088   }
25089 #endif
25090
25091   else if( pLockingStyle == &dotlockIoMethods ){
25092     /* Dotfile locking uses the file path so it needs to be included in
25093     ** the dotlockLockingContext 
25094     */
25095     char *zLockFile;
25096     int nFilename;
25097     nFilename = (int)strlen(zFilename) + 6;
25098     zLockFile = (char *)sqlite3_malloc(nFilename);
25099     if( zLockFile==0 ){
25100       rc = SQLITE_NOMEM;
25101     }else{
25102       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
25103     }
25104     pNew->lockingContext = zLockFile;
25105   }
25106
25107 #if OS_VXWORKS
25108   else if( pLockingStyle == &semIoMethods ){
25109     /* Named semaphore locking uses the file path so it needs to be
25110     ** included in the semLockingContext
25111     */
25112     unixEnterMutex();
25113     rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
25114     if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
25115       char *zSemName = pNew->pOpen->aSemName;
25116       int n;
25117       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
25118                        pNew->pId->zCanonicalName);
25119       for( n=1; zSemName[n]; n++ )
25120         if( zSemName[n]=='/' ) zSemName[n] = '_';
25121       pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
25122       if( pNew->pOpen->pSem == SEM_FAILED ){
25123         rc = SQLITE_NOMEM;
25124         pNew->pOpen->aSemName[0] = '\0';
25125       }
25126     }
25127     unixLeaveMutex();
25128   }
25129 #endif
25130   
25131   pNew->lastErrno = 0;
25132 #if OS_VXWORKS
25133   if( rc!=SQLITE_OK ){
25134     unlink(zFilename);
25135     isDelete = 0;
25136   }
25137   pNew->isDelete = isDelete;
25138 #endif
25139   if( rc!=SQLITE_OK ){
25140     if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
25141     if( h>=0 ) close(h);
25142   }else{
25143     pNew->pMethod = pLockingStyle;
25144     OpenCounter(+1);
25145   }
25146   return rc;
25147 }
25148
25149 /*
25150 ** Open a file descriptor to the directory containing file zFilename.
25151 ** If successful, *pFd is set to the opened file descriptor and
25152 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
25153 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
25154 ** value.
25155 **
25156 ** If SQLITE_OK is returned, the caller is responsible for closing
25157 ** the file descriptor *pFd using close().
25158 */
25159 static int openDirectory(const char *zFilename, int *pFd){
25160   int ii;
25161   int fd = -1;
25162   char zDirname[MAX_PATHNAME+1];
25163
25164   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
25165   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
25166   if( ii>0 ){
25167     zDirname[ii] = '\0';
25168     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
25169     if( fd>=0 ){
25170 #ifdef FD_CLOEXEC
25171       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25172 #endif
25173       OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
25174     }
25175   }
25176   *pFd = fd;
25177   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
25178 }
25179
25180 /*
25181 ** Create a temporary file name in zBuf.  zBuf must be allocated
25182 ** by the calling process and must be big enough to hold at least
25183 ** pVfs->mxPathname bytes.
25184 */
25185 static int getTempname(int nBuf, char *zBuf){
25186   static const char *azDirs[] = {
25187      0,
25188      0,
25189      "/var/tmp",
25190      "/usr/tmp",
25191      "/tmp",
25192      ".",
25193   };
25194   static const unsigned char zChars[] =
25195     "abcdefghijklmnopqrstuvwxyz"
25196     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
25197     "0123456789";
25198   unsigned int i, j;
25199   struct stat buf;
25200   const char *zDir = ".";
25201
25202   /* It's odd to simulate an io-error here, but really this is just
25203   ** using the io-error infrastructure to test that SQLite handles this
25204   ** function failing. 
25205   */
25206   SimulateIOError( return SQLITE_IOERR );
25207
25208   azDirs[0] = sqlite3_temp_directory;
25209   if (NULL == azDirs[1]) {
25210     azDirs[1] = getenv("TMPDIR");
25211   }
25212   
25213   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
25214     if( azDirs[i]==0 ) continue;
25215     if( stat(azDirs[i], &buf) ) continue;
25216     if( !S_ISDIR(buf.st_mode) ) continue;
25217     if( access(azDirs[i], 07) ) continue;
25218     zDir = azDirs[i];
25219     break;
25220   }
25221
25222   /* Check that the output buffer is large enough for the temporary file 
25223   ** name. If it is not, return SQLITE_ERROR.
25224   */
25225   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
25226     return SQLITE_ERROR;
25227   }
25228
25229   do{
25230     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
25231     j = (int)strlen(zBuf);
25232     sqlite3_randomness(15, &zBuf[j]);
25233     for(i=0; i<15; i++, j++){
25234       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
25235     }
25236     zBuf[j] = 0;
25237   }while( access(zBuf,0)==0 );
25238   return SQLITE_OK;
25239 }
25240
25241 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25242 /*
25243 ** Routine to transform a unixFile into a proxy-locking unixFile.
25244 ** Implementation in the proxy-lock division, but used by unixOpen()
25245 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
25246 */
25247 static int proxyTransformUnixFile(unixFile*, const char*);
25248 #endif
25249
25250 /*
25251 ** Search for an unused file descriptor that was opened on the database 
25252 ** file (not a journal or master-journal file) identified by pathname
25253 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
25254 ** argument to this function.
25255 **
25256 ** Such a file descriptor may exist if a database connection was closed
25257 ** but the associated file descriptor could not be closed because some
25258 ** other file descriptor open on the same file is holding a file-lock.
25259 ** Refer to comments in the unixClose() function and the lengthy comment
25260 ** describing "Posix Advisory Locking" at the start of this file for 
25261 ** further details. Also, ticket #4018.
25262 **
25263 ** If a suitable file descriptor is found, then it is returned. If no
25264 ** such file descriptor is located, -1 is returned.
25265 */
25266 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
25267   UnixUnusedFd *pUnused = 0;
25268
25269   /* Do not search for an unused file descriptor on vxworks. Not because
25270   ** vxworks would not benefit from the change (it might, we're not sure),
25271   ** but because no way to test it is currently available. It is better 
25272   ** not to risk breaking vxworks support for the sake of such an obscure 
25273   ** feature.  */
25274 #if !OS_VXWORKS
25275   struct stat sStat;                   /* Results of stat() call */
25276
25277   /* A stat() call may fail for various reasons. If this happens, it is
25278   ** almost certain that an open() call on the same path will also fail.
25279   ** For this reason, if an error occurs in the stat() call here, it is
25280   ** ignored and -1 is returned. The caller will try to open a new file
25281   ** descriptor on the same path, fail, and return an error to SQLite.
25282   **
25283   ** Even if a subsequent open() call does succeed, the consequences of
25284   ** not searching for a resusable file descriptor are not dire.  */
25285   if( 0==stat(zPath, &sStat) ){
25286     struct unixOpenCnt *pOpen;
25287
25288     unixEnterMutex();
25289     pOpen = openList;
25290     while( pOpen && (pOpen->fileId.dev!=sStat.st_dev
25291                      || pOpen->fileId.ino!=sStat.st_ino) ){
25292        pOpen = pOpen->pNext;
25293     }
25294     if( pOpen ){
25295       UnixUnusedFd **pp;
25296       for(pp=&pOpen->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
25297       pUnused = *pp;
25298       if( pUnused ){
25299         *pp = pUnused->pNext;
25300       }
25301     }
25302     unixLeaveMutex();
25303   }
25304 #endif    /* if !OS_VXWORKS */
25305   return pUnused;
25306 }
25307
25308 /*
25309 ** Open the file zPath.
25310 ** 
25311 ** Previously, the SQLite OS layer used three functions in place of this
25312 ** one:
25313 **
25314 **     sqlite3OsOpenReadWrite();
25315 **     sqlite3OsOpenReadOnly();
25316 **     sqlite3OsOpenExclusive();
25317 **
25318 ** These calls correspond to the following combinations of flags:
25319 **
25320 **     ReadWrite() ->     (READWRITE | CREATE)
25321 **     ReadOnly()  ->     (READONLY) 
25322 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
25323 **
25324 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
25325 ** true, the file was configured to be automatically deleted when the
25326 ** file handle closed. To achieve the same effect using this new 
25327 ** interface, add the DELETEONCLOSE flag to those specified above for 
25328 ** OpenExclusive().
25329 */
25330 static int unixOpen(
25331   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
25332   const char *zPath,           /* Pathname of file to be opened */
25333   sqlite3_file *pFile,         /* The file descriptor to be filled in */
25334   int flags,                   /* Input flags to control the opening */
25335   int *pOutFlags               /* Output flags returned to SQLite core */
25336 ){
25337   unixFile *p = (unixFile *)pFile;
25338   int fd = -1;                   /* File descriptor returned by open() */
25339   int dirfd = -1;                /* Directory file descriptor */
25340   int openFlags = 0;             /* Flags to pass to open() */
25341   int eType = flags&0xFFFFFF00;  /* Type of file to open */
25342   int noLock;                    /* True to omit locking primitives */
25343   int rc = SQLITE_OK;            /* Function Return Code */
25344
25345   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
25346   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
25347   int isCreate     = (flags & SQLITE_OPEN_CREATE);
25348   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
25349   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
25350
25351   /* If creating a master or main-file journal, this function will open
25352   ** a file-descriptor on the directory too. The first time unixSync()
25353   ** is called the directory file descriptor will be fsync()ed and close()d.
25354   */
25355   int isOpenDirectory = (isCreate && 
25356       (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
25357   );
25358
25359   /* If argument zPath is a NULL pointer, this function is required to open
25360   ** a temporary file. Use this buffer to store the file name in.
25361   */
25362   char zTmpname[MAX_PATHNAME+1];
25363   const char *zName = zPath;
25364
25365   /* Check the following statements are true: 
25366   **
25367   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
25368   **   (b) if CREATE is set, then READWRITE must also be set, and
25369   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
25370   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
25371   */
25372   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
25373   assert(isCreate==0 || isReadWrite);
25374   assert(isExclusive==0 || isCreate);
25375   assert(isDelete==0 || isCreate);
25376
25377   /* The main DB, main journal, and master journal are never automatically
25378   ** deleted. Nor are they ever temporary files.  */
25379   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
25380   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
25381   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
25382
25383   /* Assert that the upper layer has set one of the "file-type" flags. */
25384   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
25385        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
25386        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
25387        || eType==SQLITE_OPEN_TRANSIENT_DB
25388   );
25389
25390   memset(p, 0, sizeof(unixFile));
25391
25392   if( eType==SQLITE_OPEN_MAIN_DB ){
25393     UnixUnusedFd *pUnused;
25394     pUnused = findReusableFd(zName, flags);
25395     if( pUnused ){
25396       fd = pUnused->fd;
25397     }else{
25398       pUnused = sqlite3_malloc(sizeof(*pUnused));
25399       if( !pUnused ){
25400         return SQLITE_NOMEM;
25401       }
25402     }
25403     p->pUnused = pUnused;
25404   }else if( !zName ){
25405     /* If zName is NULL, the upper layer is requesting a temp file. */
25406     assert(isDelete && !isOpenDirectory);
25407     rc = getTempname(MAX_PATHNAME+1, zTmpname);
25408     if( rc!=SQLITE_OK ){
25409       return rc;
25410     }
25411     zName = zTmpname;
25412   }
25413
25414   /* Determine the value of the flags parameter passed to POSIX function
25415   ** open(). These must be calculated even if open() is not called, as
25416   ** they may be stored as part of the file handle and used by the 
25417   ** 'conch file' locking functions later on.  */
25418   if( isReadonly )  openFlags |= O_RDONLY;
25419   if( isReadWrite ) openFlags |= O_RDWR;
25420   if( isCreate )    openFlags |= O_CREAT;
25421   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
25422   openFlags |= (O_LARGEFILE|O_BINARY);
25423
25424   if( fd<0 ){
25425     mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
25426     fd = open(zName, openFlags, openMode);
25427     OSTRACE4("OPENX   %-3d %s 0%o\n", fd, zName, openFlags);
25428     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
25429       /* Failed to open the file for read/write access. Try read-only. */
25430       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
25431       openFlags &= ~(O_RDWR|O_CREAT);
25432       flags |= SQLITE_OPEN_READONLY;
25433       openFlags |= O_RDONLY;
25434       fd = open(zName, openFlags, openMode);
25435     }
25436     if( fd<0 ){
25437       rc = SQLITE_CANTOPEN;
25438       goto open_finished;
25439     }
25440   }
25441   assert( fd>=0 );
25442   if( pOutFlags ){
25443     *pOutFlags = flags;
25444   }
25445
25446   if( p->pUnused ){
25447     p->pUnused->fd = fd;
25448     p->pUnused->flags = flags;
25449   }
25450
25451   if( isDelete ){
25452 #if OS_VXWORKS
25453     zPath = zName;
25454 #else
25455     unlink(zName);
25456 #endif
25457   }
25458 #if SQLITE_ENABLE_LOCKING_STYLE
25459   else{
25460     p->openFlags = openFlags;
25461   }
25462 #endif
25463
25464   if( isOpenDirectory ){
25465     rc = openDirectory(zPath, &dirfd);
25466     if( rc!=SQLITE_OK ){
25467       /* It is safe to close fd at this point, because it is guaranteed not
25468       ** to be open on a database file. If it were open on a database file,
25469       ** it would not be safe to close as this would release any locks held
25470       ** on the file by this process.  */
25471       assert( eType!=SQLITE_OPEN_MAIN_DB );
25472       close(fd);             /* silently leak if fail, already in error */
25473       goto open_finished;
25474     }
25475   }
25476
25477 #ifdef FD_CLOEXEC
25478   fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25479 #endif
25480
25481   noLock = eType!=SQLITE_OPEN_MAIN_DB;
25482
25483 #if SQLITE_PREFER_PROXY_LOCKING
25484   if( zPath!=NULL && !noLock && pVfs->xOpen ){
25485     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
25486     int useProxy = 0;
25487
25488     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
25489     ** never use proxy, NULL means use proxy for non-local files only.  */
25490     if( envforce!=NULL ){
25491       useProxy = atoi(envforce)>0;
25492     }else{
25493       struct statfs fsInfo;
25494       if( statfs(zPath, &fsInfo) == -1 ){
25495         /* In theory, the close(fd) call is sub-optimal. If the file opened
25496         ** with fd is a database file, and there are other connections open
25497         ** on that file that are currently holding advisory locks on it,
25498         ** then the call to close() will cancel those locks. In practice,
25499         ** we're assuming that statfs() doesn't fail very often. At least
25500         ** not while other file descriptors opened by the same process on
25501         ** the same file are working.  */
25502         p->lastErrno = errno;
25503         if( dirfd>=0 ){
25504           close(dirfd); /* silently leak if fail, in error */
25505         }
25506         close(fd); /* silently leak if fail, in error */
25507         rc = SQLITE_IOERR_ACCESS;
25508         goto open_finished;
25509       }
25510       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
25511     }
25512     if( useProxy ){
25513       rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
25514       if( rc==SQLITE_OK ){
25515         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
25516       }
25517       goto open_finished;
25518     }
25519   }
25520 #endif
25521   
25522   rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
25523 open_finished:
25524   if( rc!=SQLITE_OK ){
25525     sqlite3_free(p->pUnused);
25526   }
25527   return rc;
25528 }
25529
25530
25531 /*
25532 ** Delete the file at zPath. If the dirSync argument is true, fsync()
25533 ** the directory after deleting the file.
25534 */
25535 static int unixDelete(
25536   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
25537   const char *zPath,        /* Name of file to be deleted */
25538   int dirSync               /* If true, fsync() directory after deleting file */
25539 ){
25540   int rc = SQLITE_OK;
25541   UNUSED_PARAMETER(NotUsed);
25542   SimulateIOError(return SQLITE_IOERR_DELETE);
25543   unlink(zPath);
25544 #ifndef SQLITE_DISABLE_DIRSYNC
25545   if( dirSync ){
25546     int fd;
25547     rc = openDirectory(zPath, &fd);
25548     if( rc==SQLITE_OK ){
25549 #if OS_VXWORKS
25550       if( fsync(fd)==-1 )
25551 #else
25552       if( fsync(fd) )
25553 #endif
25554       {
25555         rc = SQLITE_IOERR_DIR_FSYNC;
25556       }
25557       if( close(fd)&&!rc ){
25558         rc = SQLITE_IOERR_DIR_CLOSE;
25559       }
25560     }
25561   }
25562 #endif
25563   return rc;
25564 }
25565
25566 /*
25567 ** Test the existance of or access permissions of file zPath. The
25568 ** test performed depends on the value of flags:
25569 **
25570 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
25571 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
25572 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
25573 **
25574 ** Otherwise return 0.
25575 */
25576 static int unixAccess(
25577   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
25578   const char *zPath,      /* Path of the file to examine */
25579   int flags,              /* What do we want to learn about the zPath file? */
25580   int *pResOut            /* Write result boolean here */
25581 ){
25582   int amode = 0;
25583   UNUSED_PARAMETER(NotUsed);
25584   SimulateIOError( return SQLITE_IOERR_ACCESS; );
25585   switch( flags ){
25586     case SQLITE_ACCESS_EXISTS:
25587       amode = F_OK;
25588       break;
25589     case SQLITE_ACCESS_READWRITE:
25590       amode = W_OK|R_OK;
25591       break;
25592     case SQLITE_ACCESS_READ:
25593       amode = R_OK;
25594       break;
25595
25596     default:
25597       assert(!"Invalid flags argument");
25598   }
25599   *pResOut = (access(zPath, amode)==0);
25600   return SQLITE_OK;
25601 }
25602
25603
25604 /*
25605 ** Turn a relative pathname into a full pathname. The relative path
25606 ** is stored as a nul-terminated string in the buffer pointed to by
25607 ** zPath. 
25608 **
25609 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
25610 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
25611 ** this buffer before returning.
25612 */
25613 static int unixFullPathname(
25614   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
25615   const char *zPath,            /* Possibly relative input path */
25616   int nOut,                     /* Size of output buffer in bytes */
25617   char *zOut                    /* Output buffer */
25618 ){
25619
25620   /* It's odd to simulate an io-error here, but really this is just
25621   ** using the io-error infrastructure to test that SQLite handles this
25622   ** function failing. This function could fail if, for example, the
25623   ** current working directory has been unlinked.
25624   */
25625   SimulateIOError( return SQLITE_ERROR );
25626
25627   assert( pVfs->mxPathname==MAX_PATHNAME );
25628   UNUSED_PARAMETER(pVfs);
25629
25630   zOut[nOut-1] = '\0';
25631   if( zPath[0]=='/' ){
25632     sqlite3_snprintf(nOut, zOut, "%s", zPath);
25633   }else{
25634     int nCwd;
25635     if( getcwd(zOut, nOut-1)==0 ){
25636       return SQLITE_CANTOPEN;
25637     }
25638     nCwd = (int)strlen(zOut);
25639     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
25640   }
25641   return SQLITE_OK;
25642 }
25643
25644
25645 #ifndef SQLITE_OMIT_LOAD_EXTENSION
25646 /*
25647 ** Interfaces for opening a shared library, finding entry points
25648 ** within the shared library, and closing the shared library.
25649 */
25650 #include <dlfcn.h>
25651 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
25652   UNUSED_PARAMETER(NotUsed);
25653   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
25654 }
25655
25656 /*
25657 ** SQLite calls this function immediately after a call to unixDlSym() or
25658 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
25659 ** message is available, it is written to zBufOut. If no error message
25660 ** is available, zBufOut is left unmodified and SQLite uses a default
25661 ** error message.
25662 */
25663 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
25664   char *zErr;
25665   UNUSED_PARAMETER(NotUsed);
25666   unixEnterMutex();
25667   zErr = dlerror();
25668   if( zErr ){
25669     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
25670   }
25671   unixLeaveMutex();
25672 }
25673 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
25674   /* 
25675   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
25676   ** cast into a pointer to a function.  And yet the library dlsym() routine
25677   ** returns a void* which is really a pointer to a function.  So how do we
25678   ** use dlsym() with -pedantic-errors?
25679   **
25680   ** Variable x below is defined to be a pointer to a function taking
25681   ** parameters void* and const char* and returning a pointer to a function.
25682   ** We initialize x by assigning it a pointer to the dlsym() function.
25683   ** (That assignment requires a cast.)  Then we call the function that
25684   ** x points to.  
25685   **
25686   ** This work-around is unlikely to work correctly on any system where
25687   ** you really cannot cast a function pointer into void*.  But then, on the
25688   ** other hand, dlsym() will not work on such a system either, so we have
25689   ** not really lost anything.
25690   */
25691   void (*(*x)(void*,const char*))(void);
25692   UNUSED_PARAMETER(NotUsed);
25693   x = (void(*(*)(void*,const char*))(void))dlsym;
25694   return (*x)(p, zSym);
25695 }
25696 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
25697   UNUSED_PARAMETER(NotUsed);
25698   dlclose(pHandle);
25699 }
25700 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
25701   #define unixDlOpen  0
25702   #define unixDlError 0
25703   #define unixDlSym   0
25704   #define unixDlClose 0
25705 #endif
25706
25707 /*
25708 ** Write nBuf bytes of random data to the supplied buffer zBuf.
25709 */
25710 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
25711   UNUSED_PARAMETER(NotUsed);
25712   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
25713
25714   /* We have to initialize zBuf to prevent valgrind from reporting
25715   ** errors.  The reports issued by valgrind are incorrect - we would
25716   ** prefer that the randomness be increased by making use of the
25717   ** uninitialized space in zBuf - but valgrind errors tend to worry
25718   ** some users.  Rather than argue, it seems easier just to initialize
25719   ** the whole array and silence valgrind, even if that means less randomness
25720   ** in the random seed.
25721   **
25722   ** When testing, initializing zBuf[] to zero is all we do.  That means
25723   ** that we always use the same random number sequence.  This makes the
25724   ** tests repeatable.
25725   */
25726   memset(zBuf, 0, nBuf);
25727 #if !defined(SQLITE_TEST)
25728   {
25729     int pid, fd;
25730     fd = open("/dev/urandom", O_RDONLY);
25731     if( fd<0 ){
25732       time_t t;
25733       time(&t);
25734       memcpy(zBuf, &t, sizeof(t));
25735       pid = getpid();
25736       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
25737       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
25738       nBuf = sizeof(t) + sizeof(pid);
25739     }else{
25740       nBuf = read(fd, zBuf, nBuf);
25741       close(fd);
25742     }
25743   }
25744 #endif
25745   return nBuf;
25746 }
25747
25748
25749 /*
25750 ** Sleep for a little while.  Return the amount of time slept.
25751 ** The argument is the number of microseconds we want to sleep.
25752 ** The return value is the number of microseconds of sleep actually
25753 ** requested from the underlying operating system, a number which
25754 ** might be greater than or equal to the argument, but not less
25755 ** than the argument.
25756 */
25757 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
25758 #if OS_VXWORKS
25759   struct timespec sp;
25760
25761   sp.tv_sec = microseconds / 1000000;
25762   sp.tv_nsec = (microseconds % 1000000) * 1000;
25763   nanosleep(&sp, NULL);
25764   UNUSED_PARAMETER(NotUsed);
25765   return microseconds;
25766 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
25767   usleep(microseconds);
25768   UNUSED_PARAMETER(NotUsed);
25769   return microseconds;
25770 #else
25771   int seconds = (microseconds+999999)/1000000;
25772   sleep(seconds);
25773   UNUSED_PARAMETER(NotUsed);
25774   return seconds*1000000;
25775 #endif
25776 }
25777
25778 /*
25779 ** The following variable, if set to a non-zero value, is interpreted as
25780 ** the number of seconds since 1970 and is used to set the result of
25781 ** sqlite3OsCurrentTime() during testing.
25782 */
25783 #ifdef SQLITE_TEST
25784 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
25785 #endif
25786
25787 /*
25788 ** Find the current time (in Universal Coordinated Time).  Write the
25789 ** current time and date as a Julian Day number into *prNow and
25790 ** return 0.  Return 1 if the time and date cannot be found.
25791 */
25792 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
25793 #if defined(SQLITE_OMIT_FLOATING_POINT)
25794   time_t t;
25795   time(&t);
25796   *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
25797 #elif defined(NO_GETTOD)
25798   time_t t;
25799   time(&t);
25800   *prNow = t/86400.0 + 2440587.5;
25801 #elif OS_VXWORKS
25802   struct timespec sNow;
25803   clock_gettime(CLOCK_REALTIME, &sNow);
25804   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
25805 #else
25806   struct timeval sNow;
25807 #ifdef _SVID_GETTOD
25808   gettimeofday(&sNow);
25809 #else
25810   gettimeofday(&sNow, 0);
25811 #endif
25812   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
25813 #endif
25814
25815 #ifdef SQLITE_TEST
25816   if( sqlite3_current_time ){
25817     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
25818   }
25819 #endif
25820   UNUSED_PARAMETER(NotUsed);
25821   return 0;
25822 }
25823
25824 /*
25825 ** We added the xGetLastError() method with the intention of providing
25826 ** better low-level error messages when operating-system problems come up
25827 ** during SQLite operation.  But so far, none of that has been implemented
25828 ** in the core.  So this routine is never called.  For now, it is merely
25829 ** a place-holder.
25830 */
25831 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
25832   UNUSED_PARAMETER(NotUsed);
25833   UNUSED_PARAMETER(NotUsed2);
25834   UNUSED_PARAMETER(NotUsed3);
25835   return 0;
25836 }
25837
25838 /*
25839 ************************ End of sqlite3_vfs methods ***************************
25840 ******************************************************************************/
25841
25842 /******************************************************************************
25843 ************************** Begin Proxy Locking ********************************
25844 **
25845 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
25846 ** other locking methods on secondary lock files.  Proxy locking is a
25847 ** meta-layer over top of the primitive locking implemented above.  For
25848 ** this reason, the division that implements of proxy locking is deferred
25849 ** until late in the file (here) after all of the other I/O methods have
25850 ** been defined - so that the primitive locking methods are available
25851 ** as services to help with the implementation of proxy locking.
25852 **
25853 ****
25854 **
25855 ** The default locking schemes in SQLite use byte-range locks on the
25856 ** database file to coordinate safe, concurrent access by multiple readers
25857 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
25858 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
25859 ** as POSIX read & write locks over fixed set of locations (via fsctl),
25860 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
25861 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
25862 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
25863 ** address in the shared range is taken for a SHARED lock, the entire
25864 ** shared range is taken for an EXCLUSIVE lock):
25865 **
25866 **      PENDING_BYTE        0x40000000                  
25867 **      RESERVED_BYTE       0x40000001
25868 **      SHARED_RANGE        0x40000002 -> 0x40000200
25869 **
25870 ** This works well on the local file system, but shows a nearly 100x
25871 ** slowdown in read performance on AFP because the AFP client disables
25872 ** the read cache when byte-range locks are present.  Enabling the read
25873 ** cache exposes a cache coherency problem that is present on all OS X
25874 ** supported network file systems.  NFS and AFP both observe the
25875 ** close-to-open semantics for ensuring cache coherency
25876 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
25877 ** address the requirements for concurrent database access by multiple
25878 ** readers and writers
25879 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
25880 **
25881 ** To address the performance and cache coherency issues, proxy file locking
25882 ** changes the way database access is controlled by limiting access to a
25883 ** single host at a time and moving file locks off of the database file
25884 ** and onto a proxy file on the local file system.  
25885 **
25886 **
25887 ** Using proxy locks
25888 ** -----------------
25889 **
25890 ** C APIs
25891 **
25892 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
25893 **                       <proxy_path> | ":auto:");
25894 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
25895 **
25896 **
25897 ** SQL pragmas
25898 **
25899 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
25900 **  PRAGMA [database.]lock_proxy_file
25901 **
25902 ** Specifying ":auto:" means that if there is a conch file with a matching
25903 ** host ID in it, the proxy path in the conch file will be used, otherwise
25904 ** a proxy path based on the user's temp dir
25905 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
25906 ** actual proxy file name is generated from the name and path of the
25907 ** database file.  For example:
25908 **
25909 **       For database path "/Users/me/foo.db" 
25910 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
25911 **
25912 ** Once a lock proxy is configured for a database connection, it can not
25913 ** be removed, however it may be switched to a different proxy path via
25914 ** the above APIs (assuming the conch file is not being held by another
25915 ** connection or process). 
25916 **
25917 **
25918 ** How proxy locking works
25919 ** -----------------------
25920 **
25921 ** Proxy file locking relies primarily on two new supporting files: 
25922 **
25923 **   *  conch file to limit access to the database file to a single host
25924 **      at a time
25925 **
25926 **   *  proxy file to act as a proxy for the advisory locks normally
25927 **      taken on the database
25928 **
25929 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
25930 ** by taking an sqlite-style shared lock on the conch file, reading the
25931 ** contents and comparing the host's unique host ID (see below) and lock
25932 ** proxy path against the values stored in the conch.  The conch file is
25933 ** stored in the same directory as the database file and the file name
25934 ** is patterned after the database file name as ".<databasename>-conch".
25935 ** If the conch file does not exist, or it's contents do not match the
25936 ** host ID and/or proxy path, then the lock is escalated to an exclusive
25937 ** lock and the conch file contents is updated with the host ID and proxy
25938 ** path and the lock is downgraded to a shared lock again.  If the conch
25939 ** is held by another process (with a shared lock), the exclusive lock
25940 ** will fail and SQLITE_BUSY is returned.
25941 **
25942 ** The proxy file - a single-byte file used for all advisory file locks
25943 ** normally taken on the database file.   This allows for safe sharing
25944 ** of the database file for multiple readers and writers on the same
25945 ** host (the conch ensures that they all use the same local lock file).
25946 **
25947 ** There is a third file - the host ID file - used as a persistent record
25948 ** of a unique identifier for the host, a 128-byte unique host id file
25949 ** in the path defined by the HOSTIDPATH macro (default value is
25950 ** /Library/Caches/.com.apple.sqliteConchHostId).
25951 **
25952 ** Requesting the lock proxy does not immediately take the conch, it is
25953 ** only taken when the first request to lock database file is made.  
25954 ** This matches the semantics of the traditional locking behavior, where
25955 ** opening a connection to a database file does not take a lock on it.
25956 ** The shared lock and an open file descriptor are maintained until 
25957 ** the connection to the database is closed. 
25958 **
25959 ** The proxy file and the lock file are never deleted so they only need
25960 ** to be created the first time they are used.
25961 **
25962 ** Configuration options
25963 ** ---------------------
25964 **
25965 **  SQLITE_PREFER_PROXY_LOCKING
25966 **
25967 **       Database files accessed on non-local file systems are
25968 **       automatically configured for proxy locking, lock files are
25969 **       named automatically using the same logic as
25970 **       PRAGMA lock_proxy_file=":auto:"
25971 **    
25972 **  SQLITE_PROXY_DEBUG
25973 **
25974 **       Enables the logging of error messages during host id file
25975 **       retrieval and creation
25976 **
25977 **  HOSTIDPATH
25978 **
25979 **       Overrides the default host ID file path location
25980 **
25981 **  LOCKPROXYDIR
25982 **
25983 **       Overrides the default directory used for lock proxy files that
25984 **       are named automatically via the ":auto:" setting
25985 **
25986 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
25987 **
25988 **       Permissions to use when creating a directory for storing the
25989 **       lock proxy files, only used when LOCKPROXYDIR is not set.
25990 **    
25991 **    
25992 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
25993 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
25994 ** force proxy locking to be used for every database file opened, and 0
25995 ** will force automatic proxy locking to be disabled for all database
25996 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
25997 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
25998 */
25999
26000 /*
26001 ** Proxy locking is only available on MacOSX 
26002 */
26003 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26004
26005 #ifdef SQLITE_TEST
26006 /* simulate multiple hosts by creating unique hostid file paths */
26007 SQLITE_API int sqlite3_hostid_num = 0;
26008 #endif
26009
26010 /*
26011 ** The proxyLockingContext has the path and file structures for the remote 
26012 ** and local proxy files in it
26013 */
26014 typedef struct proxyLockingContext proxyLockingContext;
26015 struct proxyLockingContext {
26016   unixFile *conchFile;         /* Open conch file */
26017   char *conchFilePath;         /* Name of the conch file */
26018   unixFile *lockProxy;         /* Open proxy lock file */
26019   char *lockProxyPath;         /* Name of the proxy lock file */
26020   char *dbPath;                /* Name of the open file */
26021   int conchHeld;               /* True if the conch is currently held */
26022   void *oldLockingContext;     /* Original lockingcontext to restore on close */
26023   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
26024 };
26025
26026 /* HOSTIDLEN and CONCHLEN both include space for the string 
26027 ** terminating nul 
26028 */
26029 #define HOSTIDLEN         128
26030 #define CONCHLEN          (MAXPATHLEN+HOSTIDLEN+1)
26031 #ifndef HOSTIDPATH
26032 # define HOSTIDPATH       "/Library/Caches/.com.apple.sqliteConchHostId"
26033 #endif
26034
26035 /* basically a copy of unixRandomness with different
26036 ** test behavior built in */
26037 static int proxyGenerateHostID(char *pHostID){
26038   int pid, fd, len;
26039   unsigned char *key = (unsigned char *)pHostID;
26040   
26041   memset(key, 0, HOSTIDLEN);
26042   len = 0;
26043   fd = open("/dev/urandom", O_RDONLY);
26044   if( fd>=0 ){
26045     len = read(fd, key, HOSTIDLEN);
26046     close(fd); /* silently leak the fd if it fails */
26047   }
26048   if( len < HOSTIDLEN ){
26049     time_t t;
26050     time(&t);
26051     memcpy(key, &t, sizeof(t));
26052     pid = getpid();
26053     memcpy(&key[sizeof(t)], &pid, sizeof(pid));
26054   }
26055   
26056 #ifdef MAKE_PRETTY_HOSTID
26057   {
26058     int i;
26059     /* filter the bytes into printable ascii characters and NUL terminate */
26060     key[(HOSTIDLEN-1)] = 0x00;
26061     for( i=0; i<(HOSTIDLEN-1); i++ ){
26062       unsigned char pa = key[i]&0x7F;
26063       if( pa<0x20 ){
26064         key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
26065       }else if( pa==0x7F ){
26066         key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
26067       }
26068     }
26069   }
26070 #endif
26071   return SQLITE_OK;
26072 }
26073
26074 /* writes the host id path to path, path should be an pre-allocated buffer
26075 ** with enough space for a path 
26076 */
26077 static void proxyGetHostIDPath(char *path, size_t len){
26078   strlcpy(path, HOSTIDPATH, len);
26079 #ifdef SQLITE_TEST
26080   if( sqlite3_hostid_num>0 ){
26081     char suffix[2] = "1";
26082     suffix[0] = suffix[0] + sqlite3_hostid_num;
26083     strlcat(path, suffix, len);
26084   }
26085 #endif
26086   OSTRACE3("GETHOSTIDPATH  %s pid=%d\n", path, getpid());
26087 }
26088
26089 /* get the host ID from a sqlite hostid file stored in the 
26090 ** user-specific tmp directory, create the ID if it's not there already 
26091 */
26092 static int proxyGetHostID(char *pHostID, int *pError){
26093   int fd;
26094   char path[MAXPATHLEN]; 
26095   size_t len;
26096   int rc=SQLITE_OK;
26097
26098   proxyGetHostIDPath(path, MAXPATHLEN);
26099   /* try to create the host ID file, if it already exists read the contents */
26100   fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
26101   if( fd<0 ){
26102     int err=errno;
26103                 
26104     if( err!=EEXIST ){
26105 #ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
26106       fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
26107               path, strerror(err));
26108 #endif
26109       return SQLITE_PERM;
26110     }
26111     /* couldn't create the file, read it instead */
26112     fd = open(path, O_RDONLY|O_EXCL);
26113     if( fd<0 ){
26114 #ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
26115       int err = errno;
26116       fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
26117               path, strerror(err));
26118 #endif
26119       return SQLITE_PERM;
26120     }
26121     len = pread(fd, pHostID, HOSTIDLEN, 0);
26122     if( len<0 ){
26123       *pError = errno;
26124       rc = SQLITE_IOERR_READ;
26125     }else if( len<HOSTIDLEN ){
26126       *pError = 0;
26127       rc = SQLITE_IOERR_SHORT_READ;
26128     }
26129     close(fd); /* silently leak the fd if it fails */
26130     OSTRACE3("GETHOSTID  read %s pid=%d\n", pHostID, getpid());
26131     return rc;
26132   }else{
26133     /* we're creating the host ID file (use a random string of bytes) */
26134     proxyGenerateHostID(pHostID);
26135     len = pwrite(fd, pHostID, HOSTIDLEN, 0);
26136     if( len<0 ){
26137       *pError = errno;
26138       rc = SQLITE_IOERR_WRITE;
26139     }else if( len<HOSTIDLEN ){
26140       *pError = 0;
26141       rc = SQLITE_IOERR_WRITE;
26142     }
26143     close(fd); /* silently leak the fd if it fails */
26144     OSTRACE3("GETHOSTID  wrote %s pid=%d\n", pHostID, getpid());
26145     return rc;
26146   }
26147 }
26148
26149 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
26150   int len;
26151   int dbLen;
26152   int i;
26153
26154 #ifdef LOCKPROXYDIR
26155   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
26156 #else
26157 # ifdef _CS_DARWIN_USER_TEMP_DIR
26158   {
26159     confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
26160     len = strlcat(lPath, "sqliteplocks", maxLen);    
26161     if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
26162       /* if mkdir fails, handle as lock file creation failure */
26163 #  ifdef SQLITE_DEBUG
26164       int err = errno;
26165       if( err!=EEXIST ){
26166         fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
26167                 SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
26168       }
26169 #  endif
26170     }else{
26171       OSTRACE3("GETLOCKPATH  mkdir %s pid=%d\n", lPath, getpid());
26172     }
26173     
26174   }
26175 # else
26176   len = strlcpy(lPath, "/tmp/", maxLen);
26177 # endif
26178 #endif
26179
26180   if( lPath[len-1]!='/' ){
26181     len = strlcat(lPath, "/", maxLen);
26182   }
26183   
26184   /* transform the db path to a unique cache name */
26185   dbLen = (int)strlen(dbPath);
26186   for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
26187     char c = dbPath[i];
26188     lPath[i+len] = (c=='/')?'_':c;
26189   }
26190   lPath[i+len]='\0';
26191   strlcat(lPath, ":auto:", maxLen);
26192   return SQLITE_OK;
26193 }
26194
26195 /*
26196 ** Create a new VFS file descriptor (stored in memory obtained from
26197 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
26198 **
26199 ** The caller is responsible not only for closing the file descriptor
26200 ** but also for freeing the memory associated with the file descriptor.
26201 */
26202 static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
26203   unixFile *pNew;
26204   int flags = SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
26205   int rc = SQLITE_OK;
26206   sqlite3_vfs dummyVfs;
26207
26208   pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
26209   if( !pNew ){
26210     return SQLITE_NOMEM;
26211   }
26212   memset(pNew, 0, sizeof(unixFile));
26213
26214   /* Call unixOpen() to open the proxy file. The flags passed to unixOpen()
26215   ** suggest that the file being opened is a "main database". This is
26216   ** necessary as other file types do not necessarily support locking. It
26217   ** is better to use unixOpen() instead of opening the file directly with
26218   ** open(), as unixOpen() sets up the various mechanisms required to
26219   ** make sure a call to close() does not cause the system to discard
26220   ** POSIX locks prematurely.
26221   **
26222   ** It is important that the xOpen member of the VFS object passed to 
26223   ** unixOpen() is NULL. This tells unixOpen() may try to open a proxy-file 
26224   ** for the proxy-file (creating a potential infinite loop).
26225   */
26226   dummyVfs.pAppData = (void*)&autolockIoFinder;
26227   dummyVfs.xOpen = 0;
26228   rc = unixOpen(&dummyVfs, path, (sqlite3_file *)pNew, flags, &flags);
26229   if( rc==SQLITE_OK && (flags&SQLITE_OPEN_READONLY) ){
26230     pNew->pMethod->xClose((sqlite3_file *)pNew);
26231     rc = SQLITE_CANTOPEN;
26232   }
26233
26234   if( rc!=SQLITE_OK ){
26235     sqlite3_free(pNew);
26236     pNew = 0;
26237   }
26238
26239   *ppFile = pNew;
26240   return rc;
26241 }
26242
26243 /* takes the conch by taking a shared lock and read the contents conch, if 
26244 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
26245 ** lockPath means that the lockPath in the conch file will be used if the 
26246 ** host IDs match, or a new lock path will be generated automatically 
26247 ** and written to the conch file.
26248 */
26249 static int proxyTakeConch(unixFile *pFile){
26250   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
26251   
26252   if( pCtx->conchHeld>0 ){
26253     return SQLITE_OK;
26254   }else{
26255     unixFile *conchFile = pCtx->conchFile;
26256     char testValue[CONCHLEN];
26257     char conchValue[CONCHLEN];
26258     char lockPath[MAXPATHLEN];
26259     char *tLockPath = NULL;
26260     int rc = SQLITE_OK;
26261     int readRc = SQLITE_OK;
26262     int syncPerms = 0;
26263
26264     OSTRACE4("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
26265              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
26266
26267     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
26268     if( rc==SQLITE_OK ){
26269       int pError = 0;
26270       memset(testValue, 0, CONCHLEN); /* conch is fixed size */
26271       rc = proxyGetHostID(testValue, &pError);
26272       if( (rc&0xff)==SQLITE_IOERR ){
26273         pFile->lastErrno = pError;
26274       }
26275       if( pCtx->lockProxyPath ){
26276         strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
26277       }
26278     }
26279     if( rc!=SQLITE_OK ){
26280       goto end_takeconch;
26281     }
26282     
26283     readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
26284     if( readRc!=SQLITE_IOERR_SHORT_READ ){
26285       if( readRc!=SQLITE_OK ){
26286         if( (rc&0xff)==SQLITE_IOERR ){
26287           pFile->lastErrno = conchFile->lastErrno;
26288         }
26289         rc = readRc;
26290         goto end_takeconch;
26291       }
26292       /* if the conch has data compare the contents */
26293       if( !pCtx->lockProxyPath ){
26294         /* for auto-named local lock file, just check the host ID and we'll
26295          ** use the local lock file path that's already in there */
26296         if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
26297           tLockPath = (char *)&conchValue[HOSTIDLEN];
26298           goto end_takeconch;
26299         }
26300       }else{
26301         /* we've got the conch if conchValue matches our path and host ID */
26302         if( !memcmp(testValue, conchValue, CONCHLEN) ){
26303           goto end_takeconch;
26304         }
26305       }
26306     }else{
26307       /* a short read means we're "creating" the conch (even though it could 
26308       ** have been user-intervention), if we acquire the exclusive lock,
26309       ** we'll try to match the current on-disk permissions of the database
26310       */
26311       syncPerms = 1;
26312     }
26313     
26314     /* either conch was emtpy or didn't match */
26315     if( !pCtx->lockProxyPath ){
26316       proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
26317       tLockPath = lockPath;
26318       strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
26319     }
26320     
26321     /* update conch with host and path (this will fail if other process
26322      ** has a shared lock already) */
26323     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
26324     if( rc==SQLITE_OK ){
26325       rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
26326       if( rc==SQLITE_OK && syncPerms ){
26327         struct stat buf;
26328         int err = fstat(pFile->h, &buf);
26329         if( err==0 ){
26330           /* try to match the database file permissions, ignore failure */
26331 #ifndef SQLITE_PROXY_DEBUG
26332           fchmod(conchFile->h, buf.st_mode);
26333 #else
26334           if( fchmod(conchFile->h, buf.st_mode)!=0 ){
26335             int code = errno;
26336             fprintf(stderr, "fchmod %o FAILED with %d %s\n",
26337                              buf.st_mode, code, strerror(code));
26338           } else {
26339             fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
26340           }
26341         }else{
26342           int code = errno;
26343           fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
26344                           err, code, strerror(code));
26345 #endif
26346         }
26347       }
26348     }
26349     conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
26350   
26351 end_takeconch:
26352     OSTRACE2("TRANSPROXY: CLOSE  %d\n", pFile->h);
26353     if( rc==SQLITE_OK && pFile->openFlags ){
26354       if( pFile->h>=0 ){
26355 #ifdef STRICT_CLOSE_ERROR
26356         if( close(pFile->h) ){
26357           pFile->lastErrno = errno;
26358           return SQLITE_IOERR_CLOSE;
26359         }
26360 #else
26361         close(pFile->h); /* silently leak fd if fail */
26362 #endif
26363       }
26364       pFile->h = -1;
26365       int fd = open(pCtx->dbPath, pFile->openFlags,
26366                     SQLITE_DEFAULT_FILE_PERMISSIONS);
26367       OSTRACE2("TRANSPROXY: OPEN  %d\n", fd);
26368       if( fd>=0 ){
26369         pFile->h = fd;
26370       }else{
26371         rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
26372                                during locking */
26373       }
26374     }
26375     if( rc==SQLITE_OK && !pCtx->lockProxy ){
26376       char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
26377       /* ACS: Need to make a copy of path sometimes */
26378       rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
26379     }
26380     if( rc==SQLITE_OK ){
26381       pCtx->conchHeld = 1;
26382
26383       if( tLockPath ){
26384         pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
26385         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
26386           ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
26387                      pCtx->lockProxyPath;
26388         }
26389       }
26390     } else {
26391       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
26392     }
26393     OSTRACE3("TAKECONCH  %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
26394     return rc;
26395   }
26396 }
26397
26398 /*
26399 ** If pFile holds a lock on a conch file, then release that lock.
26400 */
26401 static int proxyReleaseConch(unixFile *pFile){
26402   int rc;                     /* Subroutine return code */
26403   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
26404   unixFile *conchFile;        /* Name of the conch file */
26405
26406   pCtx = (proxyLockingContext *)pFile->lockingContext;
26407   conchFile = pCtx->conchFile;
26408   OSTRACE4("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
26409            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
26410            getpid());
26411   pCtx->conchHeld = 0;
26412   rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
26413   OSTRACE3("RELEASECONCH  %d %s\n", conchFile->h,
26414            (rc==SQLITE_OK ? "ok" : "failed"));
26415   return rc;
26416 }
26417
26418 /*
26419 ** Given the name of a database file, compute the name of its conch file.
26420 ** Store the conch filename in memory obtained from sqlite3_malloc().
26421 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
26422 ** or SQLITE_NOMEM if unable to obtain memory.
26423 **
26424 ** The caller is responsible for ensuring that the allocated memory
26425 ** space is eventually freed.
26426 **
26427 ** *pConchPath is set to NULL if a memory allocation error occurs.
26428 */
26429 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
26430   int i;                        /* Loop counter */
26431   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
26432   char *conchPath;              /* buffer in which to construct conch name */
26433
26434   /* Allocate space for the conch filename and initialize the name to
26435   ** the name of the original database file. */  
26436   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
26437   if( conchPath==0 ){
26438     return SQLITE_NOMEM;
26439   }
26440   memcpy(conchPath, dbPath, len+1);
26441   
26442   /* now insert a "." before the last / character */
26443   for( i=(len-1); i>=0; i-- ){
26444     if( conchPath[i]=='/' ){
26445       i++;
26446       break;
26447     }
26448   }
26449   conchPath[i]='.';
26450   while ( i<len ){
26451     conchPath[i+1]=dbPath[i];
26452     i++;
26453   }
26454
26455   /* append the "-conch" suffix to the file */
26456   memcpy(&conchPath[i+1], "-conch", 7);
26457   assert( (int)strlen(conchPath) == len+7 );
26458
26459   return SQLITE_OK;
26460 }
26461
26462
26463 /* Takes a fully configured proxy locking-style unix file and switches
26464 ** the local lock file path 
26465 */
26466 static int switchLockProxyPath(unixFile *pFile, const char *path) {
26467   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
26468   char *oldPath = pCtx->lockProxyPath;
26469   int rc = SQLITE_OK;
26470
26471   if( pFile->locktype!=NO_LOCK ){
26472     return SQLITE_BUSY;
26473   }  
26474
26475   /* nothing to do if the path is NULL, :auto: or matches the existing path */
26476   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
26477     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
26478     return SQLITE_OK;
26479   }else{
26480     unixFile *lockProxy = pCtx->lockProxy;
26481     pCtx->lockProxy=NULL;
26482     pCtx->conchHeld = 0;
26483     if( lockProxy!=NULL ){
26484       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
26485       if( rc ) return rc;
26486       sqlite3_free(lockProxy);
26487     }
26488     sqlite3_free(oldPath);
26489     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
26490   }
26491   
26492   return rc;
26493 }
26494
26495 /*
26496 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
26497 ** is a string buffer at least MAXPATHLEN+1 characters in size.
26498 **
26499 ** This routine find the filename associated with pFile and writes it
26500 ** int dbPath.
26501 */
26502 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
26503 #if defined(__APPLE__)
26504   if( pFile->pMethod == &afpIoMethods ){
26505     /* afp style keeps a reference to the db path in the filePath field 
26506     ** of the struct */
26507     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
26508     strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
26509   }else
26510 #endif
26511   if( pFile->pMethod == &dotlockIoMethods ){
26512     /* dot lock style uses the locking context to store the dot lock
26513     ** file path */
26514     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
26515     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
26516   }else{
26517     /* all other styles use the locking context to store the db file path */
26518     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
26519     strcpy(dbPath, (char *)pFile->lockingContext);
26520   }
26521   return SQLITE_OK;
26522 }
26523
26524 /*
26525 ** Takes an already filled in unix file and alters it so all file locking 
26526 ** will be performed on the local proxy lock file.  The following fields
26527 ** are preserved in the locking context so that they can be restored and 
26528 ** the unix structure properly cleaned up at close time:
26529 **  ->lockingContext
26530 **  ->pMethod
26531 */
26532 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
26533   proxyLockingContext *pCtx;
26534   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
26535   char *lockPath=NULL;
26536   int rc = SQLITE_OK;
26537   
26538   if( pFile->locktype!=NO_LOCK ){
26539     return SQLITE_BUSY;
26540   }
26541   proxyGetDbPathForUnixFile(pFile, dbPath);
26542   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
26543     lockPath=NULL;
26544   }else{
26545     lockPath=(char *)path;
26546   }
26547   
26548   OSTRACE4("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
26549            (lockPath ? lockPath : ":auto:"), getpid());
26550
26551   pCtx = sqlite3_malloc( sizeof(*pCtx) );
26552   if( pCtx==0 ){
26553     return SQLITE_NOMEM;
26554   }
26555   memset(pCtx, 0, sizeof(*pCtx));
26556
26557   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
26558   if( rc==SQLITE_OK ){
26559     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
26560   }  
26561   if( rc==SQLITE_OK && lockPath ){
26562     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
26563   }
26564
26565   if( rc==SQLITE_OK ){
26566     /* all memory is allocated, proxys are created and assigned, 
26567     ** switch the locking context and pMethod then return.
26568     */
26569     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
26570     pCtx->oldLockingContext = pFile->lockingContext;
26571     pFile->lockingContext = pCtx;
26572     pCtx->pOldMethod = pFile->pMethod;
26573     pFile->pMethod = &proxyIoMethods;
26574   }else{
26575     if( pCtx->conchFile ){ 
26576       rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
26577       if( rc ) return rc;
26578       sqlite3_free(pCtx->conchFile);
26579     }
26580     sqlite3_free(pCtx->conchFilePath); 
26581     sqlite3_free(pCtx);
26582   }
26583   OSTRACE3("TRANSPROXY  %d %s\n", pFile->h,
26584            (rc==SQLITE_OK ? "ok" : "failed"));
26585   return rc;
26586 }
26587
26588
26589 /*
26590 ** This routine handles sqlite3_file_control() calls that are specific
26591 ** to proxy locking.
26592 */
26593 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
26594   switch( op ){
26595     case SQLITE_GET_LOCKPROXYFILE: {
26596       unixFile *pFile = (unixFile*)id;
26597       if( pFile->pMethod == &proxyIoMethods ){
26598         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
26599         proxyTakeConch(pFile);
26600         if( pCtx->lockProxyPath ){
26601           *(const char **)pArg = pCtx->lockProxyPath;
26602         }else{
26603           *(const char **)pArg = ":auto: (not held)";
26604         }
26605       } else {
26606         *(const char **)pArg = NULL;
26607       }
26608       return SQLITE_OK;
26609     }
26610     case SQLITE_SET_LOCKPROXYFILE: {
26611       unixFile *pFile = (unixFile*)id;
26612       int rc = SQLITE_OK;
26613       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
26614       if( pArg==NULL || (const char *)pArg==0 ){
26615         if( isProxyStyle ){
26616           /* turn off proxy locking - not supported */
26617           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
26618         }else{
26619           /* turn off proxy locking - already off - NOOP */
26620           rc = SQLITE_OK;
26621         }
26622       }else{
26623         const char *proxyPath = (const char *)pArg;
26624         if( isProxyStyle ){
26625           proxyLockingContext *pCtx = 
26626             (proxyLockingContext*)pFile->lockingContext;
26627           if( !strcmp(pArg, ":auto:") 
26628            || (pCtx->lockProxyPath &&
26629                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
26630           ){
26631             rc = SQLITE_OK;
26632           }else{
26633             rc = switchLockProxyPath(pFile, proxyPath);
26634           }
26635         }else{
26636           /* turn on proxy file locking */
26637           rc = proxyTransformUnixFile(pFile, proxyPath);
26638         }
26639       }
26640       return rc;
26641     }
26642     default: {
26643       assert( 0 );  /* The call assures that only valid opcodes are sent */
26644     }
26645   }
26646   /*NOTREACHED*/
26647   return SQLITE_ERROR;
26648 }
26649
26650 /*
26651 ** Within this division (the proxying locking implementation) the procedures
26652 ** above this point are all utilities.  The lock-related methods of the
26653 ** proxy-locking sqlite3_io_method object follow.
26654 */
26655
26656
26657 /*
26658 ** This routine checks if there is a RESERVED lock held on the specified
26659 ** file by this or any other process. If such a lock is held, set *pResOut
26660 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26661 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26662 */
26663 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
26664   unixFile *pFile = (unixFile*)id;
26665   int rc = proxyTakeConch(pFile);
26666   if( rc==SQLITE_OK ){
26667     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26668     unixFile *proxy = pCtx->lockProxy;
26669     return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
26670   }
26671   return rc;
26672 }
26673
26674 /*
26675 ** Lock the file with the lock specified by parameter locktype - one
26676 ** of the following:
26677 **
26678 **     (1) SHARED_LOCK
26679 **     (2) RESERVED_LOCK
26680 **     (3) PENDING_LOCK
26681 **     (4) EXCLUSIVE_LOCK
26682 **
26683 ** Sometimes when requesting one lock state, additional lock states
26684 ** are inserted in between.  The locking might fail on one of the later
26685 ** transitions leaving the lock state different from what it started but
26686 ** still short of its goal.  The following chart shows the allowed
26687 ** transitions and the inserted intermediate states:
26688 **
26689 **    UNLOCKED -> SHARED
26690 **    SHARED -> RESERVED
26691 **    SHARED -> (PENDING) -> EXCLUSIVE
26692 **    RESERVED -> (PENDING) -> EXCLUSIVE
26693 **    PENDING -> EXCLUSIVE
26694 **
26695 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26696 ** routine to lower a locking level.
26697 */
26698 static int proxyLock(sqlite3_file *id, int locktype) {
26699   unixFile *pFile = (unixFile*)id;
26700   int rc = proxyTakeConch(pFile);
26701   if( rc==SQLITE_OK ){
26702     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26703     unixFile *proxy = pCtx->lockProxy;
26704     rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
26705     pFile->locktype = proxy->locktype;
26706   }
26707   return rc;
26708 }
26709
26710
26711 /*
26712 ** Lower the locking level on file descriptor pFile to locktype.  locktype
26713 ** must be either NO_LOCK or SHARED_LOCK.
26714 **
26715 ** If the locking level of the file descriptor is already at or below
26716 ** the requested locking level, this routine is a no-op.
26717 */
26718 static int proxyUnlock(sqlite3_file *id, int locktype) {
26719   unixFile *pFile = (unixFile*)id;
26720   int rc = proxyTakeConch(pFile);
26721   if( rc==SQLITE_OK ){
26722     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26723     unixFile *proxy = pCtx->lockProxy;
26724     rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
26725     pFile->locktype = proxy->locktype;
26726   }
26727   return rc;
26728 }
26729
26730 /*
26731 ** Close a file that uses proxy locks.
26732 */
26733 static int proxyClose(sqlite3_file *id) {
26734   if( id ){
26735     unixFile *pFile = (unixFile*)id;
26736     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26737     unixFile *lockProxy = pCtx->lockProxy;
26738     unixFile *conchFile = pCtx->conchFile;
26739     int rc = SQLITE_OK;
26740     
26741     if( lockProxy ){
26742       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
26743       if( rc ) return rc;
26744       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
26745       if( rc ) return rc;
26746       sqlite3_free(lockProxy);
26747       pCtx->lockProxy = 0;
26748     }
26749     if( conchFile ){
26750       if( pCtx->conchHeld ){
26751         rc = proxyReleaseConch(pFile);
26752         if( rc ) return rc;
26753       }
26754       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
26755       if( rc ) return rc;
26756       sqlite3_free(conchFile);
26757     }
26758     sqlite3_free(pCtx->lockProxyPath);
26759     sqlite3_free(pCtx->conchFilePath);
26760     sqlite3_free(pCtx->dbPath);
26761     /* restore the original locking context and pMethod then close it */
26762     pFile->lockingContext = pCtx->oldLockingContext;
26763     pFile->pMethod = pCtx->pOldMethod;
26764     sqlite3_free(pCtx);
26765     return pFile->pMethod->xClose(id);
26766   }
26767   return SQLITE_OK;
26768 }
26769
26770
26771
26772 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26773 /*
26774 ** The proxy locking style is intended for use with AFP filesystems.
26775 ** And since AFP is only supported on MacOSX, the proxy locking is also
26776 ** restricted to MacOSX.
26777 ** 
26778 **
26779 ******************* End of the proxy lock implementation **********************
26780 ******************************************************************************/
26781
26782 /*
26783 ** Initialize the operating system interface.
26784 **
26785 ** This routine registers all VFS implementations for unix-like operating
26786 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
26787 ** should be the only routines in this file that are visible from other
26788 ** files.
26789 **
26790 ** This routine is called once during SQLite initialization and by a
26791 ** single thread.  The memory allocation and mutex subsystems have not
26792 ** necessarily been initialized when this routine is called, and so they
26793 ** should not be used.
26794 */
26795 SQLITE_API int sqlite3_os_init(void){ 
26796   /* 
26797   ** The following macro defines an initializer for an sqlite3_vfs object.
26798   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
26799   ** to the "finder" function.  (pAppData is a pointer to a pointer because
26800   ** silly C90 rules prohibit a void* from being cast to a function pointer
26801   ** and so we have to go through the intermediate pointer to avoid problems
26802   ** when compiling with -pedantic-errors on GCC.)
26803   **
26804   ** The FINDER parameter to this macro is the name of the pointer to the
26805   ** finder-function.  The finder-function returns a pointer to the
26806   ** sqlite_io_methods object that implements the desired locking
26807   ** behaviors.  See the division above that contains the IOMETHODS
26808   ** macro for addition information on finder-functions.
26809   **
26810   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
26811   ** object.  But the "autolockIoFinder" available on MacOSX does a little
26812   ** more than that; it looks at the filesystem type that hosts the 
26813   ** database file and tries to choose an locking method appropriate for
26814   ** that filesystem time.
26815   */
26816   #define UNIXVFS(VFSNAME, FINDER) {                        \
26817     1,                    /* iVersion */                    \
26818     sizeof(unixFile),     /* szOsFile */                    \
26819     MAX_PATHNAME,         /* mxPathname */                  \
26820     0,                    /* pNext */                       \
26821     VFSNAME,              /* zName */                       \
26822     (void*)&FINDER,       /* pAppData */                    \
26823     unixOpen,             /* xOpen */                       \
26824     unixDelete,           /* xDelete */                     \
26825     unixAccess,           /* xAccess */                     \
26826     unixFullPathname,     /* xFullPathname */               \
26827     unixDlOpen,           /* xDlOpen */                     \
26828     unixDlError,          /* xDlError */                    \
26829     unixDlSym,            /* xDlSym */                      \
26830     unixDlClose,          /* xDlClose */                    \
26831     unixRandomness,       /* xRandomness */                 \
26832     unixSleep,            /* xSleep */                      \
26833     unixCurrentTime,      /* xCurrentTime */                \
26834     unixGetLastError      /* xGetLastError */               \
26835   }
26836
26837   /*
26838   ** All default VFSes for unix are contained in the following array.
26839   **
26840   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
26841   ** by the SQLite core when the VFS is registered.  So the following
26842   ** array cannot be const.
26843   */
26844   static sqlite3_vfs aVfs[] = {
26845 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
26846     UNIXVFS("unix",          autolockIoFinder ),
26847 #else
26848     UNIXVFS("unix",          posixIoFinder ),
26849 #endif
26850     UNIXVFS("unix-none",     nolockIoFinder ),
26851     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
26852     UNIXVFS("unix-wfl",      posixWflIoFinder ),
26853 #if OS_VXWORKS
26854     UNIXVFS("unix-namedsem", semIoFinder ),
26855 #endif
26856 #if SQLITE_ENABLE_LOCKING_STYLE
26857     UNIXVFS("unix-posix",    posixIoFinder ),
26858 #if !OS_VXWORKS
26859     UNIXVFS("unix-flock",    flockIoFinder ),
26860 #endif
26861 #endif
26862 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26863     UNIXVFS("unix-afp",      afpIoFinder ),
26864     UNIXVFS("unix-proxy",    proxyIoFinder ),
26865 #endif
26866   };
26867   unsigned int i;          /* Loop counter */
26868
26869   /* Register all VFSes defined in the aVfs[] array */
26870   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
26871     sqlite3_vfs_register(&aVfs[i], i==0);
26872   }
26873   return SQLITE_OK; 
26874 }
26875
26876 /*
26877 ** Shutdown the operating system interface.
26878 **
26879 ** Some operating systems might need to do some cleanup in this routine,
26880 ** to release dynamically allocated objects.  But not on unix.
26881 ** This routine is a no-op for unix.
26882 */
26883 SQLITE_API int sqlite3_os_end(void){ 
26884   return SQLITE_OK; 
26885 }
26886  
26887 #endif /* SQLITE_OS_UNIX */
26888
26889 /************** End of os_unix.c *********************************************/
26890 /************** Begin file os_win.c ******************************************/
26891 /*
26892 ** 2004 May 22
26893 **
26894 ** The author disclaims copyright to this source code.  In place of
26895 ** a legal notice, here is a blessing:
26896 **
26897 **    May you do good and not evil.
26898 **    May you find forgiveness for yourself and forgive others.
26899 **    May you share freely, never taking more than you give.
26900 **
26901 ******************************************************************************
26902 **
26903 ** This file contains code that is specific to windows.
26904 */
26905 #if SQLITE_OS_WIN               /* This file is used for windows only */
26906
26907
26908 /*
26909 ** A Note About Memory Allocation:
26910 **
26911 ** This driver uses malloc()/free() directly rather than going through
26912 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
26913 ** are designed for use on embedded systems where memory is scarce and
26914 ** malloc failures happen frequently.  Win32 does not typically run on
26915 ** embedded systems, and when it does the developers normally have bigger
26916 ** problems to worry about than running out of memory.  So there is not
26917 ** a compelling need to use the wrappers.
26918 **
26919 ** But there is a good reason to not use the wrappers.  If we use the
26920 ** wrappers then we will get simulated malloc() failures within this
26921 ** driver.  And that causes all kinds of problems for our tests.  We
26922 ** could enhance SQLite to deal with simulated malloc failures within
26923 ** the OS driver, but the code to deal with those failure would not
26924 ** be exercised on Linux (which does not need to malloc() in the driver)
26925 ** and so we would have difficulty writing coverage tests for that
26926 ** code.  Better to leave the code out, we think.
26927 **
26928 ** The point of this discussion is as follows:  When creating a new
26929 ** OS layer for an embedded system, if you use this file as an example,
26930 ** avoid the use of malloc()/free().  Those routines work ok on windows
26931 ** desktops but not so well in embedded systems.
26932 */
26933
26934 #include <winbase.h>
26935
26936 #ifdef __CYGWIN__
26937 # include <sys/cygwin.h>
26938 #endif
26939
26940 /*
26941 ** Macros used to determine whether or not to use threads.
26942 */
26943 #if defined(THREADSAFE) && THREADSAFE
26944 # define SQLITE_W32_THREADS 1
26945 #endif
26946
26947 /*
26948 ** Include code that is common to all os_*.c files
26949 */
26950 /************** Include os_common.h in the middle of os_win.c ****************/
26951 /************** Begin file os_common.h ***************************************/
26952 /*
26953 ** 2004 May 22
26954 **
26955 ** The author disclaims copyright to this source code.  In place of
26956 ** a legal notice, here is a blessing:
26957 **
26958 **    May you do good and not evil.
26959 **    May you find forgiveness for yourself and forgive others.
26960 **    May you share freely, never taking more than you give.
26961 **
26962 ******************************************************************************
26963 **
26964 ** This file contains macros and a little bit of code that is common to
26965 ** all of the platform-specific files (os_*.c) and is #included into those
26966 ** files.
26967 **
26968 ** This file should be #included by the os_*.c files only.  It is not a
26969 ** general purpose header file.
26970 */
26971 #ifndef _OS_COMMON_H_
26972 #define _OS_COMMON_H_
26973
26974 /*
26975 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
26976 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
26977 ** switch.  The following code should catch this problem at compile-time.
26978 */
26979 #ifdef MEMORY_DEBUG
26980 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
26981 #endif
26982
26983 #ifdef SQLITE_DEBUG
26984 SQLITE_PRIVATE int sqlite3OSTrace = 0;
26985 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
26986 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
26987 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
26988 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
26989 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
26990 #define OSTRACE6(X,Y,Z,A,B,C) \
26991     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
26992 #define OSTRACE7(X,Y,Z,A,B,C,D) \
26993     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
26994 #else
26995 #define OSTRACE1(X)
26996 #define OSTRACE2(X,Y)
26997 #define OSTRACE3(X,Y,Z)
26998 #define OSTRACE4(X,Y,Z,A)
26999 #define OSTRACE5(X,Y,Z,A,B)
27000 #define OSTRACE6(X,Y,Z,A,B,C)
27001 #define OSTRACE7(X,Y,Z,A,B,C,D)
27002 #endif
27003
27004 /*
27005 ** Macros for performance tracing.  Normally turned off.  Only works
27006 ** on i486 hardware.
27007 */
27008 #ifdef SQLITE_PERFORMANCE_TRACE
27009
27010 /* 
27011 ** hwtime.h contains inline assembler code for implementing 
27012 ** high-performance timing routines.
27013 */
27014 /************** Include hwtime.h in the middle of os_common.h ****************/
27015 /************** Begin file hwtime.h ******************************************/
27016 /*
27017 ** 2008 May 27
27018 **
27019 ** The author disclaims copyright to this source code.  In place of
27020 ** a legal notice, here is a blessing:
27021 **
27022 **    May you do good and not evil.
27023 **    May you find forgiveness for yourself and forgive others.
27024 **    May you share freely, never taking more than you give.
27025 **
27026 ******************************************************************************
27027 **
27028 ** This file contains inline asm code for retrieving "high-performance"
27029 ** counters for x86 class CPUs.
27030 */
27031 #ifndef _HWTIME_H_
27032 #define _HWTIME_H_
27033
27034 /*
27035 ** The following routine only works on pentium-class (or newer) processors.
27036 ** It uses the RDTSC opcode to read the cycle count value out of the
27037 ** processor and returns that value.  This can be used for high-res
27038 ** profiling.
27039 */
27040 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
27041       (defined(i386) || defined(__i386__) || defined(_M_IX86))
27042
27043   #if defined(__GNUC__)
27044
27045   __inline__ sqlite_uint64 sqlite3Hwtime(void){
27046      unsigned int lo, hi;
27047      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
27048      return (sqlite_uint64)hi << 32 | lo;
27049   }
27050
27051   #elif defined(_MSC_VER)
27052
27053   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
27054      __asm {
27055         rdtsc
27056         ret       ; return value at EDX:EAX
27057      }
27058   }
27059
27060   #endif
27061
27062 #elif (defined(__GNUC__) && defined(__x86_64__))
27063
27064   __inline__ sqlite_uint64 sqlite3Hwtime(void){
27065       unsigned long val;
27066       __asm__ __volatile__ ("rdtsc" : "=A" (val));
27067       return val;
27068   }
27069  
27070 #elif (defined(__GNUC__) && defined(__ppc__))
27071
27072   __inline__ sqlite_uint64 sqlite3Hwtime(void){
27073       unsigned long long retval;
27074       unsigned long junk;
27075       __asm__ __volatile__ ("\n\
27076           1:      mftbu   %1\n\
27077                   mftb    %L0\n\
27078                   mftbu   %0\n\
27079                   cmpw    %0,%1\n\
27080                   bne     1b"
27081                   : "=r" (retval), "=r" (junk));
27082       return retval;
27083   }
27084
27085 #else
27086
27087   #error Need implementation of sqlite3Hwtime() for your platform.
27088
27089   /*
27090   ** To compile without implementing sqlite3Hwtime() for your platform,
27091   ** you can remove the above #error and use the following
27092   ** stub function.  You will lose timing support for many
27093   ** of the debugging and testing utilities, but it should at
27094   ** least compile and run.
27095   */
27096 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
27097
27098 #endif
27099
27100 #endif /* !defined(_HWTIME_H_) */
27101
27102 /************** End of hwtime.h **********************************************/
27103 /************** Continuing where we left off in os_common.h ******************/
27104
27105 static sqlite_uint64 g_start;
27106 static sqlite_uint64 g_elapsed;
27107 #define TIMER_START       g_start=sqlite3Hwtime()
27108 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
27109 #define TIMER_ELAPSED     g_elapsed
27110 #else
27111 #define TIMER_START
27112 #define TIMER_END
27113 #define TIMER_ELAPSED     ((sqlite_uint64)0)
27114 #endif
27115
27116 /*
27117 ** If we compile with the SQLITE_TEST macro set, then the following block
27118 ** of code will give us the ability to simulate a disk I/O error.  This
27119 ** is used for testing the I/O recovery logic.
27120 */
27121 #ifdef SQLITE_TEST
27122 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
27123 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
27124 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
27125 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
27126 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
27127 SQLITE_API int sqlite3_diskfull_pending = 0;
27128 SQLITE_API int sqlite3_diskfull = 0;
27129 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
27130 #define SimulateIOError(CODE)  \
27131   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
27132        || sqlite3_io_error_pending-- == 1 )  \
27133               { local_ioerr(); CODE; }
27134 static void local_ioerr(){
27135   IOTRACE(("IOERR\n"));
27136   sqlite3_io_error_hit++;
27137   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
27138 }
27139 #define SimulateDiskfullError(CODE) \
27140    if( sqlite3_diskfull_pending ){ \
27141      if( sqlite3_diskfull_pending == 1 ){ \
27142        local_ioerr(); \
27143        sqlite3_diskfull = 1; \
27144        sqlite3_io_error_hit = 1; \
27145        CODE; \
27146      }else{ \
27147        sqlite3_diskfull_pending--; \
27148      } \
27149    }
27150 #else
27151 #define SimulateIOErrorBenign(X)
27152 #define SimulateIOError(A)
27153 #define SimulateDiskfullError(A)
27154 #endif
27155
27156 /*
27157 ** When testing, keep a count of the number of open files.
27158 */
27159 #ifdef SQLITE_TEST
27160 SQLITE_API int sqlite3_open_file_count = 0;
27161 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
27162 #else
27163 #define OpenCounter(X)
27164 #endif
27165
27166 #endif /* !defined(_OS_COMMON_H_) */
27167
27168 /************** End of os_common.h *******************************************/
27169 /************** Continuing where we left off in os_win.c *********************/
27170
27171 /*
27172 ** Some microsoft compilers lack this definition.
27173 */
27174 #ifndef INVALID_FILE_ATTRIBUTES
27175 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
27176 #endif
27177
27178 /*
27179 ** Determine if we are dealing with WindowsCE - which has a much
27180 ** reduced API.
27181 */
27182 #if SQLITE_OS_WINCE
27183 # define AreFileApisANSI() 1
27184 # define FormatMessageW(a,b,c,d,e,f,g) 0
27185 #endif
27186
27187 /*
27188 ** WinCE lacks native support for file locking so we have to fake it
27189 ** with some code of our own.
27190 */
27191 #if SQLITE_OS_WINCE
27192 typedef struct winceLock {
27193   int nReaders;       /* Number of reader locks obtained */
27194   BOOL bPending;      /* Indicates a pending lock has been obtained */
27195   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
27196   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
27197 } winceLock;
27198 #endif
27199
27200 /*
27201 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
27202 ** portability layer.
27203 */
27204 typedef struct winFile winFile;
27205 struct winFile {
27206   const sqlite3_io_methods *pMethod;/* Must be first */
27207   HANDLE h;               /* Handle for accessing the file */
27208   unsigned char locktype; /* Type of lock currently held on this file */
27209   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
27210   DWORD lastErrno;        /* The Windows errno from the last I/O error */
27211   DWORD sectorSize;       /* Sector size of the device file is on */
27212 #if SQLITE_OS_WINCE
27213   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
27214   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
27215   HANDLE hShared;         /* Shared memory segment used for locking */
27216   winceLock local;        /* Locks obtained by this instance of winFile */
27217   winceLock *shared;      /* Global shared lock memory for the file  */
27218 #endif
27219 };
27220
27221 /*
27222 ** Forward prototypes.
27223 */
27224 static int getSectorSize(
27225     sqlite3_vfs *pVfs,
27226     const char *zRelative     /* UTF-8 file name */
27227 );
27228
27229 /*
27230 ** The following variable is (normally) set once and never changes
27231 ** thereafter.  It records whether the operating system is Win95
27232 ** or WinNT.
27233 **
27234 ** 0:   Operating system unknown.
27235 ** 1:   Operating system is Win95.
27236 ** 2:   Operating system is WinNT.
27237 **
27238 ** In order to facilitate testing on a WinNT system, the test fixture
27239 ** can manually set this value to 1 to emulate Win98 behavior.
27240 */
27241 #ifdef SQLITE_TEST
27242 SQLITE_API int sqlite3_os_type = 0;
27243 #else
27244 static int sqlite3_os_type = 0;
27245 #endif
27246
27247 /*
27248 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
27249 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
27250 **
27251 ** Here is an interesting observation:  Win95, Win98, and WinME lack
27252 ** the LockFileEx() API.  But we can still statically link against that
27253 ** API as long as we don't call it when running Win95/98/ME.  A call to
27254 ** this routine is used to determine if the host is Win95/98/ME or
27255 ** WinNT/2K/XP so that we will know whether or not we can safely call
27256 ** the LockFileEx() API.
27257 */
27258 #if SQLITE_OS_WINCE
27259 # define isNT()  (1)
27260 #else
27261   static int isNT(void){
27262     if( sqlite3_os_type==0 ){
27263       OSVERSIONINFO sInfo;
27264       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
27265       GetVersionEx(&sInfo);
27266       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
27267     }
27268     return sqlite3_os_type==2;
27269   }
27270 #endif /* SQLITE_OS_WINCE */
27271
27272 /*
27273 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
27274 **
27275 ** Space to hold the returned string is obtained from malloc.
27276 */
27277 static WCHAR *utf8ToUnicode(const char *zFilename){
27278   int nChar;
27279   WCHAR *zWideFilename;
27280
27281   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
27282   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
27283   if( zWideFilename==0 ){
27284     return 0;
27285   }
27286   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
27287   if( nChar==0 ){
27288     free(zWideFilename);
27289     zWideFilename = 0;
27290   }
27291   return zWideFilename;
27292 }
27293
27294 /*
27295 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
27296 ** obtained from malloc().
27297 */
27298 static char *unicodeToUtf8(const WCHAR *zWideFilename){
27299   int nByte;
27300   char *zFilename;
27301
27302   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
27303   zFilename = malloc( nByte );
27304   if( zFilename==0 ){
27305     return 0;
27306   }
27307   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
27308                               0, 0);
27309   if( nByte == 0 ){
27310     free(zFilename);
27311     zFilename = 0;
27312   }
27313   return zFilename;
27314 }
27315
27316 /*
27317 ** Convert an ansi string to microsoft unicode, based on the
27318 ** current codepage settings for file apis.
27319 ** 
27320 ** Space to hold the returned string is obtained
27321 ** from malloc.
27322 */
27323 static WCHAR *mbcsToUnicode(const char *zFilename){
27324   int nByte;
27325   WCHAR *zMbcsFilename;
27326   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
27327
27328   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
27329   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
27330   if( zMbcsFilename==0 ){
27331     return 0;
27332   }
27333   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
27334   if( nByte==0 ){
27335     free(zMbcsFilename);
27336     zMbcsFilename = 0;
27337   }
27338   return zMbcsFilename;
27339 }
27340
27341 /*
27342 ** Convert microsoft unicode to multibyte character string, based on the
27343 ** user's Ansi codepage.
27344 **
27345 ** Space to hold the returned string is obtained from
27346 ** malloc().
27347 */
27348 static char *unicodeToMbcs(const WCHAR *zWideFilename){
27349   int nByte;
27350   char *zFilename;
27351   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
27352
27353   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
27354   zFilename = malloc( nByte );
27355   if( zFilename==0 ){
27356     return 0;
27357   }
27358   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
27359                               0, 0);
27360   if( nByte == 0 ){
27361     free(zFilename);
27362     zFilename = 0;
27363   }
27364   return zFilename;
27365 }
27366
27367 /*
27368 ** Convert multibyte character string to UTF-8.  Space to hold the
27369 ** returned string is obtained from malloc().
27370 */
27371 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
27372   char *zFilenameUtf8;
27373   WCHAR *zTmpWide;
27374
27375   zTmpWide = mbcsToUnicode(zFilename);
27376   if( zTmpWide==0 ){
27377     return 0;
27378   }
27379   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
27380   free(zTmpWide);
27381   return zFilenameUtf8;
27382 }
27383
27384 /*
27385 ** Convert UTF-8 to multibyte character string.  Space to hold the 
27386 ** returned string is obtained from malloc().
27387 */
27388 static char *utf8ToMbcs(const char *zFilename){
27389   char *zFilenameMbcs;
27390   WCHAR *zTmpWide;
27391
27392   zTmpWide = utf8ToUnicode(zFilename);
27393   if( zTmpWide==0 ){
27394     return 0;
27395   }
27396   zFilenameMbcs = unicodeToMbcs(zTmpWide);
27397   free(zTmpWide);
27398   return zFilenameMbcs;
27399 }
27400
27401 #if SQLITE_OS_WINCE
27402 /*************************************************************************
27403 ** This section contains code for WinCE only.
27404 */
27405 /*
27406 ** WindowsCE does not have a localtime() function.  So create a
27407 ** substitute.
27408 */
27409 struct tm *__cdecl localtime(const time_t *t)
27410 {
27411   static struct tm y;
27412   FILETIME uTm, lTm;
27413   SYSTEMTIME pTm;
27414   sqlite3_int64 t64;
27415   t64 = *t;
27416   t64 = (t64 + 11644473600)*10000000;
27417   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
27418   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
27419   FileTimeToLocalFileTime(&uTm,&lTm);
27420   FileTimeToSystemTime(&lTm,&pTm);
27421   y.tm_year = pTm.wYear - 1900;
27422   y.tm_mon = pTm.wMonth - 1;
27423   y.tm_wday = pTm.wDayOfWeek;
27424   y.tm_mday = pTm.wDay;
27425   y.tm_hour = pTm.wHour;
27426   y.tm_min = pTm.wMinute;
27427   y.tm_sec = pTm.wSecond;
27428   return &y;
27429 }
27430
27431 /* This will never be called, but defined to make the code compile */
27432 #define GetTempPathA(a,b)
27433
27434 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
27435 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
27436 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
27437
27438 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
27439
27440 /*
27441 ** Acquire a lock on the handle h
27442 */
27443 static void winceMutexAcquire(HANDLE h){
27444    DWORD dwErr;
27445    do {
27446      dwErr = WaitForSingleObject(h, INFINITE);
27447    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
27448 }
27449 /*
27450 ** Release a lock acquired by winceMutexAcquire()
27451 */
27452 #define winceMutexRelease(h) ReleaseMutex(h)
27453
27454 /*
27455 ** Create the mutex and shared memory used for locking in the file
27456 ** descriptor pFile
27457 */
27458 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
27459   WCHAR *zTok;
27460   WCHAR *zName = utf8ToUnicode(zFilename);
27461   BOOL bInit = TRUE;
27462
27463   /* Initialize the local lockdata */
27464   ZeroMemory(&pFile->local, sizeof(pFile->local));
27465
27466   /* Replace the backslashes from the filename and lowercase it
27467   ** to derive a mutex name. */
27468   zTok = CharLowerW(zName);
27469   for (;*zTok;zTok++){
27470     if (*zTok == '\\') *zTok = '_';
27471   }
27472
27473   /* Create/open the named mutex */
27474   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
27475   if (!pFile->hMutex){
27476     pFile->lastErrno = GetLastError();
27477     free(zName);
27478     return FALSE;
27479   }
27480
27481   /* Acquire the mutex before continuing */
27482   winceMutexAcquire(pFile->hMutex);
27483   
27484   /* Since the names of named mutexes, semaphores, file mappings etc are 
27485   ** case-sensitive, take advantage of that by uppercasing the mutex name
27486   ** and using that as the shared filemapping name.
27487   */
27488   CharUpperW(zName);
27489   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
27490                                        PAGE_READWRITE, 0, sizeof(winceLock),
27491                                        zName);  
27492
27493   /* Set a flag that indicates we're the first to create the memory so it 
27494   ** must be zero-initialized */
27495   if (GetLastError() == ERROR_ALREADY_EXISTS){
27496     bInit = FALSE;
27497   }
27498
27499   free(zName);
27500
27501   /* If we succeeded in making the shared memory handle, map it. */
27502   if (pFile->hShared){
27503     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
27504              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
27505     /* If mapping failed, close the shared memory handle and erase it */
27506     if (!pFile->shared){
27507       pFile->lastErrno = GetLastError();
27508       CloseHandle(pFile->hShared);
27509       pFile->hShared = NULL;
27510     }
27511   }
27512
27513   /* If shared memory could not be created, then close the mutex and fail */
27514   if (pFile->hShared == NULL){
27515     winceMutexRelease(pFile->hMutex);
27516     CloseHandle(pFile->hMutex);
27517     pFile->hMutex = NULL;
27518     return FALSE;
27519   }
27520   
27521   /* Initialize the shared memory if we're supposed to */
27522   if (bInit) {
27523     ZeroMemory(pFile->shared, sizeof(winceLock));
27524   }
27525
27526   winceMutexRelease(pFile->hMutex);
27527   return TRUE;
27528 }
27529
27530 /*
27531 ** Destroy the part of winFile that deals with wince locks
27532 */
27533 static void winceDestroyLock(winFile *pFile){
27534   if (pFile->hMutex){
27535     /* Acquire the mutex */
27536     winceMutexAcquire(pFile->hMutex);
27537
27538     /* The following blocks should probably assert in debug mode, but they
27539        are to cleanup in case any locks remained open */
27540     if (pFile->local.nReaders){
27541       pFile->shared->nReaders --;
27542     }
27543     if (pFile->local.bReserved){
27544       pFile->shared->bReserved = FALSE;
27545     }
27546     if (pFile->local.bPending){
27547       pFile->shared->bPending = FALSE;
27548     }
27549     if (pFile->local.bExclusive){
27550       pFile->shared->bExclusive = FALSE;
27551     }
27552
27553     /* De-reference and close our copy of the shared memory handle */
27554     UnmapViewOfFile(pFile->shared);
27555     CloseHandle(pFile->hShared);
27556
27557     /* Done with the mutex */
27558     winceMutexRelease(pFile->hMutex);    
27559     CloseHandle(pFile->hMutex);
27560     pFile->hMutex = NULL;
27561   }
27562 }
27563
27564 /* 
27565 ** An implementation of the LockFile() API of windows for wince
27566 */
27567 static BOOL winceLockFile(
27568   HANDLE *phFile,
27569   DWORD dwFileOffsetLow,
27570   DWORD dwFileOffsetHigh,
27571   DWORD nNumberOfBytesToLockLow,
27572   DWORD nNumberOfBytesToLockHigh
27573 ){
27574   winFile *pFile = HANDLE_TO_WINFILE(phFile);
27575   BOOL bReturn = FALSE;
27576
27577   UNUSED_PARAMETER(dwFileOffsetHigh);
27578   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
27579
27580   if (!pFile->hMutex) return TRUE;
27581   winceMutexAcquire(pFile->hMutex);
27582
27583   /* Wanting an exclusive lock? */
27584   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
27585        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
27586     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
27587        pFile->shared->bExclusive = TRUE;
27588        pFile->local.bExclusive = TRUE;
27589        bReturn = TRUE;
27590     }
27591   }
27592
27593   /* Want a read-only lock? */
27594   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
27595            nNumberOfBytesToLockLow == 1){
27596     if (pFile->shared->bExclusive == 0){
27597       pFile->local.nReaders ++;
27598       if (pFile->local.nReaders == 1){
27599         pFile->shared->nReaders ++;
27600       }
27601       bReturn = TRUE;
27602     }
27603   }
27604
27605   /* Want a pending lock? */
27606   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
27607     /* If no pending lock has been acquired, then acquire it */
27608     if (pFile->shared->bPending == 0) {
27609       pFile->shared->bPending = TRUE;
27610       pFile->local.bPending = TRUE;
27611       bReturn = TRUE;
27612     }
27613   }
27614
27615   /* Want a reserved lock? */
27616   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
27617     if (pFile->shared->bReserved == 0) {
27618       pFile->shared->bReserved = TRUE;
27619       pFile->local.bReserved = TRUE;
27620       bReturn = TRUE;
27621     }
27622   }
27623
27624   winceMutexRelease(pFile->hMutex);
27625   return bReturn;
27626 }
27627
27628 /*
27629 ** An implementation of the UnlockFile API of windows for wince
27630 */
27631 static BOOL winceUnlockFile(
27632   HANDLE *phFile,
27633   DWORD dwFileOffsetLow,
27634   DWORD dwFileOffsetHigh,
27635   DWORD nNumberOfBytesToUnlockLow,
27636   DWORD nNumberOfBytesToUnlockHigh
27637 ){
27638   winFile *pFile = HANDLE_TO_WINFILE(phFile);
27639   BOOL bReturn = FALSE;
27640
27641   UNUSED_PARAMETER(dwFileOffsetHigh);
27642   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
27643
27644   if (!pFile->hMutex) return TRUE;
27645   winceMutexAcquire(pFile->hMutex);
27646
27647   /* Releasing a reader lock or an exclusive lock */
27648   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
27649     /* Did we have an exclusive lock? */
27650     if (pFile->local.bExclusive){
27651       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
27652       pFile->local.bExclusive = FALSE;
27653       pFile->shared->bExclusive = FALSE;
27654       bReturn = TRUE;
27655     }
27656
27657     /* Did we just have a reader lock? */
27658     else if (pFile->local.nReaders){
27659       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
27660       pFile->local.nReaders --;
27661       if (pFile->local.nReaders == 0)
27662       {
27663         pFile->shared->nReaders --;
27664       }
27665       bReturn = TRUE;
27666     }
27667   }
27668
27669   /* Releasing a pending lock */
27670   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
27671     if (pFile->local.bPending){
27672       pFile->local.bPending = FALSE;
27673       pFile->shared->bPending = FALSE;
27674       bReturn = TRUE;
27675     }
27676   }
27677   /* Releasing a reserved lock */
27678   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
27679     if (pFile->local.bReserved) {
27680       pFile->local.bReserved = FALSE;
27681       pFile->shared->bReserved = FALSE;
27682       bReturn = TRUE;
27683     }
27684   }
27685
27686   winceMutexRelease(pFile->hMutex);
27687   return bReturn;
27688 }
27689
27690 /*
27691 ** An implementation of the LockFileEx() API of windows for wince
27692 */
27693 static BOOL winceLockFileEx(
27694   HANDLE *phFile,
27695   DWORD dwFlags,
27696   DWORD dwReserved,
27697   DWORD nNumberOfBytesToLockLow,
27698   DWORD nNumberOfBytesToLockHigh,
27699   LPOVERLAPPED lpOverlapped
27700 ){
27701   UNUSED_PARAMETER(dwReserved);
27702   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
27703
27704   /* If the caller wants a shared read lock, forward this call
27705   ** to winceLockFile */
27706   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
27707       dwFlags == 1 &&
27708       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
27709     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
27710   }
27711   return FALSE;
27712 }
27713 /*
27714 ** End of the special code for wince
27715 *****************************************************************************/
27716 #endif /* SQLITE_OS_WINCE */
27717
27718 /*****************************************************************************
27719 ** The next group of routines implement the I/O methods specified
27720 ** by the sqlite3_io_methods object.
27721 ******************************************************************************/
27722
27723 /*
27724 ** Close a file.
27725 **
27726 ** It is reported that an attempt to close a handle might sometimes
27727 ** fail.  This is a very unreasonable result, but windows is notorious
27728 ** for being unreasonable so I do not doubt that it might happen.  If
27729 ** the close fails, we pause for 100 milliseconds and try again.  As
27730 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
27731 ** giving up and returning an error.
27732 */
27733 #define MX_CLOSE_ATTEMPT 3
27734 static int winClose(sqlite3_file *id){
27735   int rc, cnt = 0;
27736   winFile *pFile = (winFile*)id;
27737
27738   assert( id!=0 );
27739   OSTRACE2("CLOSE %d\n", pFile->h);
27740   do{
27741     rc = CloseHandle(pFile->h);
27742   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
27743 #if SQLITE_OS_WINCE
27744 #define WINCE_DELETION_ATTEMPTS 3
27745   winceDestroyLock(pFile);
27746   if( pFile->zDeleteOnClose ){
27747     int cnt = 0;
27748     while(
27749            DeleteFileW(pFile->zDeleteOnClose)==0
27750         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
27751         && cnt++ < WINCE_DELETION_ATTEMPTS
27752     ){
27753        Sleep(100);  /* Wait a little before trying again */
27754     }
27755     free(pFile->zDeleteOnClose);
27756   }
27757 #endif
27758   OpenCounter(-1);
27759   return rc ? SQLITE_OK : SQLITE_IOERR;
27760 }
27761
27762 /*
27763 ** Some microsoft compilers lack this definition.
27764 */
27765 #ifndef INVALID_SET_FILE_POINTER
27766 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
27767 #endif
27768
27769 /*
27770 ** Read data from a file into a buffer.  Return SQLITE_OK if all
27771 ** bytes were read successfully and SQLITE_IOERR if anything goes
27772 ** wrong.
27773 */
27774 static int winRead(
27775   sqlite3_file *id,          /* File to read from */
27776   void *pBuf,                /* Write content into this buffer */
27777   int amt,                   /* Number of bytes to read */
27778   sqlite3_int64 offset       /* Begin reading at this offset */
27779 ){
27780   LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
27781   LONG lowerBits = (LONG)(offset & 0xffffffff);
27782   DWORD rc;
27783   winFile *pFile = (winFile*)id;
27784   DWORD error;
27785   DWORD got;
27786
27787   assert( id!=0 );
27788   SimulateIOError(return SQLITE_IOERR_READ);
27789   OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
27790   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
27791   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
27792     pFile->lastErrno = error;
27793     return SQLITE_FULL;
27794   }
27795   if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
27796     pFile->lastErrno = GetLastError();
27797     return SQLITE_IOERR_READ;
27798   }
27799   if( got==(DWORD)amt ){
27800     return SQLITE_OK;
27801   }else{
27802     /* Unread parts of the buffer must be zero-filled */
27803     memset(&((char*)pBuf)[got], 0, amt-got);
27804     return SQLITE_IOERR_SHORT_READ;
27805   }
27806 }
27807
27808 /*
27809 ** Write data from a buffer into a file.  Return SQLITE_OK on success
27810 ** or some other error code on failure.
27811 */
27812 static int winWrite(
27813   sqlite3_file *id,         /* File to write into */
27814   const void *pBuf,         /* The bytes to be written */
27815   int amt,                  /* Number of bytes to write */
27816   sqlite3_int64 offset      /* Offset into the file to begin writing at */
27817 ){
27818   LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
27819   LONG lowerBits = (LONG)(offset & 0xffffffff);
27820   DWORD rc;
27821   winFile *pFile = (winFile*)id;
27822   DWORD error;
27823   DWORD wrote = 0;
27824
27825   assert( id!=0 );
27826   SimulateIOError(return SQLITE_IOERR_WRITE);
27827   SimulateDiskfullError(return SQLITE_FULL);
27828   OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
27829   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
27830   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
27831     pFile->lastErrno = error;
27832     return SQLITE_FULL;
27833   }
27834   assert( amt>0 );
27835   while(
27836      amt>0
27837      && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
27838      && wrote>0
27839   ){
27840     amt -= wrote;
27841     pBuf = &((char*)pBuf)[wrote];
27842   }
27843   if( !rc || amt>(int)wrote ){
27844     pFile->lastErrno = GetLastError();
27845     return SQLITE_FULL;
27846   }
27847   return SQLITE_OK;
27848 }
27849
27850 /*
27851 ** Truncate an open file to a specified size
27852 */
27853 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
27854   LONG upperBits = (LONG)((nByte>>32) & 0x7fffffff);
27855   LONG lowerBits = (LONG)(nByte & 0xffffffff);
27856   DWORD rc;
27857   winFile *pFile = (winFile*)id;
27858   DWORD error;
27859
27860   assert( id!=0 );
27861   OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
27862   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
27863   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
27864   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
27865     pFile->lastErrno = error;
27866     return SQLITE_IOERR_TRUNCATE;
27867   }
27868   /* SetEndOfFile will fail if nByte is negative */
27869   if( !SetEndOfFile(pFile->h) ){
27870     pFile->lastErrno = GetLastError();
27871     return SQLITE_IOERR_TRUNCATE;
27872   }
27873   return SQLITE_OK;
27874 }
27875
27876 #ifdef SQLITE_TEST
27877 /*
27878 ** Count the number of fullsyncs and normal syncs.  This is used to test
27879 ** that syncs and fullsyncs are occuring at the right times.
27880 */
27881 SQLITE_API int sqlite3_sync_count = 0;
27882 SQLITE_API int sqlite3_fullsync_count = 0;
27883 #endif
27884
27885 /*
27886 ** Make sure all writes to a particular file are committed to disk.
27887 */
27888 static int winSync(sqlite3_file *id, int flags){
27889 #ifndef SQLITE_NO_SYNC
27890   winFile *pFile = (winFile*)id;
27891
27892   assert( id!=0 );
27893   OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
27894 #else
27895   UNUSED_PARAMETER(id);
27896 #endif
27897 #ifndef SQLITE_TEST
27898   UNUSED_PARAMETER(flags);
27899 #else
27900   if( flags & SQLITE_SYNC_FULL ){
27901     sqlite3_fullsync_count++;
27902   }
27903   sqlite3_sync_count++;
27904 #endif
27905   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
27906   ** no-op
27907   */
27908 #ifdef SQLITE_NO_SYNC
27909     return SQLITE_OK;
27910 #else
27911   if( FlushFileBuffers(pFile->h) ){
27912     return SQLITE_OK;
27913   }else{
27914     pFile->lastErrno = GetLastError();
27915     return SQLITE_IOERR;
27916   }
27917 #endif
27918 }
27919
27920 /*
27921 ** Determine the current size of a file in bytes
27922 */
27923 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
27924   DWORD upperBits;
27925   DWORD lowerBits;
27926   winFile *pFile = (winFile*)id;
27927   DWORD error;
27928
27929   assert( id!=0 );
27930   SimulateIOError(return SQLITE_IOERR_FSTAT);
27931   lowerBits = GetFileSize(pFile->h, &upperBits);
27932   if(   (lowerBits == INVALID_FILE_SIZE)
27933      && ((error = GetLastError()) != NO_ERROR) )
27934   {
27935     pFile->lastErrno = error;
27936     return SQLITE_IOERR_FSTAT;
27937   }
27938   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
27939   return SQLITE_OK;
27940 }
27941
27942 /*
27943 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
27944 */
27945 #ifndef LOCKFILE_FAIL_IMMEDIATELY
27946 # define LOCKFILE_FAIL_IMMEDIATELY 1
27947 #endif
27948
27949 /*
27950 ** Acquire a reader lock.
27951 ** Different API routines are called depending on whether or not this
27952 ** is Win95 or WinNT.
27953 */
27954 static int getReadLock(winFile *pFile){
27955   int res;
27956   if( isNT() ){
27957     OVERLAPPED ovlp;
27958     ovlp.Offset = SHARED_FIRST;
27959     ovlp.OffsetHigh = 0;
27960     ovlp.hEvent = 0;
27961     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
27962                      0, SHARED_SIZE, 0, &ovlp);
27963 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
27964 */
27965 #if SQLITE_OS_WINCE==0
27966   }else{
27967     int lk;
27968     sqlite3_randomness(sizeof(lk), &lk);
27969     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
27970     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
27971 #endif
27972   }
27973   if( res == 0 ){
27974     pFile->lastErrno = GetLastError();
27975   }
27976   return res;
27977 }
27978
27979 /*
27980 ** Undo a readlock
27981 */
27982 static int unlockReadLock(winFile *pFile){
27983   int res;
27984   if( isNT() ){
27985     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
27986 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
27987 */
27988 #if SQLITE_OS_WINCE==0
27989   }else{
27990     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
27991 #endif
27992   }
27993   if( res == 0 ){
27994     pFile->lastErrno = GetLastError();
27995   }
27996   return res;
27997 }
27998
27999 /*
28000 ** Lock the file with the lock specified by parameter locktype - one
28001 ** of the following:
28002 **
28003 **     (1) SHARED_LOCK
28004 **     (2) RESERVED_LOCK
28005 **     (3) PENDING_LOCK
28006 **     (4) EXCLUSIVE_LOCK
28007 **
28008 ** Sometimes when requesting one lock state, additional lock states
28009 ** are inserted in between.  The locking might fail on one of the later
28010 ** transitions leaving the lock state different from what it started but
28011 ** still short of its goal.  The following chart shows the allowed
28012 ** transitions and the inserted intermediate states:
28013 **
28014 **    UNLOCKED -> SHARED
28015 **    SHARED -> RESERVED
28016 **    SHARED -> (PENDING) -> EXCLUSIVE
28017 **    RESERVED -> (PENDING) -> EXCLUSIVE
28018 **    PENDING -> EXCLUSIVE
28019 **
28020 ** This routine will only increase a lock.  The winUnlock() routine
28021 ** erases all locks at once and returns us immediately to locking level 0.
28022 ** It is not possible to lower the locking level one step at a time.  You
28023 ** must go straight to locking level 0.
28024 */
28025 static int winLock(sqlite3_file *id, int locktype){
28026   int rc = SQLITE_OK;    /* Return code from subroutines */
28027   int res = 1;           /* Result of a windows lock call */
28028   int newLocktype;       /* Set pFile->locktype to this value before exiting */
28029   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
28030   winFile *pFile = (winFile*)id;
28031   DWORD error = NO_ERROR;
28032
28033   assert( id!=0 );
28034   OSTRACE5("LOCK %d %d was %d(%d)\n",
28035           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
28036
28037   /* If there is already a lock of this type or more restrictive on the
28038   ** OsFile, do nothing. Don't use the end_lock: exit path, as
28039   ** sqlite3OsEnterMutex() hasn't been called yet.
28040   */
28041   if( pFile->locktype>=locktype ){
28042     return SQLITE_OK;
28043   }
28044
28045   /* Make sure the locking sequence is correct
28046   */
28047   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
28048   assert( locktype!=PENDING_LOCK );
28049   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
28050
28051   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
28052   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
28053   ** the PENDING_LOCK byte is temporary.
28054   */
28055   newLocktype = pFile->locktype;
28056   if(   (pFile->locktype==NO_LOCK)
28057      || (   (locktype==EXCLUSIVE_LOCK)
28058          && (pFile->locktype==RESERVED_LOCK))
28059   ){
28060     int cnt = 3;
28061     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
28062       /* Try 3 times to get the pending lock.  The pending lock might be
28063       ** held by another reader process who will release it momentarily.
28064       */
28065       OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
28066       Sleep(1);
28067     }
28068     gotPendingLock = res;
28069     if( !res ){
28070       error = GetLastError();
28071     }
28072   }
28073
28074   /* Acquire a shared lock
28075   */
28076   if( locktype==SHARED_LOCK && res ){
28077     assert( pFile->locktype==NO_LOCK );
28078     res = getReadLock(pFile);
28079     if( res ){
28080       newLocktype = SHARED_LOCK;
28081     }else{
28082       error = GetLastError();
28083     }
28084   }
28085
28086   /* Acquire a RESERVED lock
28087   */
28088   if( locktype==RESERVED_LOCK && res ){
28089     assert( pFile->locktype==SHARED_LOCK );
28090     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28091     if( res ){
28092       newLocktype = RESERVED_LOCK;
28093     }else{
28094       error = GetLastError();
28095     }
28096   }
28097
28098   /* Acquire a PENDING lock
28099   */
28100   if( locktype==EXCLUSIVE_LOCK && res ){
28101     newLocktype = PENDING_LOCK;
28102     gotPendingLock = 0;
28103   }
28104
28105   /* Acquire an EXCLUSIVE lock
28106   */
28107   if( locktype==EXCLUSIVE_LOCK && res ){
28108     assert( pFile->locktype>=SHARED_LOCK );
28109     res = unlockReadLock(pFile);
28110     OSTRACE2("unreadlock = %d\n", res);
28111     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28112     if( res ){
28113       newLocktype = EXCLUSIVE_LOCK;
28114     }else{
28115       error = GetLastError();
28116       OSTRACE2("error-code = %d\n", error);
28117       getReadLock(pFile);
28118     }
28119   }
28120
28121   /* If we are holding a PENDING lock that ought to be released, then
28122   ** release it now.
28123   */
28124   if( gotPendingLock && locktype==SHARED_LOCK ){
28125     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
28126   }
28127
28128   /* Update the state of the lock has held in the file descriptor then
28129   ** return the appropriate result code.
28130   */
28131   if( res ){
28132     rc = SQLITE_OK;
28133   }else{
28134     OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
28135            locktype, newLocktype);
28136     pFile->lastErrno = error;
28137     rc = SQLITE_BUSY;
28138   }
28139   pFile->locktype = (u8)newLocktype;
28140   return rc;
28141 }
28142
28143 /*
28144 ** This routine checks if there is a RESERVED lock held on the specified
28145 ** file by this or any other process. If such a lock is held, return
28146 ** non-zero, otherwise zero.
28147 */
28148 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
28149   int rc;
28150   winFile *pFile = (winFile*)id;
28151
28152   assert( id!=0 );
28153   if( pFile->locktype>=RESERVED_LOCK ){
28154     rc = 1;
28155     OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
28156   }else{
28157     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28158     if( rc ){
28159       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28160     }
28161     rc = !rc;
28162     OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
28163   }
28164   *pResOut = rc;
28165   return SQLITE_OK;
28166 }
28167
28168 /*
28169 ** Lower the locking level on file descriptor id to locktype.  locktype
28170 ** must be either NO_LOCK or SHARED_LOCK.
28171 **
28172 ** If the locking level of the file descriptor is already at or below
28173 ** the requested locking level, this routine is a no-op.
28174 **
28175 ** It is not possible for this routine to fail if the second argument
28176 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
28177 ** might return SQLITE_IOERR;
28178 */
28179 static int winUnlock(sqlite3_file *id, int locktype){
28180   int type;
28181   winFile *pFile = (winFile*)id;
28182   int rc = SQLITE_OK;
28183   assert( pFile!=0 );
28184   assert( locktype<=SHARED_LOCK );
28185   OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
28186           pFile->locktype, pFile->sharedLockByte);
28187   type = pFile->locktype;
28188   if( type>=EXCLUSIVE_LOCK ){
28189     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28190     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
28191       /* This should never happen.  We should always be able to
28192       ** reacquire the read lock */
28193       rc = SQLITE_IOERR_UNLOCK;
28194     }
28195   }
28196   if( type>=RESERVED_LOCK ){
28197     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28198   }
28199   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
28200     unlockReadLock(pFile);
28201   }
28202   if( type>=PENDING_LOCK ){
28203     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
28204   }
28205   pFile->locktype = (u8)locktype;
28206   return rc;
28207 }
28208
28209 /*
28210 ** Control and query of the open file handle.
28211 */
28212 static int winFileControl(sqlite3_file *id, int op, void *pArg){
28213   switch( op ){
28214     case SQLITE_FCNTL_LOCKSTATE: {
28215       *(int*)pArg = ((winFile*)id)->locktype;
28216       return SQLITE_OK;
28217     }
28218     case SQLITE_LAST_ERRNO: {
28219       *(int*)pArg = (int)((winFile*)id)->lastErrno;
28220       return SQLITE_OK;
28221     }
28222   }
28223   return SQLITE_ERROR;
28224 }
28225
28226 /*
28227 ** Return the sector size in bytes of the underlying block device for
28228 ** the specified file. This is almost always 512 bytes, but may be
28229 ** larger for some devices.
28230 **
28231 ** SQLite code assumes this function cannot fail. It also assumes that
28232 ** if two files are created in the same file-system directory (i.e.
28233 ** a database and its journal file) that the sector size will be the
28234 ** same for both.
28235 */
28236 static int winSectorSize(sqlite3_file *id){
28237   assert( id!=0 );
28238   return (int)(((winFile*)id)->sectorSize);
28239 }
28240
28241 /*
28242 ** Return a vector of device characteristics.
28243 */
28244 static int winDeviceCharacteristics(sqlite3_file *id){
28245   UNUSED_PARAMETER(id);
28246   return 0;
28247 }
28248
28249 /*
28250 ** This vector defines all the methods that can operate on an
28251 ** sqlite3_file for win32.
28252 */
28253 static const sqlite3_io_methods winIoMethod = {
28254   1,                        /* iVersion */
28255   winClose,
28256   winRead,
28257   winWrite,
28258   winTruncate,
28259   winSync,
28260   winFileSize,
28261   winLock,
28262   winUnlock,
28263   winCheckReservedLock,
28264   winFileControl,
28265   winSectorSize,
28266   winDeviceCharacteristics
28267 };
28268
28269 /***************************************************************************
28270 ** Here ends the I/O methods that form the sqlite3_io_methods object.
28271 **
28272 ** The next block of code implements the VFS methods.
28273 ****************************************************************************/
28274
28275 /*
28276 ** Convert a UTF-8 filename into whatever form the underlying
28277 ** operating system wants filenames in.  Space to hold the result
28278 ** is obtained from malloc and must be freed by the calling
28279 ** function.
28280 */
28281 static void *convertUtf8Filename(const char *zFilename){
28282   void *zConverted = 0;
28283   if( isNT() ){
28284     zConverted = utf8ToUnicode(zFilename);
28285 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28286 */
28287 #if SQLITE_OS_WINCE==0
28288   }else{
28289     zConverted = utf8ToMbcs(zFilename);
28290 #endif
28291   }
28292   /* caller will handle out of memory */
28293   return zConverted;
28294 }
28295
28296 /*
28297 ** Create a temporary file name in zBuf.  zBuf must be big enough to
28298 ** hold at pVfs->mxPathname characters.
28299 */
28300 static int getTempname(int nBuf, char *zBuf){
28301   static char zChars[] =
28302     "abcdefghijklmnopqrstuvwxyz"
28303     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
28304     "0123456789";
28305   size_t i, j;
28306   char zTempPath[MAX_PATH+1];
28307   if( sqlite3_temp_directory ){
28308     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
28309   }else if( isNT() ){
28310     char *zMulti;
28311     WCHAR zWidePath[MAX_PATH];
28312     GetTempPathW(MAX_PATH-30, zWidePath);
28313     zMulti = unicodeToUtf8(zWidePath);
28314     if( zMulti ){
28315       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
28316       free(zMulti);
28317     }else{
28318       return SQLITE_NOMEM;
28319     }
28320 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28321 ** Since the ASCII version of these Windows API do not exist for WINCE,
28322 ** it's important to not reference them for WINCE builds.
28323 */
28324 #if SQLITE_OS_WINCE==0
28325   }else{
28326     char *zUtf8;
28327     char zMbcsPath[MAX_PATH];
28328     GetTempPathA(MAX_PATH-30, zMbcsPath);
28329     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
28330     if( zUtf8 ){
28331       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
28332       free(zUtf8);
28333     }else{
28334       return SQLITE_NOMEM;
28335     }
28336 #endif
28337   }
28338   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
28339   zTempPath[i] = 0;
28340   sqlite3_snprintf(nBuf-30, zBuf,
28341                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
28342   j = sqlite3Strlen30(zBuf);
28343   sqlite3_randomness(20, &zBuf[j]);
28344   for(i=0; i<20; i++, j++){
28345     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
28346   }
28347   zBuf[j] = 0;
28348   OSTRACE2("TEMP FILENAME: %s\n", zBuf);
28349   return SQLITE_OK; 
28350 }
28351
28352 /*
28353 ** The return value of getLastErrorMsg
28354 ** is zero if the error message fits in the buffer, or non-zero
28355 ** otherwise (if the message was truncated).
28356 */
28357 static int getLastErrorMsg(int nBuf, char *zBuf){
28358   /* FormatMessage returns 0 on failure.  Otherwise it
28359   ** returns the number of TCHARs written to the output
28360   ** buffer, excluding the terminating null char.
28361   */
28362   DWORD error = GetLastError();
28363   DWORD dwLen = 0;
28364   char *zOut = 0;
28365
28366   if( isNT() ){
28367     WCHAR *zTempWide = NULL;
28368     dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
28369                            NULL,
28370                            error,
28371                            0,
28372                            (LPWSTR) &zTempWide,
28373                            0,
28374                            0);
28375     if( dwLen > 0 ){
28376       /* allocate a buffer and convert to UTF8 */
28377       zOut = unicodeToUtf8(zTempWide);
28378       /* free the system buffer allocated by FormatMessage */
28379       LocalFree(zTempWide);
28380     }
28381 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28382 ** Since the ASCII version of these Windows API do not exist for WINCE,
28383 ** it's important to not reference them for WINCE builds.
28384 */
28385 #if SQLITE_OS_WINCE==0
28386   }else{
28387     char *zTemp = NULL;
28388     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
28389                            NULL,
28390                            error,
28391                            0,
28392                            (LPSTR) &zTemp,
28393                            0,
28394                            0);
28395     if( dwLen > 0 ){
28396       /* allocate a buffer and convert to UTF8 */
28397       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
28398       /* free the system buffer allocated by FormatMessage */
28399       LocalFree(zTemp);
28400     }
28401 #endif
28402   }
28403   if( 0 == dwLen ){
28404     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
28405   }else{
28406     /* copy a maximum of nBuf chars to output buffer */
28407     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
28408     /* free the UTF8 buffer */
28409     free(zOut);
28410   }
28411   return 0;
28412 }
28413
28414 /*
28415 ** Open a file.
28416 */
28417 static int winOpen(
28418   sqlite3_vfs *pVfs,        /* Not used */
28419   const char *zName,        /* Name of the file (UTF-8) */
28420   sqlite3_file *id,         /* Write the SQLite file handle here */
28421   int flags,                /* Open mode flags */
28422   int *pOutFlags            /* Status return flags */
28423 ){
28424   HANDLE h;
28425   DWORD dwDesiredAccess;
28426   DWORD dwShareMode;
28427   DWORD dwCreationDisposition;
28428   DWORD dwFlagsAndAttributes = 0;
28429 #if SQLITE_OS_WINCE
28430   int isTemp = 0;
28431 #endif
28432   winFile *pFile = (winFile*)id;
28433   void *zConverted;                 /* Filename in OS encoding */
28434   const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
28435   char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
28436
28437   assert( id!=0 );
28438   UNUSED_PARAMETER(pVfs);
28439
28440   /* If the second argument to this function is NULL, generate a 
28441   ** temporary file name to use 
28442   */
28443   if( !zUtf8Name ){
28444     int rc = getTempname(MAX_PATH+1, zTmpname);
28445     if( rc!=SQLITE_OK ){
28446       return rc;
28447     }
28448     zUtf8Name = zTmpname;
28449   }
28450
28451   /* Convert the filename to the system encoding. */
28452   zConverted = convertUtf8Filename(zUtf8Name);
28453   if( zConverted==0 ){
28454     return SQLITE_NOMEM;
28455   }
28456
28457   if( flags & SQLITE_OPEN_READWRITE ){
28458     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
28459   }else{
28460     dwDesiredAccess = GENERIC_READ;
28461   }
28462   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
28463   ** created. SQLite doesn't use it to indicate "exclusive access" 
28464   ** as it is usually understood.
28465   */
28466   assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
28467   if( flags & SQLITE_OPEN_EXCLUSIVE ){
28468     /* Creates a new file, only if it does not already exist. */
28469     /* If the file exists, it fails. */
28470     dwCreationDisposition = CREATE_NEW;
28471   }else if( flags & SQLITE_OPEN_CREATE ){
28472     /* Open existing file, or create if it doesn't exist */
28473     dwCreationDisposition = OPEN_ALWAYS;
28474   }else{
28475     /* Opens a file, only if it exists. */
28476     dwCreationDisposition = OPEN_EXISTING;
28477   }
28478   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
28479   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
28480 #if SQLITE_OS_WINCE
28481     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
28482     isTemp = 1;
28483 #else
28484     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
28485                                | FILE_ATTRIBUTE_HIDDEN
28486                                | FILE_FLAG_DELETE_ON_CLOSE;
28487 #endif
28488   }else{
28489     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
28490   }
28491   /* Reports from the internet are that performance is always
28492   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
28493 #if SQLITE_OS_WINCE
28494   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
28495 #endif
28496   if( isNT() ){
28497     h = CreateFileW((WCHAR*)zConverted,
28498        dwDesiredAccess,
28499        dwShareMode,
28500        NULL,
28501        dwCreationDisposition,
28502        dwFlagsAndAttributes,
28503        NULL
28504     );
28505 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28506 ** Since the ASCII version of these Windows API do not exist for WINCE,
28507 ** it's important to not reference them for WINCE builds.
28508 */
28509 #if SQLITE_OS_WINCE==0
28510   }else{
28511     h = CreateFileA((char*)zConverted,
28512        dwDesiredAccess,
28513        dwShareMode,
28514        NULL,
28515        dwCreationDisposition,
28516        dwFlagsAndAttributes,
28517        NULL
28518     );
28519 #endif
28520   }
28521   if( h==INVALID_HANDLE_VALUE ){
28522     free(zConverted);
28523     if( flags & SQLITE_OPEN_READWRITE ){
28524       return winOpen(pVfs, zName, id, 
28525              ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
28526     }else{
28527       return SQLITE_CANTOPEN;
28528     }
28529   }
28530   if( pOutFlags ){
28531     if( flags & SQLITE_OPEN_READWRITE ){
28532       *pOutFlags = SQLITE_OPEN_READWRITE;
28533     }else{
28534       *pOutFlags = SQLITE_OPEN_READONLY;
28535     }
28536   }
28537   memset(pFile, 0, sizeof(*pFile));
28538   pFile->pMethod = &winIoMethod;
28539   pFile->h = h;
28540   pFile->lastErrno = NO_ERROR;
28541   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
28542 #if SQLITE_OS_WINCE
28543   if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
28544                (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
28545        && !winceCreateLock(zName, pFile)
28546   ){
28547     CloseHandle(h);
28548     free(zConverted);
28549     return SQLITE_CANTOPEN;
28550   }
28551   if( isTemp ){
28552     pFile->zDeleteOnClose = zConverted;
28553   }else
28554 #endif
28555   {
28556     free(zConverted);
28557   }
28558   OpenCounter(+1);
28559   return SQLITE_OK;
28560 }
28561
28562 /*
28563 ** Delete the named file.
28564 **
28565 ** Note that windows does not allow a file to be deleted if some other
28566 ** process has it open.  Sometimes a virus scanner or indexing program
28567 ** will open a journal file shortly after it is created in order to do
28568 ** whatever it does.  While this other process is holding the
28569 ** file open, we will be unable to delete it.  To work around this
28570 ** problem, we delay 100 milliseconds and try to delete again.  Up
28571 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
28572 ** up and returning an error.
28573 */
28574 #define MX_DELETION_ATTEMPTS 5
28575 static int winDelete(
28576   sqlite3_vfs *pVfs,          /* Not used on win32 */
28577   const char *zFilename,      /* Name of file to delete */
28578   int syncDir                 /* Not used on win32 */
28579 ){
28580   int cnt = 0;
28581   DWORD rc;
28582   DWORD error = 0;
28583   void *zConverted = convertUtf8Filename(zFilename);
28584   UNUSED_PARAMETER(pVfs);
28585   UNUSED_PARAMETER(syncDir);
28586   if( zConverted==0 ){
28587     return SQLITE_NOMEM;
28588   }
28589   SimulateIOError(return SQLITE_IOERR_DELETE);
28590   if( isNT() ){
28591     do{
28592       DeleteFileW(zConverted);
28593     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
28594                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
28595            && (++cnt < MX_DELETION_ATTEMPTS)
28596            && (Sleep(100), 1) );
28597 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28598 ** Since the ASCII version of these Windows API do not exist for WINCE,
28599 ** it's important to not reference them for WINCE builds.
28600 */
28601 #if SQLITE_OS_WINCE==0
28602   }else{
28603     do{
28604       DeleteFileA(zConverted);
28605     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
28606                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
28607            && (++cnt < MX_DELETION_ATTEMPTS)
28608            && (Sleep(100), 1) );
28609 #endif
28610   }
28611   free(zConverted);
28612   OSTRACE2("DELETE \"%s\"\n", zFilename);
28613   return (   (rc == INVALID_FILE_ATTRIBUTES) 
28614           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
28615 }
28616
28617 /*
28618 ** Check the existance and status of a file.
28619 */
28620 static int winAccess(
28621   sqlite3_vfs *pVfs,         /* Not used on win32 */
28622   const char *zFilename,     /* Name of file to check */
28623   int flags,                 /* Type of test to make on this file */
28624   int *pResOut               /* OUT: Result */
28625 ){
28626   DWORD attr;
28627   int rc = 0;
28628   void *zConverted = convertUtf8Filename(zFilename);
28629   UNUSED_PARAMETER(pVfs);
28630   if( zConverted==0 ){
28631     return SQLITE_NOMEM;
28632   }
28633   if( isNT() ){
28634     attr = GetFileAttributesW((WCHAR*)zConverted);
28635 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28636 ** Since the ASCII version of these Windows API do not exist for WINCE,
28637 ** it's important to not reference them for WINCE builds.
28638 */
28639 #if SQLITE_OS_WINCE==0
28640   }else{
28641     attr = GetFileAttributesA((char*)zConverted);
28642 #endif
28643   }
28644   free(zConverted);
28645   switch( flags ){
28646     case SQLITE_ACCESS_READ:
28647     case SQLITE_ACCESS_EXISTS:
28648       rc = attr!=INVALID_FILE_ATTRIBUTES;
28649       break;
28650     case SQLITE_ACCESS_READWRITE:
28651       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
28652       break;
28653     default:
28654       assert(!"Invalid flags argument");
28655   }
28656   *pResOut = rc;
28657   return SQLITE_OK;
28658 }
28659
28660
28661 /*
28662 ** Turn a relative pathname into a full pathname.  Write the full
28663 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
28664 ** bytes in size.
28665 */
28666 static int winFullPathname(
28667   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
28668   const char *zRelative,        /* Possibly relative input path */
28669   int nFull,                    /* Size of output buffer in bytes */
28670   char *zFull                   /* Output buffer */
28671 ){
28672   
28673 #if defined(__CYGWIN__)
28674   UNUSED_PARAMETER(nFull);
28675   cygwin_conv_to_full_win32_path(zRelative, zFull);
28676   return SQLITE_OK;
28677 #endif
28678
28679 #if SQLITE_OS_WINCE
28680   UNUSED_PARAMETER(nFull);
28681   /* WinCE has no concept of a relative pathname, or so I am told. */
28682   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
28683   return SQLITE_OK;
28684 #endif
28685
28686 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
28687   int nByte;
28688   void *zConverted;
28689   char *zOut;
28690   UNUSED_PARAMETER(nFull);
28691   zConverted = convertUtf8Filename(zRelative);
28692   if( isNT() ){
28693     WCHAR *zTemp;
28694     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
28695     zTemp = malloc( nByte*sizeof(zTemp[0]) );
28696     if( zTemp==0 ){
28697       free(zConverted);
28698       return SQLITE_NOMEM;
28699     }
28700     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
28701     free(zConverted);
28702     zOut = unicodeToUtf8(zTemp);
28703     free(zTemp);
28704 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28705 ** Since the ASCII version of these Windows API do not exist for WINCE,
28706 ** it's important to not reference them for WINCE builds.
28707 */
28708 #if SQLITE_OS_WINCE==0
28709   }else{
28710     char *zTemp;
28711     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
28712     zTemp = malloc( nByte*sizeof(zTemp[0]) );
28713     if( zTemp==0 ){
28714       free(zConverted);
28715       return SQLITE_NOMEM;
28716     }
28717     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
28718     free(zConverted);
28719     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
28720     free(zTemp);
28721 #endif
28722   }
28723   if( zOut ){
28724     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
28725     free(zOut);
28726     return SQLITE_OK;
28727   }else{
28728     return SQLITE_NOMEM;
28729   }
28730 #endif
28731 }
28732
28733 /*
28734 ** Get the sector size of the device used to store
28735 ** file.
28736 */
28737 static int getSectorSize(
28738     sqlite3_vfs *pVfs,
28739     const char *zRelative     /* UTF-8 file name */
28740 ){
28741   DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
28742   /* GetDiskFreeSpace is not supported under WINCE */
28743 #if SQLITE_OS_WINCE
28744   UNUSED_PARAMETER(pVfs);
28745   UNUSED_PARAMETER(zRelative);
28746 #else
28747   char zFullpath[MAX_PATH+1];
28748   int rc;
28749   DWORD dwRet = 0;
28750   DWORD dwDummy;
28751
28752   /*
28753   ** We need to get the full path name of the file
28754   ** to get the drive letter to look up the sector
28755   ** size.
28756   */
28757   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
28758   if( rc == SQLITE_OK )
28759   {
28760     void *zConverted = convertUtf8Filename(zFullpath);
28761     if( zConverted ){
28762       if( isNT() ){
28763         /* trim path to just drive reference */
28764         WCHAR *p = zConverted;
28765         for(;*p;p++){
28766           if( *p == '\\' ){
28767             *p = '\0';
28768             break;
28769           }
28770         }
28771         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
28772                                   &dwDummy,
28773                                   &bytesPerSector,
28774                                   &dwDummy,
28775                                   &dwDummy);
28776       }else{
28777         /* trim path to just drive reference */
28778         char *p = (char *)zConverted;
28779         for(;*p;p++){
28780           if( *p == '\\' ){
28781             *p = '\0';
28782             break;
28783           }
28784         }
28785         dwRet = GetDiskFreeSpaceA((char*)zConverted,
28786                                   &dwDummy,
28787                                   &bytesPerSector,
28788                                   &dwDummy,
28789                                   &dwDummy);
28790       }
28791       free(zConverted);
28792     }
28793     if( !dwRet ){
28794       bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
28795     }
28796   }
28797 #endif
28798   return (int) bytesPerSector; 
28799 }
28800
28801 #ifndef SQLITE_OMIT_LOAD_EXTENSION
28802 /*
28803 ** Interfaces for opening a shared library, finding entry points
28804 ** within the shared library, and closing the shared library.
28805 */
28806 /*
28807 ** Interfaces for opening a shared library, finding entry points
28808 ** within the shared library, and closing the shared library.
28809 */
28810 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
28811   HANDLE h;
28812   void *zConverted = convertUtf8Filename(zFilename);
28813   UNUSED_PARAMETER(pVfs);
28814   if( zConverted==0 ){
28815     return 0;
28816   }
28817   if( isNT() ){
28818     h = LoadLibraryW((WCHAR*)zConverted);
28819 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28820 ** Since the ASCII version of these Windows API do not exist for WINCE,
28821 ** it's important to not reference them for WINCE builds.
28822 */
28823 #if SQLITE_OS_WINCE==0
28824   }else{
28825     h = LoadLibraryA((char*)zConverted);
28826 #endif
28827   }
28828   free(zConverted);
28829   return (void*)h;
28830 }
28831 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
28832   UNUSED_PARAMETER(pVfs);
28833   getLastErrorMsg(nBuf, zBufOut);
28834 }
28835 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
28836   UNUSED_PARAMETER(pVfs);
28837 #if SQLITE_OS_WINCE
28838   /* The GetProcAddressA() routine is only available on wince. */
28839   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
28840 #else
28841   /* All other windows platforms expect GetProcAddress() to take
28842   ** an Ansi string regardless of the _UNICODE setting */
28843   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
28844 #endif
28845 }
28846 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
28847   UNUSED_PARAMETER(pVfs);
28848   FreeLibrary((HANDLE)pHandle);
28849 }
28850 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
28851   #define winDlOpen  0
28852   #define winDlError 0
28853   #define winDlSym   0
28854   #define winDlClose 0
28855 #endif
28856
28857
28858 /*
28859 ** Write up to nBuf bytes of randomness into zBuf.
28860 */
28861 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
28862   int n = 0;
28863   UNUSED_PARAMETER(pVfs);
28864 #if defined(SQLITE_TEST)
28865   n = nBuf;
28866   memset(zBuf, 0, nBuf);
28867 #else
28868   if( sizeof(SYSTEMTIME)<=nBuf-n ){
28869     SYSTEMTIME x;
28870     GetSystemTime(&x);
28871     memcpy(&zBuf[n], &x, sizeof(x));
28872     n += sizeof(x);
28873   }
28874   if( sizeof(DWORD)<=nBuf-n ){
28875     DWORD pid = GetCurrentProcessId();
28876     memcpy(&zBuf[n], &pid, sizeof(pid));
28877     n += sizeof(pid);
28878   }
28879   if( sizeof(DWORD)<=nBuf-n ){
28880     DWORD cnt = GetTickCount();
28881     memcpy(&zBuf[n], &cnt, sizeof(cnt));
28882     n += sizeof(cnt);
28883   }
28884   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
28885     LARGE_INTEGER i;
28886     QueryPerformanceCounter(&i);
28887     memcpy(&zBuf[n], &i, sizeof(i));
28888     n += sizeof(i);
28889   }
28890 #endif
28891   return n;
28892 }
28893
28894
28895 /*
28896 ** Sleep for a little while.  Return the amount of time slept.
28897 */
28898 static int winSleep(sqlite3_vfs *pVfs, int microsec){
28899   Sleep((microsec+999)/1000);
28900   UNUSED_PARAMETER(pVfs);
28901   return ((microsec+999)/1000)*1000;
28902 }
28903
28904 /*
28905 ** The following variable, if set to a non-zero value, becomes the result
28906 ** returned from sqlite3OsCurrentTime().  This is used for testing.
28907 */
28908 #ifdef SQLITE_TEST
28909 SQLITE_API int sqlite3_current_time = 0;
28910 #endif
28911
28912 /*
28913 ** Find the current time (in Universal Coordinated Time).  Write the
28914 ** current time and date as a Julian Day number into *prNow and
28915 ** return 0.  Return 1 if the time and date cannot be found.
28916 */
28917 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
28918   FILETIME ft;
28919   /* FILETIME structure is a 64-bit value representing the number of 
28920      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
28921   */
28922   sqlite3_int64 timeW;   /* Whole days */
28923   sqlite3_int64 timeF;   /* Fractional Days */
28924
28925   /* Number of 100-nanosecond intervals in a single day */
28926   static const sqlite3_int64 ntuPerDay = 
28927       10000000*(sqlite3_int64)86400;
28928
28929   /* Number of 100-nanosecond intervals in half of a day */
28930   static const sqlite3_int64 ntuPerHalfDay = 
28931       10000000*(sqlite3_int64)43200;
28932
28933   /* 2^32 - to avoid use of LL and warnings in gcc */
28934   static const sqlite3_int64 max32BitValue = 
28935       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
28936
28937 #if SQLITE_OS_WINCE
28938   SYSTEMTIME time;
28939   GetSystemTime(&time);
28940   /* if SystemTimeToFileTime() fails, it returns zero. */
28941   if (!SystemTimeToFileTime(&time,&ft)){
28942     return 1;
28943   }
28944 #else
28945   GetSystemTimeAsFileTime( &ft );
28946 #endif
28947   UNUSED_PARAMETER(pVfs);
28948   timeW = (((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + (sqlite3_int64)ft.dwLowDateTime;
28949   timeF = timeW % ntuPerDay;          /* fractional days (100-nanoseconds) */
28950   timeW = timeW / ntuPerDay;          /* whole days */
28951   timeW = timeW + 2305813;            /* add whole days (from 2305813.5) */
28952   timeF = timeF + ntuPerHalfDay;      /* add half a day (from 2305813.5) */
28953   timeW = timeW + (timeF/ntuPerDay);  /* add whole day if half day made one */
28954   timeF = timeF % ntuPerDay;          /* compute new fractional days */
28955   *prNow = (double)timeW + ((double)timeF / (double)ntuPerDay);
28956 #ifdef SQLITE_TEST
28957   if( sqlite3_current_time ){
28958     *prNow = ((double)sqlite3_current_time + (double)43200) / (double)86400 + (double)2440587;
28959   }
28960 #endif
28961   return 0;
28962 }
28963
28964 /*
28965 ** The idea is that this function works like a combination of
28966 ** GetLastError() and FormatMessage() on windows (or errno and
28967 ** strerror_r() on unix). After an error is returned by an OS
28968 ** function, SQLite calls this function with zBuf pointing to
28969 ** a buffer of nBuf bytes. The OS layer should populate the
28970 ** buffer with a nul-terminated UTF-8 encoded error message
28971 ** describing the last IO error to have occurred within the calling
28972 ** thread.
28973 **
28974 ** If the error message is too large for the supplied buffer,
28975 ** it should be truncated. The return value of xGetLastError
28976 ** is zero if the error message fits in the buffer, or non-zero
28977 ** otherwise (if the message was truncated). If non-zero is returned,
28978 ** then it is not necessary to include the nul-terminator character
28979 ** in the output buffer.
28980 **
28981 ** Not supplying an error message will have no adverse effect
28982 ** on SQLite. It is fine to have an implementation that never
28983 ** returns an error message:
28984 **
28985 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
28986 **     assert(zBuf[0]=='\0');
28987 **     return 0;
28988 **   }
28989 **
28990 ** However if an error message is supplied, it will be incorporated
28991 ** by sqlite into the error message available to the user using
28992 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
28993 */
28994 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
28995   UNUSED_PARAMETER(pVfs);
28996   return getLastErrorMsg(nBuf, zBuf);
28997 }
28998
28999 /*
29000 ** Initialize and deinitialize the operating system interface.
29001 */
29002 SQLITE_API int sqlite3_os_init(void){
29003   static sqlite3_vfs winVfs = {
29004     1,                 /* iVersion */
29005     sizeof(winFile),   /* szOsFile */
29006     MAX_PATH,          /* mxPathname */
29007     0,                 /* pNext */
29008     "win32",           /* zName */
29009     0,                 /* pAppData */
29010  
29011     winOpen,           /* xOpen */
29012     winDelete,         /* xDelete */
29013     winAccess,         /* xAccess */
29014     winFullPathname,   /* xFullPathname */
29015     winDlOpen,         /* xDlOpen */
29016     winDlError,        /* xDlError */
29017     winDlSym,          /* xDlSym */
29018     winDlClose,        /* xDlClose */
29019     winRandomness,     /* xRandomness */
29020     winSleep,          /* xSleep */
29021     winCurrentTime,    /* xCurrentTime */
29022     winGetLastError    /* xGetLastError */
29023   };
29024
29025   sqlite3_vfs_register(&winVfs, 1);
29026   return SQLITE_OK; 
29027 }
29028 SQLITE_API int sqlite3_os_end(void){ 
29029   return SQLITE_OK;
29030 }
29031
29032 #endif /* SQLITE_OS_WIN */
29033
29034 /************** End of os_win.c **********************************************/
29035 /************** Begin file bitvec.c ******************************************/
29036 /*
29037 ** 2008 February 16
29038 **
29039 ** The author disclaims copyright to this source code.  In place of
29040 ** a legal notice, here is a blessing:
29041 **
29042 **    May you do good and not evil.
29043 **    May you find forgiveness for yourself and forgive others.
29044 **    May you share freely, never taking more than you give.
29045 **
29046 *************************************************************************
29047 ** This file implements an object that represents a fixed-length
29048 ** bitmap.  Bits are numbered starting with 1.
29049 **
29050 ** A bitmap is used to record which pages of a database file have been
29051 ** journalled during a transaction, or which pages have the "dont-write"
29052 ** property.  Usually only a few pages are meet either condition.
29053 ** So the bitmap is usually sparse and has low cardinality.
29054 ** But sometimes (for example when during a DROP of a large table) most
29055 ** or all of the pages in a database can get journalled.  In those cases, 
29056 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
29057 ** to handle both cases well.
29058 **
29059 ** The size of the bitmap is fixed when the object is created.
29060 **
29061 ** All bits are clear when the bitmap is created.  Individual bits
29062 ** may be set or cleared one at a time.
29063 **
29064 ** Test operations are about 100 times more common that set operations.
29065 ** Clear operations are exceedingly rare.  There are usually between
29066 ** 5 and 500 set operations per Bitvec object, though the number of sets can
29067 ** sometimes grow into tens of thousands or larger.  The size of the
29068 ** Bitvec object is the number of pages in the database file at the
29069 ** start of a transaction, and is thus usually less than a few thousand,
29070 ** but can be as large as 2 billion for a really big database.
29071 */
29072
29073 /* Size of the Bitvec structure in bytes. */
29074 #define BITVEC_SZ        (sizeof(void*)*128)  /* 512 on 32bit.  1024 on 64bit */
29075
29076 /* Round the union size down to the nearest pointer boundary, since that's how 
29077 ** it will be aligned within the Bitvec struct. */
29078 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
29079
29080 /* Type of the array "element" for the bitmap representation. 
29081 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
29082 ** Setting this to the "natural word" size of your CPU may improve
29083 ** performance. */
29084 #define BITVEC_TELEM     u8
29085 /* Size, in bits, of the bitmap element. */
29086 #define BITVEC_SZELEM    8
29087 /* Number of elements in a bitmap array. */
29088 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
29089 /* Number of bits in the bitmap array. */
29090 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
29091
29092 /* Number of u32 values in hash table. */
29093 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
29094 /* Maximum number of entries in hash table before 
29095 ** sub-dividing and re-hashing. */
29096 #define BITVEC_MXHASH    (BITVEC_NINT/2)
29097 /* Hashing function for the aHash representation.
29098 ** Empirical testing showed that the *37 multiplier 
29099 ** (an arbitrary prime)in the hash function provided 
29100 ** no fewer collisions than the no-op *1. */
29101 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
29102
29103 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
29104
29105
29106 /*
29107 ** A bitmap is an instance of the following structure.
29108 **
29109 ** This bitmap records the existance of zero or more bits
29110 ** with values between 1 and iSize, inclusive.
29111 **
29112 ** There are three possible representations of the bitmap.
29113 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
29114 ** bitmap.  The least significant bit is bit 1.
29115 **
29116 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
29117 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
29118 **
29119 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
29120 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
29121 ** handles up to iDivisor separate values of i.  apSub[0] holds
29122 ** values between 1 and iDivisor.  apSub[1] holds values between
29123 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
29124 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
29125 ** to hold deal with values between 1 and iDivisor.
29126 */
29127 struct Bitvec {
29128   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
29129   u32 nSet;       /* Number of bits that are set - only valid for aHash
29130                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
29131                   ** this would be 125. */
29132   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
29133                   /* Should >=0 for apSub element. */
29134                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
29135                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
29136   union {
29137     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
29138     u32 aHash[BITVEC_NINT];      /* Hash table representation */
29139     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
29140   } u;
29141 };
29142
29143 /*
29144 ** Create a new bitmap object able to handle bits between 0 and iSize,
29145 ** inclusive.  Return a pointer to the new object.  Return NULL if 
29146 ** malloc fails.
29147 */
29148 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
29149   Bitvec *p;
29150   assert( sizeof(*p)==BITVEC_SZ );
29151   p = sqlite3MallocZero( sizeof(*p) );
29152   if( p ){
29153     p->iSize = iSize;
29154   }
29155   return p;
29156 }
29157
29158 /*
29159 ** Check to see if the i-th bit is set.  Return true or false.
29160 ** If p is NULL (if the bitmap has not been created) or if
29161 ** i is out of range, then return false.
29162 */
29163 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
29164   if( p==0 ) return 0;
29165   if( i>p->iSize || i==0 ) return 0;
29166   i--;
29167   while( p->iDivisor ){
29168     u32 bin = i/p->iDivisor;
29169     i = i%p->iDivisor;
29170     p = p->u.apSub[bin];
29171     if (!p) {
29172       return 0;
29173     }
29174   }
29175   if( p->iSize<=BITVEC_NBIT ){
29176     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
29177   } else{
29178     u32 h = BITVEC_HASH(i++);
29179     while( p->u.aHash[h] ){
29180       if( p->u.aHash[h]==i ) return 1;
29181       h = (h+1) % BITVEC_NINT;
29182     }
29183     return 0;
29184   }
29185 }
29186
29187 /*
29188 ** Set the i-th bit.  Return 0 on success and an error code if
29189 ** anything goes wrong.
29190 **
29191 ** This routine might cause sub-bitmaps to be allocated.  Failing
29192 ** to get the memory needed to hold the sub-bitmap is the only
29193 ** that can go wrong with an insert, assuming p and i are valid.
29194 **
29195 ** The calling function must ensure that p is a valid Bitvec object
29196 ** and that the value for "i" is within range of the Bitvec object.
29197 ** Otherwise the behavior is undefined.
29198 */
29199 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
29200   u32 h;
29201   if( p==0 ) return SQLITE_OK;
29202   assert( i>0 );
29203   assert( i<=p->iSize );
29204   i--;
29205   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
29206     u32 bin = i/p->iDivisor;
29207     i = i%p->iDivisor;
29208     if( p->u.apSub[bin]==0 ){
29209       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
29210       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
29211     }
29212     p = p->u.apSub[bin];
29213   }
29214   if( p->iSize<=BITVEC_NBIT ){
29215     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
29216     return SQLITE_OK;
29217   }
29218   h = BITVEC_HASH(i++);
29219   /* if there wasn't a hash collision, and this doesn't */
29220   /* completely fill the hash, then just add it without */
29221   /* worring about sub-dividing and re-hashing. */
29222   if( !p->u.aHash[h] ){
29223     if (p->nSet<(BITVEC_NINT-1)) {
29224       goto bitvec_set_end;
29225     } else {
29226       goto bitvec_set_rehash;
29227     }
29228   }
29229   /* there was a collision, check to see if it's already */
29230   /* in hash, if not, try to find a spot for it */
29231   do {
29232     if( p->u.aHash[h]==i ) return SQLITE_OK;
29233     h++;
29234     if( h>=BITVEC_NINT ) h = 0;
29235   } while( p->u.aHash[h] );
29236   /* we didn't find it in the hash.  h points to the first */
29237   /* available free spot. check to see if this is going to */
29238   /* make our hash too "full".  */
29239 bitvec_set_rehash:
29240   if( p->nSet>=BITVEC_MXHASH ){
29241     unsigned int j;
29242     int rc;
29243     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
29244     if( aiValues==0 ){
29245       return SQLITE_NOMEM;
29246     }else{
29247       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
29248       memset(p->u.apSub, 0, sizeof(p->u.apSub));
29249       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
29250       rc = sqlite3BitvecSet(p, i);
29251       for(j=0; j<BITVEC_NINT; j++){
29252         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
29253       }
29254       sqlite3StackFree(0, aiValues);
29255       return rc;
29256     }
29257   }
29258 bitvec_set_end:
29259   p->nSet++;
29260   p->u.aHash[h] = i;
29261   return SQLITE_OK;
29262 }
29263
29264 /*
29265 ** Clear the i-th bit.
29266 **
29267 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
29268 ** that BitvecClear can use to rebuilt its hash table.
29269 */
29270 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
29271   if( p==0 ) return;
29272   assert( i>0 );
29273   i--;
29274   while( p->iDivisor ){
29275     u32 bin = i/p->iDivisor;
29276     i = i%p->iDivisor;
29277     p = p->u.apSub[bin];
29278     if (!p) {
29279       return;
29280     }
29281   }
29282   if( p->iSize<=BITVEC_NBIT ){
29283     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
29284   }else{
29285     unsigned int j;
29286     u32 *aiValues = pBuf;
29287     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
29288     memset(p->u.aHash, 0, sizeof(p->u.aHash));
29289     p->nSet = 0;
29290     for(j=0; j<BITVEC_NINT; j++){
29291       if( aiValues[j] && aiValues[j]!=(i+1) ){
29292         u32 h = BITVEC_HASH(aiValues[j]-1);
29293         p->nSet++;
29294         while( p->u.aHash[h] ){
29295           h++;
29296           if( h>=BITVEC_NINT ) h = 0;
29297         }
29298         p->u.aHash[h] = aiValues[j];
29299       }
29300     }
29301   }
29302 }
29303
29304 /*
29305 ** Destroy a bitmap object.  Reclaim all memory used.
29306 */
29307 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
29308   if( p==0 ) return;
29309   if( p->iDivisor ){
29310     unsigned int i;
29311     for(i=0; i<BITVEC_NPTR; i++){
29312       sqlite3BitvecDestroy(p->u.apSub[i]);
29313     }
29314   }
29315   sqlite3_free(p);
29316 }
29317
29318 /*
29319 ** Return the value of the iSize parameter specified when Bitvec *p
29320 ** was created.
29321 */
29322 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
29323   return p->iSize;
29324 }
29325
29326 #ifndef SQLITE_OMIT_BUILTIN_TEST
29327 /*
29328 ** Let V[] be an array of unsigned characters sufficient to hold
29329 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
29330 ** Then the following macros can be used to set, clear, or test
29331 ** individual bits within V.
29332 */
29333 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
29334 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
29335 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
29336
29337 /*
29338 ** This routine runs an extensive test of the Bitvec code.
29339 **
29340 ** The input is an array of integers that acts as a program
29341 ** to test the Bitvec.  The integers are opcodes followed
29342 ** by 0, 1, or 3 operands, depending on the opcode.  Another
29343 ** opcode follows immediately after the last operand.
29344 **
29345 ** There are 6 opcodes numbered from 0 through 5.  0 is the
29346 ** "halt" opcode and causes the test to end.
29347 **
29348 **    0          Halt and return the number of errors
29349 **    1 N S X    Set N bits beginning with S and incrementing by X
29350 **    2 N S X    Clear N bits beginning with S and incrementing by X
29351 **    3 N        Set N randomly chosen bits
29352 **    4 N        Clear N randomly chosen bits
29353 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
29354 **
29355 ** The opcodes 1 through 4 perform set and clear operations are performed
29356 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
29357 ** Opcode 5 works on the linear array only, not on the Bitvec.
29358 ** Opcode 5 is used to deliberately induce a fault in order to
29359 ** confirm that error detection works.
29360 **
29361 ** At the conclusion of the test the linear array is compared
29362 ** against the Bitvec object.  If there are any differences,
29363 ** an error is returned.  If they are the same, zero is returned.
29364 **
29365 ** If a memory allocation error occurs, return -1.
29366 */
29367 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
29368   Bitvec *pBitvec = 0;
29369   unsigned char *pV = 0;
29370   int rc = -1;
29371   int i, nx, pc, op;
29372   void *pTmpSpace;
29373
29374   /* Allocate the Bitvec to be tested and a linear array of
29375   ** bits to act as the reference */
29376   pBitvec = sqlite3BitvecCreate( sz );
29377   pV = sqlite3_malloc( (sz+7)/8 + 1 );
29378   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
29379   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
29380   memset(pV, 0, (sz+7)/8 + 1);
29381
29382   /* NULL pBitvec tests */
29383   sqlite3BitvecSet(0, 1);
29384   sqlite3BitvecClear(0, 1, pTmpSpace);
29385
29386   /* Run the program */
29387   pc = 0;
29388   while( (op = aOp[pc])!=0 ){
29389     switch( op ){
29390       case 1:
29391       case 2:
29392       case 5: {
29393         nx = 4;
29394         i = aOp[pc+2] - 1;
29395         aOp[pc+2] += aOp[pc+3];
29396         break;
29397       }
29398       case 3:
29399       case 4: 
29400       default: {
29401         nx = 2;
29402         sqlite3_randomness(sizeof(i), &i);
29403         break;
29404       }
29405     }
29406     if( (--aOp[pc+1]) > 0 ) nx = 0;
29407     pc += nx;
29408     i = (i & 0x7fffffff)%sz;
29409     if( (op & 1)!=0 ){
29410       SETBIT(pV, (i+1));
29411       if( op!=5 ){
29412         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
29413       }
29414     }else{
29415       CLEARBIT(pV, (i+1));
29416       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
29417     }
29418   }
29419
29420   /* Test to make sure the linear array exactly matches the
29421   ** Bitvec object.  Start with the assumption that they do
29422   ** match (rc==0).  Change rc to non-zero if a discrepancy
29423   ** is found.
29424   */
29425   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
29426           + sqlite3BitvecTest(pBitvec, 0)
29427           + (sqlite3BitvecSize(pBitvec) - sz);
29428   for(i=1; i<=sz; i++){
29429     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
29430       rc = i;
29431       break;
29432     }
29433   }
29434
29435   /* Free allocated structure */
29436 bitvec_end:
29437   sqlite3_free(pTmpSpace);
29438   sqlite3_free(pV);
29439   sqlite3BitvecDestroy(pBitvec);
29440   return rc;
29441 }
29442 #endif /* SQLITE_OMIT_BUILTIN_TEST */
29443
29444 /************** End of bitvec.c **********************************************/
29445 /************** Begin file pcache.c ******************************************/
29446 /*
29447 ** 2008 August 05
29448 **
29449 ** The author disclaims copyright to this source code.  In place of
29450 ** a legal notice, here is a blessing:
29451 **
29452 **    May you do good and not evil.
29453 **    May you find forgiveness for yourself and forgive others.
29454 **    May you share freely, never taking more than you give.
29455 **
29456 *************************************************************************
29457 ** This file implements that page cache.
29458 */
29459
29460 /*
29461 ** A complete page cache is an instance of this structure.
29462 */
29463 struct PCache {
29464   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
29465   PgHdr *pSynced;                     /* Last synced page in dirty page list */
29466   int nRef;                           /* Number of referenced pages */
29467   int nMax;                           /* Configured cache size */
29468   int szPage;                         /* Size of every page in this cache */
29469   int szExtra;                        /* Size of extra space for each page */
29470   int bPurgeable;                     /* True if pages are on backing store */
29471   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
29472   void *pStress;                      /* Argument to xStress */
29473   sqlite3_pcache *pCache;             /* Pluggable cache module */
29474   PgHdr *pPage1;                      /* Reference to page 1 */
29475 };
29476
29477 /*
29478 ** Some of the assert() macros in this code are too expensive to run
29479 ** even during normal debugging.  Use them only rarely on long-running
29480 ** tests.  Enable the expensive asserts using the
29481 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
29482 */
29483 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
29484 # define expensive_assert(X)  assert(X)
29485 #else
29486 # define expensive_assert(X)
29487 #endif
29488
29489 /********************************** Linked List Management ********************/
29490
29491 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
29492 /*
29493 ** Check that the pCache->pSynced variable is set correctly. If it
29494 ** is not, either fail an assert or return zero. Otherwise, return
29495 ** non-zero. This is only used in debugging builds, as follows:
29496 **
29497 **   expensive_assert( pcacheCheckSynced(pCache) );
29498 */
29499 static int pcacheCheckSynced(PCache *pCache){
29500   PgHdr *p;
29501   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
29502     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
29503   }
29504   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
29505 }
29506 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
29507
29508 /*
29509 ** Remove page pPage from the list of dirty pages.
29510 */
29511 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
29512   PCache *p = pPage->pCache;
29513
29514   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
29515   assert( pPage->pDirtyPrev || pPage==p->pDirty );
29516
29517   /* Update the PCache1.pSynced variable if necessary. */
29518   if( p->pSynced==pPage ){
29519     PgHdr *pSynced = pPage->pDirtyPrev;
29520     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
29521       pSynced = pSynced->pDirtyPrev;
29522     }
29523     p->pSynced = pSynced;
29524   }
29525
29526   if( pPage->pDirtyNext ){
29527     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
29528   }else{
29529     assert( pPage==p->pDirtyTail );
29530     p->pDirtyTail = pPage->pDirtyPrev;
29531   }
29532   if( pPage->pDirtyPrev ){
29533     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
29534   }else{
29535     assert( pPage==p->pDirty );
29536     p->pDirty = pPage->pDirtyNext;
29537   }
29538   pPage->pDirtyNext = 0;
29539   pPage->pDirtyPrev = 0;
29540
29541   expensive_assert( pcacheCheckSynced(p) );
29542 }
29543
29544 /*
29545 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
29546 ** pPage).
29547 */
29548 static void pcacheAddToDirtyList(PgHdr *pPage){
29549   PCache *p = pPage->pCache;
29550
29551   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
29552
29553   pPage->pDirtyNext = p->pDirty;
29554   if( pPage->pDirtyNext ){
29555     assert( pPage->pDirtyNext->pDirtyPrev==0 );
29556     pPage->pDirtyNext->pDirtyPrev = pPage;
29557   }
29558   p->pDirty = pPage;
29559   if( !p->pDirtyTail ){
29560     p->pDirtyTail = pPage;
29561   }
29562   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
29563     p->pSynced = pPage;
29564   }
29565   expensive_assert( pcacheCheckSynced(p) );
29566 }
29567
29568 /*
29569 ** Wrapper around the pluggable caches xUnpin method. If the cache is
29570 ** being used for an in-memory database, this function is a no-op.
29571 */
29572 static void pcacheUnpin(PgHdr *p){
29573   PCache *pCache = p->pCache;
29574   if( pCache->bPurgeable ){
29575     if( p->pgno==1 ){
29576       pCache->pPage1 = 0;
29577     }
29578     sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
29579   }
29580 }
29581
29582 /*************************************************** General Interfaces ******
29583 **
29584 ** Initialize and shutdown the page cache subsystem. Neither of these 
29585 ** functions are threadsafe.
29586 */
29587 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
29588   if( sqlite3GlobalConfig.pcache.xInit==0 ){
29589     sqlite3PCacheSetDefault();
29590   }
29591   return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
29592 }
29593 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
29594   if( sqlite3GlobalConfig.pcache.xShutdown ){
29595     sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
29596   }
29597 }
29598
29599 /*
29600 ** Return the size in bytes of a PCache object.
29601 */
29602 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
29603
29604 /*
29605 ** Create a new PCache object. Storage space to hold the object
29606 ** has already been allocated and is passed in as the p pointer. 
29607 ** The caller discovers how much space needs to be allocated by 
29608 ** calling sqlite3PcacheSize().
29609 */
29610 SQLITE_PRIVATE void sqlite3PcacheOpen(
29611   int szPage,                  /* Size of every page */
29612   int szExtra,                 /* Extra space associated with each page */
29613   int bPurgeable,              /* True if pages are on backing store */
29614   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
29615   void *pStress,               /* Argument to xStress */
29616   PCache *p                    /* Preallocated space for the PCache */
29617 ){
29618   memset(p, 0, sizeof(PCache));
29619   p->szPage = szPage;
29620   p->szExtra = szExtra;
29621   p->bPurgeable = bPurgeable;
29622   p->xStress = xStress;
29623   p->pStress = pStress;
29624   p->nMax = 100;
29625 }
29626
29627 /*
29628 ** Change the page size for PCache object. The caller must ensure that there
29629 ** are no outstanding page references when this function is called.
29630 */
29631 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
29632   assert( pCache->nRef==0 && pCache->pDirty==0 );
29633   if( pCache->pCache ){
29634     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
29635     pCache->pCache = 0;
29636   }
29637   pCache->szPage = szPage;
29638 }
29639
29640 /*
29641 ** Try to obtain a page from the cache.
29642 */
29643 SQLITE_PRIVATE int sqlite3PcacheFetch(
29644   PCache *pCache,       /* Obtain the page from this cache */
29645   Pgno pgno,            /* Page number to obtain */
29646   int createFlag,       /* If true, create page if it does not exist already */
29647   PgHdr **ppPage        /* Write the page here */
29648 ){
29649   PgHdr *pPage = 0;
29650   int eCreate;
29651
29652   assert( pCache!=0 );
29653   assert( createFlag==1 || createFlag==0 );
29654   assert( pgno>0 );
29655
29656   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
29657   ** allocate it now.
29658   */
29659   if( !pCache->pCache && createFlag ){
29660     sqlite3_pcache *p;
29661     int nByte;
29662     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
29663     p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
29664     if( !p ){
29665       return SQLITE_NOMEM;
29666     }
29667     sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
29668     pCache->pCache = p;
29669   }
29670
29671   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
29672   if( pCache->pCache ){
29673     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
29674   }
29675
29676   if( !pPage && eCreate==1 ){
29677     PgHdr *pPg;
29678
29679     /* Find a dirty page to write-out and recycle. First try to find a 
29680     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
29681     ** cleared), but if that is not possible settle for any other 
29682     ** unreferenced dirty page.
29683     */
29684     expensive_assert( pcacheCheckSynced(pCache) );
29685     for(pPg=pCache->pSynced; 
29686         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
29687         pPg=pPg->pDirtyPrev
29688     );
29689     if( !pPg ){
29690       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
29691     }
29692     if( pPg ){
29693       int rc;
29694       rc = pCache->xStress(pCache->pStress, pPg);
29695       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
29696         return rc;
29697       }
29698     }
29699
29700     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
29701   }
29702
29703   if( pPage ){
29704     if( !pPage->pData ){
29705       memset(pPage, 0, sizeof(PgHdr) + pCache->szExtra);
29706       pPage->pExtra = (void*)&pPage[1];
29707       pPage->pData = (void *)&((char *)pPage)[sizeof(PgHdr) + pCache->szExtra];
29708       pPage->pCache = pCache;
29709       pPage->pgno = pgno;
29710     }
29711     assert( pPage->pCache==pCache );
29712     assert( pPage->pgno==pgno );
29713     assert( pPage->pExtra==(void *)&pPage[1] );
29714
29715     if( 0==pPage->nRef ){
29716       pCache->nRef++;
29717     }
29718     pPage->nRef++;
29719     if( pgno==1 ){
29720       pCache->pPage1 = pPage;
29721     }
29722   }
29723   *ppPage = pPage;
29724   return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
29725 }
29726
29727 /*
29728 ** Decrement the reference count on a page. If the page is clean and the
29729 ** reference count drops to 0, then it is made elible for recycling.
29730 */
29731 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
29732   assert( p->nRef>0 );
29733   p->nRef--;
29734   if( p->nRef==0 ){
29735     PCache *pCache = p->pCache;
29736     pCache->nRef--;
29737     if( (p->flags&PGHDR_DIRTY)==0 ){
29738       pcacheUnpin(p);
29739     }else{
29740       /* Move the page to the head of the dirty list. */
29741       pcacheRemoveFromDirtyList(p);
29742       pcacheAddToDirtyList(p);
29743     }
29744   }
29745 }
29746
29747 /*
29748 ** Increase the reference count of a supplied page by 1.
29749 */
29750 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
29751   assert(p->nRef>0);
29752   p->nRef++;
29753 }
29754
29755 /*
29756 ** Drop a page from the cache. There must be exactly one reference to the
29757 ** page. This function deletes that reference, so after it returns the
29758 ** page pointed to by p is invalid.
29759 */
29760 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
29761   PCache *pCache;
29762   assert( p->nRef==1 );
29763   if( p->flags&PGHDR_DIRTY ){
29764     pcacheRemoveFromDirtyList(p);
29765   }
29766   pCache = p->pCache;
29767   pCache->nRef--;
29768   if( p->pgno==1 ){
29769     pCache->pPage1 = 0;
29770   }
29771   sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
29772 }
29773
29774 /*
29775 ** Make sure the page is marked as dirty. If it isn't dirty already,
29776 ** make it so.
29777 */
29778 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
29779   p->flags &= ~PGHDR_DONT_WRITE;
29780   assert( p->nRef>0 );
29781   if( 0==(p->flags & PGHDR_DIRTY) ){
29782     p->flags |= PGHDR_DIRTY;
29783     pcacheAddToDirtyList( p);
29784   }
29785 }
29786
29787 /*
29788 ** Make sure the page is marked as clean. If it isn't clean already,
29789 ** make it so.
29790 */
29791 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
29792   if( (p->flags & PGHDR_DIRTY) ){
29793     pcacheRemoveFromDirtyList(p);
29794     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
29795     if( p->nRef==0 ){
29796       pcacheUnpin(p);
29797     }
29798   }
29799 }
29800
29801 /*
29802 ** Make every page in the cache clean.
29803 */
29804 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
29805   PgHdr *p;
29806   while( (p = pCache->pDirty)!=0 ){
29807     sqlite3PcacheMakeClean(p);
29808   }
29809 }
29810
29811 /*
29812 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
29813 */
29814 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
29815   PgHdr *p;
29816   for(p=pCache->pDirty; p; p=p->pDirtyNext){
29817     p->flags &= ~PGHDR_NEED_SYNC;
29818   }
29819   pCache->pSynced = pCache->pDirtyTail;
29820 }
29821
29822 /*
29823 ** Change the page number of page p to newPgno. 
29824 */
29825 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
29826   PCache *pCache = p->pCache;
29827   assert( p->nRef>0 );
29828   assert( newPgno>0 );
29829   sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
29830   p->pgno = newPgno;
29831   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
29832     pcacheRemoveFromDirtyList(p);
29833     pcacheAddToDirtyList(p);
29834   }
29835 }
29836
29837 /*
29838 ** Drop every cache entry whose page number is greater than "pgno". The
29839 ** caller must ensure that there are no outstanding references to any pages
29840 ** other than page 1 with a page number greater than pgno.
29841 **
29842 ** If there is a reference to page 1 and the pgno parameter passed to this
29843 ** function is 0, then the data area associated with page 1 is zeroed, but
29844 ** the page object is not dropped.
29845 */
29846 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
29847   if( pCache->pCache ){
29848     PgHdr *p;
29849     PgHdr *pNext;
29850     for(p=pCache->pDirty; p; p=pNext){
29851       pNext = p->pDirtyNext;
29852       if( p->pgno>pgno ){
29853         assert( p->flags&PGHDR_DIRTY );
29854         sqlite3PcacheMakeClean(p);
29855       }
29856     }
29857     if( pgno==0 && pCache->pPage1 ){
29858       memset(pCache->pPage1->pData, 0, pCache->szPage);
29859       pgno = 1;
29860     }
29861     sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
29862   }
29863 }
29864
29865 /*
29866 ** Close a cache.
29867 */
29868 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
29869   if( pCache->pCache ){
29870     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
29871   }
29872 }
29873
29874 /* 
29875 ** Discard the contents of the cache.
29876 */
29877 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
29878   sqlite3PcacheTruncate(pCache, 0);
29879 }
29880
29881 /*
29882 ** Merge two lists of pages connected by pDirty and in pgno order.
29883 ** Do not both fixing the pDirtyPrev pointers.
29884 */
29885 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
29886   PgHdr result, *pTail;
29887   pTail = &result;
29888   while( pA && pB ){
29889     if( pA->pgno<pB->pgno ){
29890       pTail->pDirty = pA;
29891       pTail = pA;
29892       pA = pA->pDirty;
29893     }else{
29894       pTail->pDirty = pB;
29895       pTail = pB;
29896       pB = pB->pDirty;
29897     }
29898   }
29899   if( pA ){
29900     pTail->pDirty = pA;
29901   }else if( pB ){
29902     pTail->pDirty = pB;
29903   }else{
29904     pTail->pDirty = 0;
29905   }
29906   return result.pDirty;
29907 }
29908
29909 /*
29910 ** Sort the list of pages in accending order by pgno.  Pages are
29911 ** connected by pDirty pointers.  The pDirtyPrev pointers are
29912 ** corrupted by this sort.
29913 **
29914 ** Since there cannot be more than 2^31 distinct pages in a database,
29915 ** there cannot be more than 31 buckets required by the merge sorter.
29916 ** One extra bucket is added to catch overflow in case something
29917 ** ever changes to make the previous sentence incorrect.
29918 */
29919 #define N_SORT_BUCKET  32
29920 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
29921   PgHdr *a[N_SORT_BUCKET], *p;
29922   int i;
29923   memset(a, 0, sizeof(a));
29924   while( pIn ){
29925     p = pIn;
29926     pIn = p->pDirty;
29927     p->pDirty = 0;
29928     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
29929       if( a[i]==0 ){
29930         a[i] = p;
29931         break;
29932       }else{
29933         p = pcacheMergeDirtyList(a[i], p);
29934         a[i] = 0;
29935       }
29936     }
29937     if( NEVER(i==N_SORT_BUCKET-1) ){
29938       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
29939       ** the input list.  But that is impossible.
29940       */
29941       a[i] = pcacheMergeDirtyList(a[i], p);
29942     }
29943   }
29944   p = a[0];
29945   for(i=1; i<N_SORT_BUCKET; i++){
29946     p = pcacheMergeDirtyList(p, a[i]);
29947   }
29948   return p;
29949 }
29950
29951 /*
29952 ** Return a list of all dirty pages in the cache, sorted by page number.
29953 */
29954 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
29955   PgHdr *p;
29956   for(p=pCache->pDirty; p; p=p->pDirtyNext){
29957     p->pDirty = p->pDirtyNext;
29958   }
29959   return pcacheSortDirtyList(pCache->pDirty);
29960 }
29961
29962 /* 
29963 ** Return the total number of referenced pages held by the cache.
29964 */
29965 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
29966   return pCache->nRef;
29967 }
29968
29969 /*
29970 ** Return the number of references to the page supplied as an argument.
29971 */
29972 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
29973   return p->nRef;
29974 }
29975
29976 /* 
29977 ** Return the total number of pages in the cache.
29978 */
29979 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
29980   int nPage = 0;
29981   if( pCache->pCache ){
29982     nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
29983   }
29984   return nPage;
29985 }
29986
29987 #ifdef SQLITE_TEST
29988 /*
29989 ** Get the suggested cache-size value.
29990 */
29991 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
29992   return pCache->nMax;
29993 }
29994 #endif
29995
29996 /*
29997 ** Set the suggested cache-size value.
29998 */
29999 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
30000   pCache->nMax = mxPage;
30001   if( pCache->pCache ){
30002     sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
30003   }
30004 }
30005
30006 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
30007 /*
30008 ** For all dirty pages currently in the cache, invoke the specified
30009 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
30010 ** defined.
30011 */
30012 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
30013   PgHdr *pDirty;
30014   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
30015     xIter(pDirty);
30016   }
30017 }
30018 #endif
30019
30020 /************** End of pcache.c **********************************************/
30021 /************** Begin file pcache1.c *****************************************/
30022 /*
30023 ** 2008 November 05
30024 **
30025 ** The author disclaims copyright to this source code.  In place of
30026 ** a legal notice, here is a blessing:
30027 **
30028 **    May you do good and not evil.
30029 **    May you find forgiveness for yourself and forgive others.
30030 **    May you share freely, never taking more than you give.
30031 **
30032 *************************************************************************
30033 **
30034 ** This file implements the default page cache implementation (the
30035 ** sqlite3_pcache interface). It also contains part of the implementation
30036 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
30037 ** If the default page cache implementation is overriden, then neither of
30038 ** these two features are available.
30039 */
30040
30041
30042 typedef struct PCache1 PCache1;
30043 typedef struct PgHdr1 PgHdr1;
30044 typedef struct PgFreeslot PgFreeslot;
30045
30046 /* Pointers to structures of this type are cast and returned as 
30047 ** opaque sqlite3_pcache* handles
30048 */
30049 struct PCache1 {
30050   /* Cache configuration parameters. Page size (szPage) and the purgeable
30051   ** flag (bPurgeable) are set when the cache is created. nMax may be 
30052   ** modified at any time by a call to the pcache1CacheSize() method.
30053   ** The global mutex must be held when accessing nMax.
30054   */
30055   int szPage;                         /* Size of allocated pages in bytes */
30056   int bPurgeable;                     /* True if cache is purgeable */
30057   unsigned int nMin;                  /* Minimum number of pages reserved */
30058   unsigned int nMax;                  /* Configured "cache_size" value */
30059
30060   /* Hash table of all pages. The following variables may only be accessed
30061   ** when the accessor is holding the global mutex (see pcache1EnterMutex() 
30062   ** and pcache1LeaveMutex()).
30063   */
30064   unsigned int nRecyclable;           /* Number of pages in the LRU list */
30065   unsigned int nPage;                 /* Total number of pages in apHash */
30066   unsigned int nHash;                 /* Number of slots in apHash[] */
30067   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
30068
30069   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
30070 };
30071
30072 /*
30073 ** Each cache entry is represented by an instance of the following 
30074 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated 
30075 ** directly before this structure in memory (see the PGHDR1_TO_PAGE() 
30076 ** macro below).
30077 */
30078 struct PgHdr1 {
30079   unsigned int iKey;             /* Key value (page number) */
30080   PgHdr1 *pNext;                 /* Next in hash table chain */
30081   PCache1 *pCache;               /* Cache that currently owns this page */
30082   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
30083   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
30084 };
30085
30086 /*
30087 ** Free slots in the allocator used to divide up the buffer provided using
30088 ** the SQLITE_CONFIG_PAGECACHE mechanism.
30089 */
30090 struct PgFreeslot {
30091   PgFreeslot *pNext;  /* Next free slot */
30092 };
30093
30094 /*
30095 ** Global data used by this cache.
30096 */
30097 static SQLITE_WSD struct PCacheGlobal {
30098   sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
30099
30100   int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
30101   int nMinPage;                       /* Sum of nMinPage for purgeable caches */
30102   int nCurrentPage;                   /* Number of purgeable pages allocated */
30103   PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */
30104
30105   /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
30106   int szSlot;                         /* Size of each free slot */
30107   void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
30108   PgFreeslot *pFree;                  /* Free page blocks */
30109   int isInit;                         /* True if initialized */
30110 } pcache1_g;
30111
30112 /*
30113 ** All code in this file should access the global structure above via the
30114 ** alias "pcache1". This ensures that the WSD emulation is used when
30115 ** compiling for systems that do not support real WSD.
30116 */
30117 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
30118
30119 /*
30120 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
30121 ** bytes of data are located directly before it in memory (i.e. the total
30122 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
30123 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
30124 ** an argument and returns a pointer to the associated block of szPage
30125 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
30126 ** a pointer to a block of szPage bytes of data and the return value is
30127 ** a pointer to the associated PgHdr1 structure.
30128 **
30129 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
30130 */
30131 #define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
30132 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
30133
30134 /*
30135 ** Macros to enter and leave the global LRU mutex.
30136 */
30137 #define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
30138 #define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
30139
30140 /******************************************************************************/
30141 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
30142
30143 /*
30144 ** This function is called during initialization if a static buffer is 
30145 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
30146 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
30147 ** enough to contain 'n' buffers of 'sz' bytes each.
30148 */
30149 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
30150   if( pcache1.isInit ){
30151     PgFreeslot *p;
30152     sz = ROUNDDOWN8(sz);
30153     pcache1.szSlot = sz;
30154     pcache1.pStart = pBuf;
30155     pcache1.pFree = 0;
30156     while( n-- ){
30157       p = (PgFreeslot*)pBuf;
30158       p->pNext = pcache1.pFree;
30159       pcache1.pFree = p;
30160       pBuf = (void*)&((char*)pBuf)[sz];
30161     }
30162     pcache1.pEnd = pBuf;
30163   }
30164 }
30165
30166 /*
30167 ** Malloc function used within this file to allocate space from the buffer
30168 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
30169 ** such buffer exists or there is no space left in it, this function falls 
30170 ** back to sqlite3Malloc().
30171 */
30172 static void *pcache1Alloc(int nByte){
30173   void *p;
30174   assert( sqlite3_mutex_held(pcache1.mutex) );
30175   if( nByte<=pcache1.szSlot && pcache1.pFree ){
30176     assert( pcache1.isInit );
30177     p = (PgHdr1 *)pcache1.pFree;
30178     pcache1.pFree = pcache1.pFree->pNext;
30179     sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
30180     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
30181   }else{
30182
30183     /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
30184     ** global pcache mutex and unlock the pager-cache object pCache. This is 
30185     ** so that if the attempt to allocate a new buffer causes the the 
30186     ** configured soft-heap-limit to be breached, it will be possible to
30187     ** reclaim memory from this pager-cache.
30188     */
30189     pcache1LeaveMutex();
30190     p = sqlite3Malloc(nByte);
30191     pcache1EnterMutex();
30192     if( p ){
30193       int sz = sqlite3MallocSize(p);
30194       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
30195     }
30196   }
30197   return p;
30198 }
30199
30200 /*
30201 ** Free an allocated buffer obtained from pcache1Alloc().
30202 */
30203 static void pcache1Free(void *p){
30204   assert( sqlite3_mutex_held(pcache1.mutex) );
30205   if( p==0 ) return;
30206   if( p>=pcache1.pStart && p<pcache1.pEnd ){
30207     PgFreeslot *pSlot;
30208     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
30209     pSlot = (PgFreeslot*)p;
30210     pSlot->pNext = pcache1.pFree;
30211     pcache1.pFree = pSlot;
30212   }else{
30213     int iSize = sqlite3MallocSize(p);
30214     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
30215     sqlite3_free(p);
30216   }
30217 }
30218
30219 /*
30220 ** Allocate a new page object initially associated with cache pCache.
30221 */
30222 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
30223   int nByte = sizeof(PgHdr1) + pCache->szPage;
30224   void *pPg = pcache1Alloc(nByte);
30225   PgHdr1 *p;
30226   if( pPg ){
30227     p = PAGE_TO_PGHDR1(pCache, pPg);
30228     if( pCache->bPurgeable ){
30229       pcache1.nCurrentPage++;
30230     }
30231   }else{
30232     p = 0;
30233   }
30234   return p;
30235 }
30236
30237 /*
30238 ** Free a page object allocated by pcache1AllocPage().
30239 **
30240 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
30241 ** that the current implementation happens to never call this routine
30242 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
30243 */
30244 static void pcache1FreePage(PgHdr1 *p){
30245   if( ALWAYS(p) ){
30246     if( p->pCache->bPurgeable ){
30247       pcache1.nCurrentPage--;
30248     }
30249     pcache1Free(PGHDR1_TO_PAGE(p));
30250   }
30251 }
30252
30253 /*
30254 ** Malloc function used by SQLite to obtain space from the buffer configured
30255 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
30256 ** exists, this function falls back to sqlite3Malloc().
30257 */
30258 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
30259   void *p;
30260   pcache1EnterMutex();
30261   p = pcache1Alloc(sz);
30262   pcache1LeaveMutex();
30263   return p;
30264 }
30265
30266 /*
30267 ** Free an allocated buffer obtained from sqlite3PageMalloc().
30268 */
30269 SQLITE_PRIVATE void sqlite3PageFree(void *p){
30270   pcache1EnterMutex();
30271   pcache1Free(p);
30272   pcache1LeaveMutex();
30273 }
30274
30275 /******************************************************************************/
30276 /******** General Implementation Functions ************************************/
30277
30278 /*
30279 ** This function is used to resize the hash table used by the cache passed
30280 ** as the first argument.
30281 **
30282 ** The global mutex must be held when this function is called.
30283 */
30284 static int pcache1ResizeHash(PCache1 *p){
30285   PgHdr1 **apNew;
30286   unsigned int nNew;
30287   unsigned int i;
30288
30289   assert( sqlite3_mutex_held(pcache1.mutex) );
30290
30291   nNew = p->nHash*2;
30292   if( nNew<256 ){
30293     nNew = 256;
30294   }
30295
30296   pcache1LeaveMutex();
30297   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
30298   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
30299   if( p->nHash ){ sqlite3EndBenignMalloc(); }
30300   pcache1EnterMutex();
30301   if( apNew ){
30302     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
30303     for(i=0; i<p->nHash; i++){
30304       PgHdr1 *pPage;
30305       PgHdr1 *pNext = p->apHash[i];
30306       while( (pPage = pNext)!=0 ){
30307         unsigned int h = pPage->iKey % nNew;
30308         pNext = pPage->pNext;
30309         pPage->pNext = apNew[h];
30310         apNew[h] = pPage;
30311       }
30312     }
30313     sqlite3_free(p->apHash);
30314     p->apHash = apNew;
30315     p->nHash = nNew;
30316   }
30317
30318   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
30319 }
30320
30321 /*
30322 ** This function is used internally to remove the page pPage from the 
30323 ** global LRU list, if is part of it. If pPage is not part of the global
30324 ** LRU list, then this function is a no-op.
30325 **
30326 ** The global mutex must be held when this function is called.
30327 */
30328 static void pcache1PinPage(PgHdr1 *pPage){
30329   assert( sqlite3_mutex_held(pcache1.mutex) );
30330   if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
30331     if( pPage->pLruPrev ){
30332       pPage->pLruPrev->pLruNext = pPage->pLruNext;
30333     }
30334     if( pPage->pLruNext ){
30335       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
30336     }
30337     if( pcache1.pLruHead==pPage ){
30338       pcache1.pLruHead = pPage->pLruNext;
30339     }
30340     if( pcache1.pLruTail==pPage ){
30341       pcache1.pLruTail = pPage->pLruPrev;
30342     }
30343     pPage->pLruNext = 0;
30344     pPage->pLruPrev = 0;
30345     pPage->pCache->nRecyclable--;
30346   }
30347 }
30348
30349
30350 /*
30351 ** Remove the page supplied as an argument from the hash table 
30352 ** (PCache1.apHash structure) that it is currently stored in.
30353 **
30354 ** The global mutex must be held when this function is called.
30355 */
30356 static void pcache1RemoveFromHash(PgHdr1 *pPage){
30357   unsigned int h;
30358   PCache1 *pCache = pPage->pCache;
30359   PgHdr1 **pp;
30360
30361   h = pPage->iKey % pCache->nHash;
30362   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
30363   *pp = (*pp)->pNext;
30364
30365   pCache->nPage--;
30366 }
30367
30368 /*
30369 ** If there are currently more than pcache.nMaxPage pages allocated, try
30370 ** to recycle pages to reduce the number allocated to pcache.nMaxPage.
30371 */
30372 static void pcache1EnforceMaxPage(void){
30373   assert( sqlite3_mutex_held(pcache1.mutex) );
30374   while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
30375     PgHdr1 *p = pcache1.pLruTail;
30376     pcache1PinPage(p);
30377     pcache1RemoveFromHash(p);
30378     pcache1FreePage(p);
30379   }
30380 }
30381
30382 /*
30383 ** Discard all pages from cache pCache with a page number (key value) 
30384 ** greater than or equal to iLimit. Any pinned pages that meet this 
30385 ** criteria are unpinned before they are discarded.
30386 **
30387 ** The global mutex must be held when this function is called.
30388 */
30389 static void pcache1TruncateUnsafe(
30390   PCache1 *pCache, 
30391   unsigned int iLimit 
30392 ){
30393   TESTONLY( unsigned int nPage = 0; )      /* Used to assert pCache->nPage is correct */
30394   unsigned int h;
30395   assert( sqlite3_mutex_held(pcache1.mutex) );
30396   for(h=0; h<pCache->nHash; h++){
30397     PgHdr1 **pp = &pCache->apHash[h]; 
30398     PgHdr1 *pPage;
30399     while( (pPage = *pp)!=0 ){
30400       if( pPage->iKey>=iLimit ){
30401         pCache->nPage--;
30402         *pp = pPage->pNext;
30403         pcache1PinPage(pPage);
30404         pcache1FreePage(pPage);
30405       }else{
30406         pp = &pPage->pNext;
30407         TESTONLY( nPage++; )
30408       }
30409     }
30410   }
30411   assert( pCache->nPage==nPage );
30412 }
30413
30414 /******************************************************************************/
30415 /******** sqlite3_pcache Methods **********************************************/
30416
30417 /*
30418 ** Implementation of the sqlite3_pcache.xInit method.
30419 */
30420 static int pcache1Init(void *NotUsed){
30421   UNUSED_PARAMETER(NotUsed);
30422   assert( pcache1.isInit==0 );
30423   memset(&pcache1, 0, sizeof(pcache1));
30424   if( sqlite3GlobalConfig.bCoreMutex ){
30425     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
30426   }
30427   pcache1.isInit = 1;
30428   return SQLITE_OK;
30429 }
30430
30431 /*
30432 ** Implementation of the sqlite3_pcache.xShutdown method.
30433 ** Note that the static mutex allocated in xInit does 
30434 ** not need to be freed.
30435 */
30436 static void pcache1Shutdown(void *NotUsed){
30437   UNUSED_PARAMETER(NotUsed);
30438   assert( pcache1.isInit!=0 );
30439   memset(&pcache1, 0, sizeof(pcache1));
30440 }
30441
30442 /*
30443 ** Implementation of the sqlite3_pcache.xCreate method.
30444 **
30445 ** Allocate a new cache.
30446 */
30447 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
30448   PCache1 *pCache;
30449
30450   pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
30451   if( pCache ){
30452     memset(pCache, 0, sizeof(PCache1));
30453     pCache->szPage = szPage;
30454     pCache->bPurgeable = (bPurgeable ? 1 : 0);
30455     if( bPurgeable ){
30456       pCache->nMin = 10;
30457       pcache1EnterMutex();
30458       pcache1.nMinPage += pCache->nMin;
30459       pcache1LeaveMutex();
30460     }
30461   }
30462   return (sqlite3_pcache *)pCache;
30463 }
30464
30465 /*
30466 ** Implementation of the sqlite3_pcache.xCachesize method. 
30467 **
30468 ** Configure the cache_size limit for a cache.
30469 */
30470 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
30471   PCache1 *pCache = (PCache1 *)p;
30472   if( pCache->bPurgeable ){
30473     pcache1EnterMutex();
30474     pcache1.nMaxPage += (nMax - pCache->nMax);
30475     pCache->nMax = nMax;
30476     pcache1EnforceMaxPage();
30477     pcache1LeaveMutex();
30478   }
30479 }
30480
30481 /*
30482 ** Implementation of the sqlite3_pcache.xPagecount method. 
30483 */
30484 static int pcache1Pagecount(sqlite3_pcache *p){
30485   int n;
30486   pcache1EnterMutex();
30487   n = ((PCache1 *)p)->nPage;
30488   pcache1LeaveMutex();
30489   return n;
30490 }
30491
30492 /*
30493 ** Implementation of the sqlite3_pcache.xFetch method. 
30494 **
30495 ** Fetch a page by key value.
30496 **
30497 ** Whether or not a new page may be allocated by this function depends on
30498 ** the value of the createFlag argument.  0 means do not allocate a new
30499 ** page.  1 means allocate a new page if space is easily available.  2 
30500 ** means to try really hard to allocate a new page.
30501 **
30502 ** For a non-purgeable cache (a cache used as the storage for an in-memory
30503 ** database) there is really no difference between createFlag 1 and 2.  So
30504 ** the calling function (pcache.c) will never have a createFlag of 1 on
30505 ** a non-purgable cache.
30506 **
30507 ** There are three different approaches to obtaining space for a page,
30508 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
30509 **
30510 **   1. Regardless of the value of createFlag, the cache is searched for a 
30511 **      copy of the requested page. If one is found, it is returned.
30512 **
30513 **   2. If createFlag==0 and the page is not already in the cache, NULL is
30514 **      returned.
30515 **
30516 **   3. If createFlag is 1, and the page is not already in the cache,
30517 **      and if either of the following are true, return NULL:
30518 **
30519 **       (a) the number of pages pinned by the cache is greater than
30520 **           PCache1.nMax, or
30521 **       (b) the number of pages pinned by the cache is greater than
30522 **           the sum of nMax for all purgeable caches, less the sum of 
30523 **           nMin for all other purgeable caches. 
30524 **
30525 **   4. If none of the first three conditions apply and the cache is marked
30526 **      as purgeable, and if one of the following is true:
30527 **
30528 **       (a) The number of pages allocated for the cache is already 
30529 **           PCache1.nMax, or
30530 **
30531 **       (b) The number of pages allocated for all purgeable caches is
30532 **           already equal to or greater than the sum of nMax for all
30533 **           purgeable caches,
30534 **
30535 **      then attempt to recycle a page from the LRU list. If it is the right
30536 **      size, return the recycled buffer. Otherwise, free the buffer and
30537 **      proceed to step 5. 
30538 **
30539 **   5. Otherwise, allocate and return a new page buffer.
30540 */
30541 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
30542   unsigned int nPinned;
30543   PCache1 *pCache = (PCache1 *)p;
30544   PgHdr1 *pPage = 0;
30545
30546   assert( pCache->bPurgeable || createFlag!=1 );
30547   pcache1EnterMutex();
30548   if( createFlag==1 ) sqlite3BeginBenignMalloc();
30549
30550   /* Search the hash table for an existing entry. */
30551   if( pCache->nHash>0 ){
30552     unsigned int h = iKey % pCache->nHash;
30553     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
30554   }
30555
30556   if( pPage || createFlag==0 ){
30557     pcache1PinPage(pPage);
30558     goto fetch_out;
30559   }
30560
30561   /* Step 3 of header comment. */
30562   nPinned = pCache->nPage - pCache->nRecyclable;
30563   if( createFlag==1 && (
30564         nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
30565      || nPinned>=(pCache->nMax * 9 / 10)
30566   )){
30567     goto fetch_out;
30568   }
30569
30570   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
30571     goto fetch_out;
30572   }
30573
30574   /* Step 4. Try to recycle a page buffer if appropriate. */
30575   if( pCache->bPurgeable && pcache1.pLruTail && (
30576      (pCache->nPage+1>=pCache->nMax) || pcache1.nCurrentPage>=pcache1.nMaxPage
30577   )){
30578     pPage = pcache1.pLruTail;
30579     pcache1RemoveFromHash(pPage);
30580     pcache1PinPage(pPage);
30581     if( pPage->pCache->szPage!=pCache->szPage ){
30582       pcache1FreePage(pPage);
30583       pPage = 0;
30584     }else{
30585       pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
30586     }
30587   }
30588
30589   /* Step 5. If a usable page buffer has still not been found, 
30590   ** attempt to allocate a new one. 
30591   */
30592   if( !pPage ){
30593     pPage = pcache1AllocPage(pCache);
30594   }
30595
30596   if( pPage ){
30597     unsigned int h = iKey % pCache->nHash;
30598     pCache->nPage++;
30599     pPage->iKey = iKey;
30600     pPage->pNext = pCache->apHash[h];
30601     pPage->pCache = pCache;
30602     pPage->pLruPrev = 0;
30603     pPage->pLruNext = 0;
30604     *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
30605     pCache->apHash[h] = pPage;
30606   }
30607
30608 fetch_out:
30609   if( pPage && iKey>pCache->iMaxKey ){
30610     pCache->iMaxKey = iKey;
30611   }
30612   if( createFlag==1 ) sqlite3EndBenignMalloc();
30613   pcache1LeaveMutex();
30614   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
30615 }
30616
30617
30618 /*
30619 ** Implementation of the sqlite3_pcache.xUnpin method.
30620 **
30621 ** Mark a page as unpinned (eligible for asynchronous recycling).
30622 */
30623 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
30624   PCache1 *pCache = (PCache1 *)p;
30625   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
30626  
30627   assert( pPage->pCache==pCache );
30628   pcache1EnterMutex();
30629
30630   /* It is an error to call this function if the page is already 
30631   ** part of the global LRU list.
30632   */
30633   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
30634   assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
30635
30636   if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
30637     pcache1RemoveFromHash(pPage);
30638     pcache1FreePage(pPage);
30639   }else{
30640     /* Add the page to the global LRU list. Normally, the page is added to
30641     ** the head of the list (last page to be recycled). However, if the 
30642     ** reuseUnlikely flag passed to this function is true, the page is added
30643     ** to the tail of the list (first page to be recycled).
30644     */
30645     if( pcache1.pLruHead ){
30646       pcache1.pLruHead->pLruPrev = pPage;
30647       pPage->pLruNext = pcache1.pLruHead;
30648       pcache1.pLruHead = pPage;
30649     }else{
30650       pcache1.pLruTail = pPage;
30651       pcache1.pLruHead = pPage;
30652     }
30653     pCache->nRecyclable++;
30654   }
30655
30656   pcache1LeaveMutex();
30657 }
30658
30659 /*
30660 ** Implementation of the sqlite3_pcache.xRekey method. 
30661 */
30662 static void pcache1Rekey(
30663   sqlite3_pcache *p,
30664   void *pPg,
30665   unsigned int iOld,
30666   unsigned int iNew
30667 ){
30668   PCache1 *pCache = (PCache1 *)p;
30669   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
30670   PgHdr1 **pp;
30671   unsigned int h; 
30672   assert( pPage->iKey==iOld );
30673   assert( pPage->pCache==pCache );
30674
30675   pcache1EnterMutex();
30676
30677   h = iOld%pCache->nHash;
30678   pp = &pCache->apHash[h];
30679   while( (*pp)!=pPage ){
30680     pp = &(*pp)->pNext;
30681   }
30682   *pp = pPage->pNext;
30683
30684   h = iNew%pCache->nHash;
30685   pPage->iKey = iNew;
30686   pPage->pNext = pCache->apHash[h];
30687   pCache->apHash[h] = pPage;
30688   if( iNew>pCache->iMaxKey ){
30689     pCache->iMaxKey = iNew;
30690   }
30691
30692   pcache1LeaveMutex();
30693 }
30694
30695 /*
30696 ** Implementation of the sqlite3_pcache.xTruncate method. 
30697 **
30698 ** Discard all unpinned pages in the cache with a page number equal to
30699 ** or greater than parameter iLimit. Any pinned pages with a page number
30700 ** equal to or greater than iLimit are implicitly unpinned.
30701 */
30702 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
30703   PCache1 *pCache = (PCache1 *)p;
30704   pcache1EnterMutex();
30705   if( iLimit<=pCache->iMaxKey ){
30706     pcache1TruncateUnsafe(pCache, iLimit);
30707     pCache->iMaxKey = iLimit-1;
30708   }
30709   pcache1LeaveMutex();
30710 }
30711
30712 /*
30713 ** Implementation of the sqlite3_pcache.xDestroy method. 
30714 **
30715 ** Destroy a cache allocated using pcache1Create().
30716 */
30717 static void pcache1Destroy(sqlite3_pcache *p){
30718   PCache1 *pCache = (PCache1 *)p;
30719   pcache1EnterMutex();
30720   pcache1TruncateUnsafe(pCache, 0);
30721   pcache1.nMaxPage -= pCache->nMax;
30722   pcache1.nMinPage -= pCache->nMin;
30723   pcache1EnforceMaxPage();
30724   pcache1LeaveMutex();
30725   sqlite3_free(pCache->apHash);
30726   sqlite3_free(pCache);
30727 }
30728
30729 /*
30730 ** This function is called during initialization (sqlite3_initialize()) to
30731 ** install the default pluggable cache module, assuming the user has not
30732 ** already provided an alternative.
30733 */
30734 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
30735   static sqlite3_pcache_methods defaultMethods = {
30736     0,                       /* pArg */
30737     pcache1Init,             /* xInit */
30738     pcache1Shutdown,         /* xShutdown */
30739     pcache1Create,           /* xCreate */
30740     pcache1Cachesize,        /* xCachesize */
30741     pcache1Pagecount,        /* xPagecount */
30742     pcache1Fetch,            /* xFetch */
30743     pcache1Unpin,            /* xUnpin */
30744     pcache1Rekey,            /* xRekey */
30745     pcache1Truncate,         /* xTruncate */
30746     pcache1Destroy           /* xDestroy */
30747   };
30748   sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
30749 }
30750
30751 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
30752 /*
30753 ** This function is called to free superfluous dynamically allocated memory
30754 ** held by the pager system. Memory in use by any SQLite pager allocated
30755 ** by the current thread may be sqlite3_free()ed.
30756 **
30757 ** nReq is the number of bytes of memory required. Once this much has
30758 ** been released, the function returns. The return value is the total number 
30759 ** of bytes of memory released.
30760 */
30761 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
30762   int nFree = 0;
30763   if( pcache1.pStart==0 ){
30764     PgHdr1 *p;
30765     pcache1EnterMutex();
30766     while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
30767       nFree += sqlite3MallocSize(PGHDR1_TO_PAGE(p));
30768       pcache1PinPage(p);
30769       pcache1RemoveFromHash(p);
30770       pcache1FreePage(p);
30771     }
30772     pcache1LeaveMutex();
30773   }
30774   return nFree;
30775 }
30776 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
30777
30778 #ifdef SQLITE_TEST
30779 /*
30780 ** This function is used by test procedures to inspect the internal state
30781 ** of the global cache.
30782 */
30783 SQLITE_PRIVATE void sqlite3PcacheStats(
30784   int *pnCurrent,      /* OUT: Total number of pages cached */
30785   int *pnMax,          /* OUT: Global maximum cache size */
30786   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
30787   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
30788 ){
30789   PgHdr1 *p;
30790   int nRecyclable = 0;
30791   for(p=pcache1.pLruHead; p; p=p->pLruNext){
30792     nRecyclable++;
30793   }
30794   *pnCurrent = pcache1.nCurrentPage;
30795   *pnMax = pcache1.nMaxPage;
30796   *pnMin = pcache1.nMinPage;
30797   *pnRecyclable = nRecyclable;
30798 }
30799 #endif
30800
30801 /************** End of pcache1.c *********************************************/
30802 /************** Begin file rowset.c ******************************************/
30803 /*
30804 ** 2008 December 3
30805 **
30806 ** The author disclaims copyright to this source code.  In place of
30807 ** a legal notice, here is a blessing:
30808 **
30809 **    May you do good and not evil.
30810 **    May you find forgiveness for yourself and forgive others.
30811 **    May you share freely, never taking more than you give.
30812 **
30813 *************************************************************************
30814 **
30815 ** This module implements an object we call a "RowSet".
30816 **
30817 ** The RowSet object is a collection of rowids.  Rowids
30818 ** are inserted into the RowSet in an arbitrary order.  Inserts
30819 ** can be intermixed with tests to see if a given rowid has been
30820 ** previously inserted into the RowSet.
30821 **
30822 ** After all inserts are finished, it is possible to extract the
30823 ** elements of the RowSet in sorted order.  Once this extraction
30824 ** process has started, no new elements may be inserted.
30825 **
30826 ** Hence, the primitive operations for a RowSet are:
30827 **
30828 **    CREATE
30829 **    INSERT
30830 **    TEST
30831 **    SMALLEST
30832 **    DESTROY
30833 **
30834 ** The CREATE and DESTROY primitives are the constructor and destructor,
30835 ** obviously.  The INSERT primitive adds a new element to the RowSet.
30836 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
30837 ** extracts the least value from the RowSet.
30838 **
30839 ** The INSERT primitive might allocate additional memory.  Memory is
30840 ** allocated in chunks so most INSERTs do no allocation.  There is an 
30841 ** upper bound on the size of allocated memory.  No memory is freed
30842 ** until DESTROY.
30843 **
30844 ** The TEST primitive includes a "batch" number.  The TEST primitive
30845 ** will only see elements that were inserted before the last change
30846 ** in the batch number.  In other words, if an INSERT occurs between
30847 ** two TESTs where the TESTs have the same batch nubmer, then the
30848 ** value added by the INSERT will not be visible to the second TEST.
30849 ** The initial batch number is zero, so if the very first TEST contains
30850 ** a non-zero batch number, it will see all prior INSERTs.
30851 **
30852 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
30853 ** that is attempted.
30854 **
30855 ** The cost of an INSERT is roughly constant.  (Sometime new memory
30856 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
30857 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
30858 ** The cost of a TEST using the same batch number is O(logN).  The cost
30859 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
30860 ** primitives are constant time.  The cost of DESTROY is O(N).
30861 **
30862 ** There is an added cost of O(N) when switching between TEST and
30863 ** SMALLEST primitives.
30864 */
30865
30866
30867 /*
30868 ** Target size for allocation chunks.
30869 */
30870 #define ROWSET_ALLOCATION_SIZE 1024
30871
30872 /*
30873 ** The number of rowset entries per allocation chunk.
30874 */
30875 #define ROWSET_ENTRY_PER_CHUNK  \
30876                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
30877
30878 /*
30879 ** Each entry in a RowSet is an instance of the following object.
30880 */
30881 struct RowSetEntry {            
30882   i64 v;                        /* ROWID value for this entry */
30883   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
30884   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
30885 };
30886
30887 /*
30888 ** RowSetEntry objects are allocated in large chunks (instances of the
30889 ** following structure) to reduce memory allocation overhead.  The
30890 ** chunks are kept on a linked list so that they can be deallocated
30891 ** when the RowSet is destroyed.
30892 */
30893 struct RowSetChunk {
30894   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
30895   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
30896 };
30897
30898 /*
30899 ** A RowSet in an instance of the following structure.
30900 **
30901 ** A typedef of this structure if found in sqliteInt.h.
30902 */
30903 struct RowSet {
30904   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
30905   sqlite3 *db;                   /* The database connection */
30906   struct RowSetEntry *pEntry;    /* List of entries using pRight */
30907   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
30908   struct RowSetEntry *pFresh;    /* Source of new entry objects */
30909   struct RowSetEntry *pTree;     /* Binary tree of entries */
30910   u16 nFresh;                    /* Number of objects on pFresh */
30911   u8 isSorted;                   /* True if pEntry is sorted */
30912   u8 iBatch;                     /* Current insert batch */
30913 };
30914
30915 /*
30916 ** Turn bulk memory into a RowSet object.  N bytes of memory
30917 ** are available at pSpace.  The db pointer is used as a memory context
30918 ** for any subsequent allocations that need to occur.
30919 ** Return a pointer to the new RowSet object.
30920 **
30921 ** It must be the case that N is sufficient to make a Rowset.  If not
30922 ** an assertion fault occurs.
30923 ** 
30924 ** If N is larger than the minimum, use the surplus as an initial
30925 ** allocation of entries available to be filled.
30926 */
30927 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
30928   RowSet *p;
30929   assert( N >= ROUND8(sizeof(*p)) );
30930   p = pSpace;
30931   p->pChunk = 0;
30932   p->db = db;
30933   p->pEntry = 0;
30934   p->pLast = 0;
30935   p->pTree = 0;
30936   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
30937   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
30938   p->isSorted = 1;
30939   p->iBatch = 0;
30940   return p;
30941 }
30942
30943 /*
30944 ** Deallocate all chunks from a RowSet.  This frees all memory that
30945 ** the RowSet has allocated over its lifetime.  This routine is
30946 ** the destructor for the RowSet.
30947 */
30948 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
30949   struct RowSetChunk *pChunk, *pNextChunk;
30950   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
30951     pNextChunk = pChunk->pNextChunk;
30952     sqlite3DbFree(p->db, pChunk);
30953   }
30954   p->pChunk = 0;
30955   p->nFresh = 0;
30956   p->pEntry = 0;
30957   p->pLast = 0;
30958   p->pTree = 0;
30959   p->isSorted = 1;
30960 }
30961
30962 /*
30963 ** Insert a new value into a RowSet.
30964 **
30965 ** The mallocFailed flag of the database connection is set if a
30966 ** memory allocation fails.
30967 */
30968 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
30969   struct RowSetEntry *pEntry;  /* The new entry */
30970   struct RowSetEntry *pLast;   /* The last prior entry */
30971   assert( p!=0 );
30972   if( p->nFresh==0 ){
30973     struct RowSetChunk *pNew;
30974     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
30975     if( pNew==0 ){
30976       return;
30977     }
30978     pNew->pNextChunk = p->pChunk;
30979     p->pChunk = pNew;
30980     p->pFresh = pNew->aEntry;
30981     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
30982   }
30983   pEntry = p->pFresh++;
30984   p->nFresh--;
30985   pEntry->v = rowid;
30986   pEntry->pRight = 0;
30987   pLast = p->pLast;
30988   if( pLast ){
30989     if( p->isSorted && rowid<=pLast->v ){
30990       p->isSorted = 0;
30991     }
30992     pLast->pRight = pEntry;
30993   }else{
30994     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
30995     p->pEntry = pEntry;
30996   }
30997   p->pLast = pEntry;
30998 }
30999
31000 /*
31001 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
31002 **
31003 ** The input lists are connected via pRight pointers and are 
31004 ** assumed to each already be in sorted order.
31005 */
31006 static struct RowSetEntry *rowSetMerge(
31007   struct RowSetEntry *pA,    /* First sorted list to be merged */
31008   struct RowSetEntry *pB     /* Second sorted list to be merged */
31009 ){
31010   struct RowSetEntry head;
31011   struct RowSetEntry *pTail;
31012
31013   pTail = &head;
31014   while( pA && pB ){
31015     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
31016     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
31017     if( pA->v<pB->v ){
31018       pTail->pRight = pA;
31019       pA = pA->pRight;
31020       pTail = pTail->pRight;
31021     }else if( pB->v<pA->v ){
31022       pTail->pRight = pB;
31023       pB = pB->pRight;
31024       pTail = pTail->pRight;
31025     }else{
31026       pA = pA->pRight;
31027     }
31028   }
31029   if( pA ){
31030     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
31031     pTail->pRight = pA;
31032   }else{
31033     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
31034     pTail->pRight = pB;
31035   }
31036   return head.pRight;
31037 }
31038
31039 /*
31040 ** Sort all elements on the pEntry list of the RowSet into ascending order.
31041 */ 
31042 static void rowSetSort(RowSet *p){
31043   unsigned int i;
31044   struct RowSetEntry *pEntry;
31045   struct RowSetEntry *aBucket[40];
31046
31047   assert( p->isSorted==0 );
31048   memset(aBucket, 0, sizeof(aBucket));
31049   while( p->pEntry ){
31050     pEntry = p->pEntry;
31051     p->pEntry = pEntry->pRight;
31052     pEntry->pRight = 0;
31053     for(i=0; aBucket[i]; i++){
31054       pEntry = rowSetMerge(aBucket[i], pEntry);
31055       aBucket[i] = 0;
31056     }
31057     aBucket[i] = pEntry;
31058   }
31059   pEntry = 0;
31060   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
31061     pEntry = rowSetMerge(pEntry, aBucket[i]);
31062   }
31063   p->pEntry = pEntry;
31064   p->pLast = 0;
31065   p->isSorted = 1;
31066 }
31067
31068
31069 /*
31070 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
31071 ** Convert this tree into a linked list connected by the pRight pointers
31072 ** and return pointers to the first and last elements of the new list.
31073 */
31074 static void rowSetTreeToList(
31075   struct RowSetEntry *pIn,         /* Root of the input tree */
31076   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
31077   struct RowSetEntry **ppLast      /* Write tail of the output list here */
31078 ){
31079   assert( pIn!=0 );
31080   if( pIn->pLeft ){
31081     struct RowSetEntry *p;
31082     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
31083     p->pRight = pIn;
31084   }else{
31085     *ppFirst = pIn;
31086   }
31087   if( pIn->pRight ){
31088     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
31089   }else{
31090     *ppLast = pIn;
31091   }
31092   assert( (*ppLast)->pRight==0 );
31093 }
31094
31095
31096 /*
31097 ** Convert a sorted list of elements (connected by pRight) into a binary
31098 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
31099 ** node taken from the head of *ppList.  A depth of 2 means a tree with
31100 ** three nodes.  And so forth.
31101 **
31102 ** Use as many entries from the input list as required and update the
31103 ** *ppList to point to the unused elements of the list.  If the input
31104 ** list contains too few elements, then construct an incomplete tree
31105 ** and leave *ppList set to NULL.
31106 **
31107 ** Return a pointer to the root of the constructed binary tree.
31108 */
31109 static struct RowSetEntry *rowSetNDeepTree(
31110   struct RowSetEntry **ppList,
31111   int iDepth
31112 ){
31113   struct RowSetEntry *p;         /* Root of the new tree */
31114   struct RowSetEntry *pLeft;     /* Left subtree */
31115   if( *ppList==0 ){
31116     return 0;
31117   }
31118   if( iDepth==1 ){
31119     p = *ppList;
31120     *ppList = p->pRight;
31121     p->pLeft = p->pRight = 0;
31122     return p;
31123   }
31124   pLeft = rowSetNDeepTree(ppList, iDepth-1);
31125   p = *ppList;
31126   if( p==0 ){
31127     return pLeft;
31128   }
31129   p->pLeft = pLeft;
31130   *ppList = p->pRight;
31131   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
31132   return p;
31133 }
31134
31135 /*
31136 ** Convert a sorted list of elements into a binary tree. Make the tree
31137 ** as deep as it needs to be in order to contain the entire list.
31138 */
31139 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
31140   int iDepth;           /* Depth of the tree so far */
31141   struct RowSetEntry *p;       /* Current tree root */
31142   struct RowSetEntry *pLeft;   /* Left subtree */
31143
31144   assert( pList!=0 );
31145   p = pList;
31146   pList = p->pRight;
31147   p->pLeft = p->pRight = 0;
31148   for(iDepth=1; pList; iDepth++){
31149     pLeft = p;
31150     p = pList;
31151     pList = p->pRight;
31152     p->pLeft = pLeft;
31153     p->pRight = rowSetNDeepTree(&pList, iDepth);
31154   }
31155   return p;
31156 }
31157
31158 /*
31159 ** Convert the list in p->pEntry into a sorted list if it is not
31160 ** sorted already.  If there is a binary tree on p->pTree, then
31161 ** convert it into a list too and merge it into the p->pEntry list.
31162 */
31163 static void rowSetToList(RowSet *p){
31164   if( !p->isSorted ){
31165     rowSetSort(p);
31166   }
31167   if( p->pTree ){
31168     struct RowSetEntry *pHead, *pTail;
31169     rowSetTreeToList(p->pTree, &pHead, &pTail);
31170     p->pTree = 0;
31171     p->pEntry = rowSetMerge(p->pEntry, pHead);
31172   }
31173 }
31174
31175 /*
31176 ** Extract the smallest element from the RowSet.
31177 ** Write the element into *pRowid.  Return 1 on success.  Return
31178 ** 0 if the RowSet is already empty.
31179 **
31180 ** After this routine has been called, the sqlite3RowSetInsert()
31181 ** routine may not be called again.  
31182 */
31183 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
31184   rowSetToList(p);
31185   if( p->pEntry ){
31186     *pRowid = p->pEntry->v;
31187     p->pEntry = p->pEntry->pRight;
31188     if( p->pEntry==0 ){
31189       sqlite3RowSetClear(p);
31190     }
31191     return 1;
31192   }else{
31193     return 0;
31194   }
31195 }
31196
31197 /*
31198 ** Check to see if element iRowid was inserted into the the rowset as
31199 ** part of any insert batch prior to iBatch.  Return 1 or 0.
31200 */
31201 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
31202   struct RowSetEntry *p;
31203   if( iBatch!=pRowSet->iBatch ){
31204     if( pRowSet->pEntry ){
31205       rowSetToList(pRowSet);
31206       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
31207       pRowSet->pEntry = 0;
31208       pRowSet->pLast = 0;
31209     }
31210     pRowSet->iBatch = iBatch;
31211   }
31212   p = pRowSet->pTree;
31213   while( p ){
31214     if( p->v<iRowid ){
31215       p = p->pRight;
31216     }else if( p->v>iRowid ){
31217       p = p->pLeft;
31218     }else{
31219       return 1;
31220     }
31221   }
31222   return 0;
31223 }
31224
31225 /************** End of rowset.c **********************************************/
31226 /************** Begin file pager.c *******************************************/
31227 /*
31228 ** 2001 September 15
31229 **
31230 ** The author disclaims copyright to this source code.  In place of
31231 ** a legal notice, here is a blessing:
31232 **
31233 **    May you do good and not evil.
31234 **    May you find forgiveness for yourself and forgive others.
31235 **    May you share freely, never taking more than you give.
31236 **
31237 *************************************************************************
31238 ** This is the implementation of the page cache subsystem or "pager".
31239 ** 
31240 ** The pager is used to access a database disk file.  It implements
31241 ** atomic commit and rollback through the use of a journal file that
31242 ** is separate from the database file.  The pager also implements file
31243 ** locking to prevent two processes from writing the same database
31244 ** file simultaneously, or one process from reading the database while
31245 ** another is writing.
31246 */
31247 #ifndef SQLITE_OMIT_DISKIO
31248
31249 /*
31250 ** Macros for troubleshooting.  Normally turned off
31251 */
31252 #if 0
31253 int sqlite3PagerTrace=1;  /* True to enable tracing */
31254 #define sqlite3DebugPrintf printf
31255 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
31256 #else
31257 #define PAGERTRACE(X)
31258 #endif
31259
31260 /*
31261 ** The following two macros are used within the PAGERTRACE() macros above
31262 ** to print out file-descriptors. 
31263 **
31264 ** PAGERID() takes a pointer to a Pager struct as its argument. The
31265 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
31266 ** struct as its argument.
31267 */
31268 #define PAGERID(p) ((int)(p->fd))
31269 #define FILEHANDLEID(fd) ((int)fd)
31270
31271 /*
31272 ** The page cache as a whole is always in one of the following
31273 ** states:
31274 **
31275 **   PAGER_UNLOCK        The page cache is not currently reading or 
31276 **                       writing the database file.  There is no
31277 **                       data held in memory.  This is the initial
31278 **                       state.
31279 **
31280 **   PAGER_SHARED        The page cache is reading the database.
31281 **                       Writing is not permitted.  There can be
31282 **                       multiple readers accessing the same database
31283 **                       file at the same time.
31284 **
31285 **   PAGER_RESERVED      This process has reserved the database for writing
31286 **                       but has not yet made any changes.  Only one process
31287 **                       at a time can reserve the database.  The original
31288 **                       database file has not been modified so other
31289 **                       processes may still be reading the on-disk
31290 **                       database file.
31291 **
31292 **   PAGER_EXCLUSIVE     The page cache is writing the database.
31293 **                       Access is exclusive.  No other processes or
31294 **                       threads can be reading or writing while one
31295 **                       process is writing.
31296 **
31297 **   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
31298 **                       after all dirty pages have been written to the
31299 **                       database file and the file has been synced to
31300 **                       disk. All that remains to do is to remove or
31301 **                       truncate the journal file and the transaction 
31302 **                       will be committed.
31303 **
31304 ** The page cache comes up in PAGER_UNLOCK.  The first time a
31305 ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
31306 ** After all pages have been released using sqlite_page_unref(),
31307 ** the state transitions back to PAGER_UNLOCK.  The first time
31308 ** that sqlite3PagerWrite() is called, the state transitions to
31309 ** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
31310 ** called on an outstanding page which means that the pager must
31311 ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
31312 ** PAGER_RESERVED means that there is an open rollback journal.
31313 ** The transition to PAGER_EXCLUSIVE occurs before any changes
31314 ** are made to the database file, though writes to the rollback
31315 ** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
31316 ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
31317 ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
31318 */
31319 #define PAGER_UNLOCK      0
31320 #define PAGER_SHARED      1   /* same as SHARED_LOCK */
31321 #define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
31322 #define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
31323 #define PAGER_SYNCED      5
31324
31325 /*
31326 ** A macro used for invoking the codec if there is one
31327 */
31328 #ifdef SQLITE_HAS_CODEC
31329 # define CODEC1(P,D,N,X,E) \
31330     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
31331 # define CODEC2(P,D,N,X,E,O) \
31332     if( P->xCodec==0 ){ O=(char*)D; }else \
31333     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
31334 #else
31335 # define CODEC1(P,D,N,X,E)   /* NO-OP */
31336 # define CODEC2(P,D,N,X,E,O) O=(char*)D
31337 #endif
31338
31339 /*
31340 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
31341 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
31342 ** This could conceivably cause corruption following a power failure on
31343 ** such a system. This is currently an undocumented limit.
31344 */
31345 #define MAX_SECTOR_SIZE 0x10000
31346
31347 /*
31348 ** An instance of the following structure is allocated for each active
31349 ** savepoint and statement transaction in the system. All such structures
31350 ** are stored in the Pager.aSavepoint[] array, which is allocated and
31351 ** resized using sqlite3Realloc().
31352 **
31353 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
31354 ** set to 0. If a journal-header is written into the main journal while
31355 ** the savepoint is active, then iHdrOffset is set to the byte offset 
31356 ** immediately following the last journal record written into the main
31357 ** journal before the journal-header. This is required during savepoint
31358 ** rollback (see pagerPlaybackSavepoint()).
31359 */
31360 typedef struct PagerSavepoint PagerSavepoint;
31361 struct PagerSavepoint {
31362   i64 iOffset;                 /* Starting offset in main journal */
31363   i64 iHdrOffset;              /* See above */
31364   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
31365   Pgno nOrig;                  /* Original number of pages in file */
31366   Pgno iSubRec;                /* Index of first record in sub-journal */
31367 };
31368
31369 /*
31370 ** A open page cache is an instance of the following structure.
31371 **
31372 ** errCode
31373 **
31374 **   Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
31375 **   or SQLITE_FULL. Once one of the first three errors occurs, it persists
31376 **   and is returned as the result of every major pager API call.  The
31377 **   SQLITE_FULL return code is slightly different. It persists only until the
31378 **   next successful rollback is performed on the pager cache. Also,
31379 **   SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
31380 **   APIs, they may still be used successfully.
31381 **
31382 ** dbSizeValid, dbSize, dbOrigSize, dbFileSize
31383 **
31384 **   Managing the size of the database file in pages is a little complicated.
31385 **   The variable Pager.dbSize contains the number of pages that the database
31386 **   image currently contains. As the database image grows or shrinks this
31387 **   variable is updated. The variable Pager.dbFileSize contains the number
31388 **   of pages in the database file. This may be different from Pager.dbSize
31389 **   if some pages have been appended to the database image but not yet written
31390 **   out from the cache to the actual file on disk. Or if the image has been
31391 **   truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
31392 **   contains the number of pages in the database image when the current
31393 **   transaction was opened. The contents of all three of these variables is
31394 **   only guaranteed to be correct if the boolean Pager.dbSizeValid is true.
31395 **
31396 **   TODO: Under what conditions is dbSizeValid set? Cleared?
31397 **
31398 ** changeCountDone
31399 **
31400 **   This boolean variable is used to make sure that the change-counter 
31401 **   (the 4-byte header field at byte offset 24 of the database file) is 
31402 **   not updated more often than necessary. 
31403 **
31404 **   It is set to true when the change-counter field is updated, which 
31405 **   can only happen if an exclusive lock is held on the database file.
31406 **   It is cleared (set to false) whenever an exclusive lock is 
31407 **   relinquished on the database file. Each time a transaction is committed,
31408 **   The changeCountDone flag is inspected. If it is true, the work of
31409 **   updating the change-counter is omitted for the current transaction.
31410 **
31411 **   This mechanism means that when running in exclusive mode, a connection 
31412 **   need only update the change-counter once, for the first transaction
31413 **   committed.
31414 **
31415 ** dbModified
31416 **
31417 **   The dbModified flag is set whenever a database page is dirtied.
31418 **   It is cleared at the end of each transaction.
31419 **
31420 **   It is used when committing or otherwise ending a transaction. If
31421 **   the dbModified flag is clear then less work has to be done.
31422 **
31423 ** journalStarted
31424 **
31425 **   This flag is set whenever the the main journal is synced. 
31426 **
31427 **   The point of this flag is that it must be set after the 
31428 **   first journal header in a journal file has been synced to disk.
31429 **   After this has happened, new pages appended to the database 
31430 **   do not need the PGHDR_NEED_SYNC flag set, as they do not need
31431 **   to wait for a journal sync before they can be written out to
31432 **   the database file (see function pager_write()).
31433 **   
31434 ** setMaster
31435 **
31436 **   This variable is used to ensure that the master journal file name
31437 **   (if any) is only written into the journal file once.
31438 **
31439 **   When committing a transaction, the master journal file name (if any)
31440 **   may be written into the journal file while the pager is still in
31441 **   PAGER_RESERVED state (see CommitPhaseOne() for the action). It
31442 **   then attempts to upgrade to an exclusive lock. If this attempt
31443 **   fails, then SQLITE_BUSY may be returned to the user and the user
31444 **   may attempt to commit the transaction again later (calling
31445 **   CommitPhaseOne() again). This flag is used to ensure that the 
31446 **   master journal name is only written to the journal file the first
31447 **   time CommitPhaseOne() is called.
31448 **
31449 ** doNotSync
31450 **
31451 **   This variable is set and cleared by sqlite3PagerWrite().
31452 **
31453 ** needSync
31454 **
31455 **   TODO: It might be easier to set this variable in writeJournalHdr()
31456 **   and writeMasterJournal() only. Change its meaning to "unsynced data
31457 **   has been written to the journal".
31458 **
31459 ** subjInMemory
31460 **
31461 **   This is a boolean variable. If true, then any required sub-journal
31462 **   is opened as an in-memory journal file. If false, then in-memory
31463 **   sub-journals are only used for in-memory pager files.
31464 */
31465 struct Pager {
31466   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
31467   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
31468   u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
31469   u8 useJournal;              /* Use a rollback journal on this file */
31470   u8 noReadlock;              /* Do not bother to obtain readlocks */
31471   u8 noSync;                  /* Do not sync the journal if true */
31472   u8 fullSync;                /* Do extra syncs of the journal for robustness */
31473   u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
31474   u8 tempFile;                /* zFilename is a temporary file */
31475   u8 readOnly;                /* True for a read-only database */
31476   u8 memDb;                   /* True to inhibit all file I/O */
31477
31478   /* The following block contains those class members that are dynamically
31479   ** modified during normal operations. The other variables in this structure
31480   ** are either constant throughout the lifetime of the pager, or else
31481   ** used to store configuration parameters that affect the way the pager 
31482   ** operates.
31483   **
31484   ** The 'state' variable is described in more detail along with the
31485   ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the
31486   ** other variables in this block are described in the comment directly 
31487   ** above this class definition.
31488   */
31489   u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
31490   u8 dbModified;              /* True if there are any changes to the Db */
31491   u8 needSync;                /* True if an fsync() is needed on the journal */
31492   u8 journalStarted;          /* True if header of journal is synced */
31493   u8 changeCountDone;         /* Set after incrementing the change-counter */
31494   u8 setMaster;               /* True if a m-j name has been written to jrnl */
31495   u8 doNotSync;               /* Boolean. While true, do not spill the cache */
31496   u8 dbSizeValid;             /* Set when dbSize is correct */
31497   u8 subjInMemory;            /* True to use in-memory sub-journals */
31498   Pgno dbSize;                /* Number of pages in the database */
31499   Pgno dbOrigSize;            /* dbSize before the current transaction */
31500   Pgno dbFileSize;            /* Number of pages in the database file */
31501   int errCode;                /* One of several kinds of errors */
31502   int nRec;                   /* Pages journalled since last j-header written */
31503   u32 cksumInit;              /* Quasi-random value added to every checksum */
31504   u32 nSubRec;                /* Number of records written to sub-journal */
31505   Bitvec *pInJournal;         /* One bit for each page in the database file */
31506   sqlite3_file *fd;           /* File descriptor for database */
31507   sqlite3_file *jfd;          /* File descriptor for main journal */
31508   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
31509   i64 journalOff;             /* Current write offset in the journal file */
31510   i64 journalHdr;             /* Byte offset to previous journal header */
31511   PagerSavepoint *aSavepoint; /* Array of active savepoints */
31512   int nSavepoint;             /* Number of elements in aSavepoint[] */
31513   char dbFileVers[16];        /* Changes whenever database file changes */
31514   u32 sectorSize;             /* Assumed sector size during rollback */
31515
31516   u16 nExtra;                 /* Add this many bytes to each in-memory page */
31517   i16 nReserve;               /* Number of unused bytes at end of each page */
31518   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
31519   int pageSize;               /* Number of bytes in a page */
31520   Pgno mxPgno;                /* Maximum allowed size of the database */
31521   char *zFilename;            /* Name of the database file */
31522   char *zJournal;             /* Name of the journal file */
31523   int (*xBusyHandler)(void*); /* Function to call when busy */
31524   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
31525 #ifdef SQLITE_TEST
31526   int nHit, nMiss;            /* Cache hits and missing */
31527   int nRead, nWrite;          /* Database pages read/written */
31528 #endif
31529   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
31530 #ifdef SQLITE_HAS_CODEC
31531   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
31532   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
31533   void (*xCodecFree)(void*);             /* Destructor for the codec */
31534   void *pCodec;               /* First argument to xCodec... methods */
31535 #endif
31536   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
31537   i64 journalSizeLimit;       /* Size limit for persistent journal files */
31538   PCache *pPCache;            /* Pointer to page cache object */
31539   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
31540 };
31541
31542 /*
31543 ** The following global variables hold counters used for
31544 ** testing purposes only.  These variables do not exist in
31545 ** a non-testing build.  These variables are not thread-safe.
31546 */
31547 #ifdef SQLITE_TEST
31548 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
31549 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
31550 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
31551 # define PAGER_INCR(v)  v++
31552 #else
31553 # define PAGER_INCR(v)
31554 #endif
31555
31556
31557
31558 /*
31559 ** Journal files begin with the following magic string.  The data
31560 ** was obtained from /dev/random.  It is used only as a sanity check.
31561 **
31562 ** Since version 2.8.0, the journal format contains additional sanity
31563 ** checking information.  If the power fails while the journal is being
31564 ** written, semi-random garbage data might appear in the journal
31565 ** file after power is restored.  If an attempt is then made
31566 ** to roll the journal back, the database could be corrupted.  The additional
31567 ** sanity checking data is an attempt to discover the garbage in the
31568 ** journal and ignore it.
31569 **
31570 ** The sanity checking information for the new journal format consists
31571 ** of a 32-bit checksum on each page of data.  The checksum covers both
31572 ** the page number and the pPager->pageSize bytes of data for the page.
31573 ** This cksum is initialized to a 32-bit random value that appears in the
31574 ** journal file right after the header.  The random initializer is important,
31575 ** because garbage data that appears at the end of a journal is likely
31576 ** data that was once in other files that have now been deleted.  If the
31577 ** garbage data came from an obsolete journal file, the checksums might
31578 ** be correct.  But by initializing the checksum to random value which
31579 ** is different for every journal, we minimize that risk.
31580 */
31581 static const unsigned char aJournalMagic[] = {
31582   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
31583 };
31584
31585 /*
31586 ** The size of the of each page record in the journal is given by
31587 ** the following macro.
31588 */
31589 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
31590
31591 /*
31592 ** The journal header size for this pager. This is usually the same 
31593 ** size as a single disk sector. See also setSectorSize().
31594 */
31595 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
31596
31597 /*
31598 ** The macro MEMDB is true if we are dealing with an in-memory database.
31599 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
31600 ** the value of MEMDB will be a constant and the compiler will optimize
31601 ** out code that would never execute.
31602 */
31603 #ifdef SQLITE_OMIT_MEMORYDB
31604 # define MEMDB 0
31605 #else
31606 # define MEMDB pPager->memDb
31607 #endif
31608
31609 /*
31610 ** The maximum legal page number is (2^31 - 1).
31611 */
31612 #define PAGER_MAX_PGNO 2147483647
31613
31614 #ifndef NDEBUG 
31615 /*
31616 ** Usage:
31617 **
31618 **   assert( assert_pager_state(pPager) );
31619 */
31620 static int assert_pager_state(Pager *pPager){
31621
31622   /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */
31623   assert( pPager->tempFile==0 || pPager->state>=PAGER_EXCLUSIVE );
31624
31625   /* The changeCountDone flag is always set for temp-files */
31626   assert( pPager->tempFile==0 || pPager->changeCountDone );
31627
31628   return 1;
31629 }
31630 #endif
31631
31632 /*
31633 ** Return true if it is necessary to write page *pPg into the sub-journal.
31634 ** A page needs to be written into the sub-journal if there exists one
31635 ** or more open savepoints for which:
31636 **
31637 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
31638 **   * The bit corresponding to the page-number is not set in
31639 **     PagerSavepoint.pInSavepoint.
31640 */
31641 static int subjRequiresPage(PgHdr *pPg){
31642   Pgno pgno = pPg->pgno;
31643   Pager *pPager = pPg->pPager;
31644   int i;
31645   for(i=0; i<pPager->nSavepoint; i++){
31646     PagerSavepoint *p = &pPager->aSavepoint[i];
31647     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
31648       return 1;
31649     }
31650   }
31651   return 0;
31652 }
31653
31654 /*
31655 ** Return true if the page is already in the journal file.
31656 */
31657 static int pageInJournal(PgHdr *pPg){
31658   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
31659 }
31660
31661 /*
31662 ** Read a 32-bit integer from the given file descriptor.  Store the integer
31663 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
31664 ** error code is something goes wrong.
31665 **
31666 ** All values are stored on disk as big-endian.
31667 */
31668 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
31669   unsigned char ac[4];
31670   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
31671   if( rc==SQLITE_OK ){
31672     *pRes = sqlite3Get4byte(ac);
31673   }
31674   return rc;
31675 }
31676
31677 /*
31678 ** Write a 32-bit integer into a string buffer in big-endian byte order.
31679 */
31680 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
31681
31682 /*
31683 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
31684 ** on success or an error code is something goes wrong.
31685 */
31686 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
31687   char ac[4];
31688   put32bits(ac, val);
31689   return sqlite3OsWrite(fd, ac, 4, offset);
31690 }
31691
31692 /*
31693 ** The argument to this macro is a file descriptor (type sqlite3_file*).
31694 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
31695 **
31696 ** This is so that expressions can be written as:
31697 **
31698 **   if( isOpen(pPager->jfd) ){ ...
31699 **
31700 ** instead of
31701 **
31702 **   if( pPager->jfd->pMethods ){ ...
31703 */
31704 #define isOpen(pFd) ((pFd)->pMethods)
31705
31706 /*
31707 ** If file pFd is open, call sqlite3OsUnlock() on it.
31708 */
31709 static int osUnlock(sqlite3_file *pFd, int eLock){
31710   if( !isOpen(pFd) ){
31711     return SQLITE_OK;
31712   }
31713   return sqlite3OsUnlock(pFd, eLock);
31714 }
31715
31716 /*
31717 ** This function determines whether or not the atomic-write optimization
31718 ** can be used with this pager. The optimization can be used if:
31719 **
31720 **  (a) the value returned by OsDeviceCharacteristics() indicates that
31721 **      a database page may be written atomically, and
31722 **  (b) the value returned by OsSectorSize() is less than or equal
31723 **      to the page size.
31724 **
31725 ** The optimization is also always enabled for temporary files. It is
31726 ** an error to call this function if pPager is opened on an in-memory
31727 ** database.
31728 **
31729 ** If the optimization cannot be used, 0 is returned. If it can be used,
31730 ** then the value returned is the size of the journal file when it
31731 ** contains rollback data for exactly one page.
31732 */
31733 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
31734 static int jrnlBufferSize(Pager *pPager){
31735   assert( !MEMDB );
31736   if( !pPager->tempFile ){
31737     int dc;                           /* Device characteristics */
31738     int nSector;                      /* Sector size */
31739     int szPage;                       /* Page size */
31740
31741     assert( isOpen(pPager->fd) );
31742     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
31743     nSector = pPager->sectorSize;
31744     szPage = pPager->pageSize;
31745
31746     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
31747     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
31748     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
31749       return 0;
31750     }
31751   }
31752
31753   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
31754 }
31755 #endif
31756
31757 /*
31758 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
31759 ** on the cache using a hash function.  This is used for testing
31760 ** and debugging only.
31761 */
31762 #ifdef SQLITE_CHECK_PAGES
31763 /*
31764 ** Return a 32-bit hash of the page data for pPage.
31765 */
31766 static u32 pager_datahash(int nByte, unsigned char *pData){
31767   u32 hash = 0;
31768   int i;
31769   for(i=0; i<nByte; i++){
31770     hash = (hash*1039) + pData[i];
31771   }
31772   return hash;
31773 }
31774 static u32 pager_pagehash(PgHdr *pPage){
31775   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
31776 }
31777 static void pager_set_pagehash(PgHdr *pPage){
31778   pPage->pageHash = pager_pagehash(pPage);
31779 }
31780
31781 /*
31782 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
31783 ** is defined, and NDEBUG is not defined, an assert() statement checks
31784 ** that the page is either dirty or still matches the calculated page-hash.
31785 */
31786 #define CHECK_PAGE(x) checkPage(x)
31787 static void checkPage(PgHdr *pPg){
31788   Pager *pPager = pPg->pPager;
31789   assert( !pPg->pageHash || pPager->errCode
31790       || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
31791 }
31792
31793 #else
31794 #define pager_datahash(X,Y)  0
31795 #define pager_pagehash(X)  0
31796 #define CHECK_PAGE(x)
31797 #endif  /* SQLITE_CHECK_PAGES */
31798
31799 /*
31800 ** When this is called the journal file for pager pPager must be open.
31801 ** This function attempts to read a master journal file name from the 
31802 ** end of the file and, if successful, copies it into memory supplied 
31803 ** by the caller. See comments above writeMasterJournal() for the format
31804 ** used to store a master journal file name at the end of a journal file.
31805 **
31806 ** zMaster must point to a buffer of at least nMaster bytes allocated by
31807 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
31808 ** enough space to write the master journal name). If the master journal
31809 ** name in the journal is longer than nMaster bytes (including a
31810 ** nul-terminator), then this is handled as if no master journal name
31811 ** were present in the journal.
31812 **
31813 ** If a master journal file name is present at the end of the journal
31814 ** file, then it is copied into the buffer pointed to by zMaster. A
31815 ** nul-terminator byte is appended to the buffer following the master
31816 ** journal file name.
31817 **
31818 ** If it is determined that no master journal file name is present 
31819 ** zMaster[0] is set to 0 and SQLITE_OK returned.
31820 **
31821 ** If an error occurs while reading from the journal file, an SQLite
31822 ** error code is returned.
31823 */
31824 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
31825   int rc;                    /* Return code */
31826   u32 len;                   /* Length in bytes of master journal name */
31827   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
31828   u32 cksum;                 /* MJ checksum value read from journal */
31829   u32 u;                     /* Unsigned loop counter */
31830   unsigned char aMagic[8];   /* A buffer to hold the magic header */
31831   zMaster[0] = '\0';
31832
31833   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
31834    || szJ<16
31835    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
31836    || len>=nMaster 
31837    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
31838    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
31839    || memcmp(aMagic, aJournalMagic, 8)
31840    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
31841   ){
31842     return rc;
31843   }
31844
31845   /* See if the checksum matches the master journal name */
31846   for(u=0; u<len; u++){
31847     cksum -= zMaster[u];
31848   }
31849   if( cksum ){
31850     /* If the checksum doesn't add up, then one or more of the disk sectors
31851     ** containing the master journal filename is corrupted. This means
31852     ** definitely roll back, so just return SQLITE_OK and report a (nul)
31853     ** master-journal filename.
31854     */
31855     len = 0;
31856   }
31857   zMaster[len] = '\0';
31858    
31859   return SQLITE_OK;
31860 }
31861
31862 /*
31863 ** Return the offset of the sector boundary at or immediately 
31864 ** following the value in pPager->journalOff, assuming a sector 
31865 ** size of pPager->sectorSize bytes.
31866 **
31867 ** i.e for a sector size of 512:
31868 **
31869 **   Pager.journalOff          Return value
31870 **   ---------------------------------------
31871 **   0                         0
31872 **   512                       512
31873 **   100                       512
31874 **   2000                      2048
31875 ** 
31876 */
31877 static i64 journalHdrOffset(Pager *pPager){
31878   i64 offset = 0;
31879   i64 c = pPager->journalOff;
31880   if( c ){
31881     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
31882   }
31883   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
31884   assert( offset>=c );
31885   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
31886   return offset;
31887 }
31888
31889 /*
31890 ** The journal file must be open when this function is called.
31891 **
31892 ** This function is a no-op if the journal file has not been written to
31893 ** within the current transaction (i.e. if Pager.journalOff==0).
31894 **
31895 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
31896 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
31897 ** zero the 28-byte header at the start of the journal file. In either case, 
31898 ** if the pager is not in no-sync mode, sync the journal file immediately 
31899 ** after writing or truncating it.
31900 **
31901 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
31902 ** following the truncation or zeroing described above the size of the 
31903 ** journal file in bytes is larger than this value, then truncate the
31904 ** journal file to Pager.journalSizeLimit bytes. The journal file does
31905 ** not need to be synced following this operation.
31906 **
31907 ** If an IO error occurs, abandon processing and return the IO error code.
31908 ** Otherwise, return SQLITE_OK.
31909 */
31910 static int zeroJournalHdr(Pager *pPager, int doTruncate){
31911   int rc = SQLITE_OK;                               /* Return code */
31912   assert( isOpen(pPager->jfd) );
31913   if( pPager->journalOff ){
31914     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
31915
31916     IOTRACE(("JZEROHDR %p\n", pPager))
31917     if( doTruncate || iLimit==0 ){
31918       rc = sqlite3OsTruncate(pPager->jfd, 0);
31919     }else{
31920       static const char zeroHdr[28] = {0};
31921       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
31922     }
31923     if( rc==SQLITE_OK && !pPager->noSync ){
31924       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
31925     }
31926
31927     /* At this point the transaction is committed but the write lock 
31928     ** is still held on the file. If there is a size limit configured for 
31929     ** the persistent journal and the journal file currently consumes more
31930     ** space than that limit allows for, truncate it now. There is no need
31931     ** to sync the file following this operation.
31932     */
31933     if( rc==SQLITE_OK && iLimit>0 ){
31934       i64 sz;
31935       rc = sqlite3OsFileSize(pPager->jfd, &sz);
31936       if( rc==SQLITE_OK && sz>iLimit ){
31937         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
31938       }
31939     }
31940   }
31941   return rc;
31942 }
31943
31944 /*
31945 ** The journal file must be open when this routine is called. A journal
31946 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
31947 ** current location.
31948 **
31949 ** The format for the journal header is as follows:
31950 ** - 8 bytes: Magic identifying journal format.
31951 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
31952 ** - 4 bytes: Random number used for page hash.
31953 ** - 4 bytes: Initial database page count.
31954 ** - 4 bytes: Sector size used by the process that wrote this journal.
31955 ** - 4 bytes: Database page size.
31956 ** 
31957 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
31958 */
31959 static int writeJournalHdr(Pager *pPager){
31960   int rc = SQLITE_OK;                 /* Return code */
31961   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
31962   u32 nHeader = pPager->pageSize;     /* Size of buffer pointed to by zHeader */
31963   u32 nWrite;                         /* Bytes of header sector written */
31964   int ii;                             /* Loop counter */
31965
31966   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
31967
31968   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
31969     nHeader = JOURNAL_HDR_SZ(pPager);
31970   }
31971
31972   /* If there are active savepoints and any of them were created 
31973   ** since the most recent journal header was written, update the 
31974   ** PagerSavepoint.iHdrOffset fields now.
31975   */
31976   for(ii=0; ii<pPager->nSavepoint; ii++){
31977     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
31978       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
31979     }
31980   }
31981
31982   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
31983
31984   /* 
31985   ** Write the nRec Field - the number of page records that follow this
31986   ** journal header. Normally, zero is written to this value at this time.
31987   ** After the records are added to the journal (and the journal synced, 
31988   ** if in full-sync mode), the zero is overwritten with the true number
31989   ** of records (see syncJournal()).
31990   **
31991   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
31992   ** reading the journal this value tells SQLite to assume that the
31993   ** rest of the journal file contains valid page records. This assumption
31994   ** is dangerous, as if a failure occurred whilst writing to the journal
31995   ** file it may contain some garbage data. There are two scenarios
31996   ** where this risk can be ignored:
31997   **
31998   **   * When the pager is in no-sync mode. Corruption can follow a
31999   **     power failure in this case anyway.
32000   **
32001   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
32002   **     that garbage data is never appended to the journal file.
32003   */
32004   assert( isOpen(pPager->fd) || pPager->noSync );
32005   if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
32006    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
32007   ){
32008     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
32009     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
32010   }else{
32011     memset(zHeader, 0, sizeof(aJournalMagic)+4);
32012   }
32013
32014   /* The random check-hash initialiser */ 
32015   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
32016   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
32017   /* The initial database size */
32018   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
32019   /* The assumed sector size for this process */
32020   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
32021
32022   /* The page size */
32023   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
32024
32025   /* Initializing the tail of the buffer is not necessary.  Everything
32026   ** works find if the following memset() is omitted.  But initializing
32027   ** the memory prevents valgrind from complaining, so we are willing to
32028   ** take the performance hit.
32029   */
32030   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
32031          nHeader-(sizeof(aJournalMagic)+20));
32032
32033   /* In theory, it is only necessary to write the 28 bytes that the 
32034   ** journal header consumes to the journal file here. Then increment the 
32035   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
32036   ** record is written to the following sector (leaving a gap in the file
32037   ** that will be implicitly filled in by the OS).
32038   **
32039   ** However it has been discovered that on some systems this pattern can 
32040   ** be significantly slower than contiguously writing data to the file,
32041   ** even if that means explicitly writing data to the block of 
32042   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
32043   ** is done. 
32044   **
32045   ** The loop is required here in case the sector-size is larger than the 
32046   ** database page size. Since the zHeader buffer is only Pager.pageSize
32047   ** bytes in size, more than one call to sqlite3OsWrite() may be required
32048   ** to populate the entire journal header sector.
32049   */ 
32050   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
32051     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
32052     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
32053     pPager->journalOff += nHeader;
32054   }
32055
32056   return rc;
32057 }
32058
32059 /*
32060 ** The journal file must be open when this is called. A journal header file
32061 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
32062 ** file. The current location in the journal file is given by
32063 ** pPager->journalOff. See comments above function writeJournalHdr() for
32064 ** a description of the journal header format.
32065 **
32066 ** If the header is read successfully, *pNRec is set to the number of
32067 ** page records following this header and *pDbSize is set to the size of the
32068 ** database before the transaction began, in pages. Also, pPager->cksumInit
32069 ** is set to the value read from the journal header. SQLITE_OK is returned
32070 ** in this case.
32071 **
32072 ** If the journal header file appears to be corrupted, SQLITE_DONE is
32073 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
32074 ** cannot be read from the journal file an error code is returned.
32075 */
32076 static int readJournalHdr(
32077   Pager *pPager,               /* Pager object */
32078   int isHot,
32079   i64 journalSize,             /* Size of the open journal file in bytes */
32080   u32 *pNRec,                  /* OUT: Value read from the nRec field */
32081   u32 *pDbSize                 /* OUT: Value of original database size field */
32082 ){
32083   int rc;                      /* Return code */
32084   unsigned char aMagic[8];     /* A buffer to hold the magic header */
32085   i64 iHdrOff;                 /* Offset of journal header being read */
32086
32087   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
32088
32089   /* Advance Pager.journalOff to the start of the next sector. If the
32090   ** journal file is too small for there to be a header stored at this
32091   ** point, return SQLITE_DONE.
32092   */
32093   pPager->journalOff = journalHdrOffset(pPager);
32094   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
32095     return SQLITE_DONE;
32096   }
32097   iHdrOff = pPager->journalOff;
32098
32099   /* Read in the first 8 bytes of the journal header. If they do not match
32100   ** the  magic string found at the start of each journal header, return
32101   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
32102   ** proceed.
32103   */
32104   if( isHot || iHdrOff!=pPager->journalHdr ){
32105     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
32106     if( rc ){
32107       return rc;
32108     }
32109     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
32110       return SQLITE_DONE;
32111     }
32112   }
32113
32114   /* Read the first three 32-bit fields of the journal header: The nRec
32115   ** field, the checksum-initializer and the database size at the start
32116   ** of the transaction. Return an error code if anything goes wrong.
32117   */
32118   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
32119    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
32120    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
32121   ){
32122     return rc;
32123   }
32124
32125   if( pPager->journalOff==0 ){
32126     u32 iPageSize;               /* Page-size field of journal header */
32127     u32 iSectorSize;             /* Sector-size field of journal header */
32128     u16 iPageSize16;             /* Copy of iPageSize in 16-bit variable */
32129
32130     /* Read the page-size and sector-size journal header fields. */
32131     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
32132      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
32133     ){
32134       return rc;
32135     }
32136
32137     /* Check that the values read from the page-size and sector-size fields
32138     ** are within range. To be 'in range', both values need to be a power
32139     ** of two greater than or equal to 512 or 32, and not greater than their 
32140     ** respective compile time maximum limits.
32141     */
32142     if( iPageSize<512                  || iSectorSize<32
32143      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
32144      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
32145     ){
32146       /* If the either the page-size or sector-size in the journal-header is 
32147       ** invalid, then the process that wrote the journal-header must have 
32148       ** crashed before the header was synced. In this case stop reading 
32149       ** the journal file here.
32150       */
32151       return SQLITE_DONE;
32152     }
32153
32154     /* Update the page-size to match the value read from the journal. 
32155     ** Use a testcase() macro to make sure that malloc failure within 
32156     ** PagerSetPagesize() is tested.
32157     */
32158     iPageSize16 = (u16)iPageSize;
32159     rc = sqlite3PagerSetPagesize(pPager, &iPageSize16, -1);
32160     testcase( rc!=SQLITE_OK );
32161     assert( rc!=SQLITE_OK || iPageSize16==(u16)iPageSize );
32162
32163     /* Update the assumed sector-size to match the value used by 
32164     ** the process that created this journal. If this journal was
32165     ** created by a process other than this one, then this routine
32166     ** is being called from within pager_playback(). The local value
32167     ** of Pager.sectorSize is restored at the end of that routine.
32168     */
32169     pPager->sectorSize = iSectorSize;
32170   }
32171
32172   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
32173   return rc;
32174 }
32175
32176
32177 /*
32178 ** Write the supplied master journal name into the journal file for pager
32179 ** pPager at the current location. The master journal name must be the last
32180 ** thing written to a journal file. If the pager is in full-sync mode, the
32181 ** journal file descriptor is advanced to the next sector boundary before
32182 ** anything is written. The format is:
32183 **
32184 **   + 4 bytes: PAGER_MJ_PGNO.
32185 **   + N bytes: Master journal filename in utf-8.
32186 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
32187 **   + 4 bytes: Master journal name checksum.
32188 **   + 8 bytes: aJournalMagic[].
32189 **
32190 ** The master journal page checksum is the sum of the bytes in the master
32191 ** journal name, where each byte is interpreted as a signed 8-bit integer.
32192 **
32193 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
32194 ** this call is a no-op.
32195 */
32196 static int writeMasterJournal(Pager *pPager, const char *zMaster){
32197   int rc;                          /* Return code */
32198   int nMaster;                     /* Length of string zMaster */
32199   i64 iHdrOff;                     /* Offset of header in journal file */
32200   i64 jrnlSize;                    /* Size of journal file on disk */
32201   u32 cksum = 0;                   /* Checksum of string zMaster */
32202
32203   if( !zMaster || pPager->setMaster
32204    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
32205    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
32206   ){
32207     return SQLITE_OK;
32208   }
32209   pPager->setMaster = 1;
32210   assert( isOpen(pPager->jfd) );
32211
32212   /* Calculate the length in bytes and the checksum of zMaster */
32213   for(nMaster=0; zMaster[nMaster]; nMaster++){
32214     cksum += zMaster[nMaster];
32215   }
32216
32217   /* If in full-sync mode, advance to the next disk sector before writing
32218   ** the master journal name. This is in case the previous page written to
32219   ** the journal has already been synced.
32220   */
32221   if( pPager->fullSync ){
32222     pPager->journalOff = journalHdrOffset(pPager);
32223   }
32224   iHdrOff = pPager->journalOff;
32225
32226   /* Write the master journal data to the end of the journal file. If
32227   ** an error occurs, return the error code to the caller.
32228   */
32229   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
32230    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
32231    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
32232    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
32233    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
32234   ){
32235     return rc;
32236   }
32237   pPager->journalOff += (nMaster+20);
32238   pPager->needSync = !pPager->noSync;
32239
32240   /* If the pager is in peristent-journal mode, then the physical 
32241   ** journal-file may extend past the end of the master-journal name
32242   ** and 8 bytes of magic data just written to the file. This is 
32243   ** dangerous because the code to rollback a hot-journal file
32244   ** will not be able to find the master-journal name to determine 
32245   ** whether or not the journal is hot. 
32246   **
32247   ** Easiest thing to do in this scenario is to truncate the journal 
32248   ** file to the required size.
32249   */ 
32250   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
32251    && jrnlSize>pPager->journalOff
32252   ){
32253     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
32254   }
32255   return rc;
32256 }
32257
32258 /*
32259 ** Find a page in the hash table given its page number. Return
32260 ** a pointer to the page or NULL if the requested page is not 
32261 ** already in memory.
32262 */
32263 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
32264   PgHdr *p;                         /* Return value */
32265
32266   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
32267   ** fail, since no attempt to allocate dynamic memory will be made.
32268   */
32269   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
32270   return p;
32271 }
32272
32273 /*
32274 ** Unless the pager is in error-state, discard all in-memory pages. If
32275 ** the pager is in error-state, then this call is a no-op.
32276 **
32277 ** TODO: Why can we not reset the pager while in error state?
32278 */
32279 static void pager_reset(Pager *pPager){
32280   if( SQLITE_OK==pPager->errCode ){
32281     sqlite3BackupRestart(pPager->pBackup);
32282     sqlite3PcacheClear(pPager->pPCache);
32283     pPager->dbSizeValid = 0;
32284   }
32285 }
32286
32287 /*
32288 ** Free all structures in the Pager.aSavepoint[] array and set both
32289 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
32290 ** if it is open and the pager is not in exclusive mode.
32291 */
32292 static void releaseAllSavepoints(Pager *pPager){
32293   int ii;               /* Iterator for looping through Pager.aSavepoint */
32294   for(ii=0; ii<pPager->nSavepoint; ii++){
32295     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
32296   }
32297   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
32298     sqlite3OsClose(pPager->sjfd);
32299   }
32300   sqlite3_free(pPager->aSavepoint);
32301   pPager->aSavepoint = 0;
32302   pPager->nSavepoint = 0;
32303   pPager->nSubRec = 0;
32304 }
32305
32306 /*
32307 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
32308 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
32309 ** or SQLITE_NOMEM if a malloc failure occurs.
32310 */
32311 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
32312   int ii;                   /* Loop counter */
32313   int rc = SQLITE_OK;       /* Result code */
32314
32315   for(ii=0; ii<pPager->nSavepoint; ii++){
32316     PagerSavepoint *p = &pPager->aSavepoint[ii];
32317     if( pgno<=p->nOrig ){
32318       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
32319       testcase( rc==SQLITE_NOMEM );
32320       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
32321     }
32322   }
32323   return rc;
32324 }
32325
32326 /*
32327 ** Unlock the database file. This function is a no-op if the pager
32328 ** is in exclusive mode.
32329 **
32330 ** If the pager is currently in error state, discard the contents of 
32331 ** the cache and reset the Pager structure internal state. If there is
32332 ** an open journal-file, then the next time a shared-lock is obtained
32333 ** on the pager file (by this or any other process), it will be
32334 ** treated as a hot-journal and rolled back.
32335 */
32336 static void pager_unlock(Pager *pPager){
32337   if( !pPager->exclusiveMode ){
32338     int rc;                      /* Return code */
32339
32340     /* Always close the journal file when dropping the database lock.
32341     ** Otherwise, another connection with journal_mode=delete might
32342     ** delete the file out from under us.
32343     */
32344     sqlite3OsClose(pPager->jfd);
32345     sqlite3BitvecDestroy(pPager->pInJournal);
32346     pPager->pInJournal = 0;
32347     releaseAllSavepoints(pPager);
32348
32349     /* If the file is unlocked, somebody else might change it. The
32350     ** values stored in Pager.dbSize etc. might become invalid if
32351     ** this happens. TODO: Really, this doesn't need to be cleared
32352     ** until the change-counter check fails in PagerSharedLock().
32353     */
32354     pPager->dbSizeValid = 0;
32355
32356     rc = osUnlock(pPager->fd, NO_LOCK);
32357     if( rc ){
32358       pPager->errCode = rc;
32359     }
32360     IOTRACE(("UNLOCK %p\n", pPager))
32361
32362     /* If Pager.errCode is set, the contents of the pager cache cannot be
32363     ** trusted. Now that the pager file is unlocked, the contents of the
32364     ** cache can be discarded and the error code safely cleared.
32365     */
32366     if( pPager->errCode ){
32367       if( rc==SQLITE_OK ){
32368         pPager->errCode = SQLITE_OK;
32369       }
32370       pager_reset(pPager);
32371     }
32372
32373     pPager->changeCountDone = 0;
32374     pPager->state = PAGER_UNLOCK;
32375     pPager->dbModified = 0;
32376   }
32377 }
32378
32379 /*
32380 ** This function should be called when an IOERR, CORRUPT or FULL error
32381 ** may have occurred. The first argument is a pointer to the pager 
32382 ** structure, the second the error-code about to be returned by a pager 
32383 ** API function. The value returned is a copy of the second argument 
32384 ** to this function. 
32385 **
32386 ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
32387 ** the error becomes persistent. Until the persisten error is cleared,
32388 ** subsequent API calls on this Pager will immediately return the same 
32389 ** error code.
32390 **
32391 ** A persistent error indicates that the contents of the pager-cache 
32392 ** cannot be trusted. This state can be cleared by completely discarding 
32393 ** the contents of the pager-cache. If a transaction was active when
32394 ** the persistent error occurred, then the rollback journal may need
32395 ** to be replayed to restore the contents of the database file (as if
32396 ** it were a hot-journal).
32397 */
32398 static int pager_error(Pager *pPager, int rc){
32399   int rc2 = rc & 0xff;
32400   assert( rc==SQLITE_OK || !MEMDB );
32401   assert(
32402        pPager->errCode==SQLITE_FULL ||
32403        pPager->errCode==SQLITE_OK ||
32404        (pPager->errCode & 0xff)==SQLITE_IOERR
32405   );
32406   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
32407     pPager->errCode = rc;
32408   }
32409   return rc;
32410 }
32411
32412 /*
32413 ** Execute a rollback if a transaction is active and unlock the 
32414 ** database file. 
32415 **
32416 ** If the pager has already entered the error state, do not attempt 
32417 ** the rollback at this time. Instead, pager_unlock() is called. The
32418 ** call to pager_unlock() will discard all in-memory pages, unlock
32419 ** the database file and clear the error state. If this means that
32420 ** there is a hot-journal left in the file-system, the next connection
32421 ** to obtain a shared lock on the pager (which may be this one) will
32422 ** roll it back.
32423 **
32424 ** If the pager has not already entered the error state, but an IO or
32425 ** malloc error occurs during a rollback, then this will itself cause 
32426 ** the pager to enter the error state. Which will be cleared by the
32427 ** call to pager_unlock(), as described above.
32428 */
32429 static void pagerUnlockAndRollback(Pager *pPager){
32430   if( pPager->errCode==SQLITE_OK && pPager->state>=PAGER_RESERVED ){
32431     sqlite3BeginBenignMalloc();
32432     sqlite3PagerRollback(pPager);
32433     sqlite3EndBenignMalloc();
32434   }
32435   pager_unlock(pPager);
32436 }
32437
32438 /*
32439 ** This routine ends a transaction. A transaction is usually ended by 
32440 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
32441 ** after rollback of a hot-journal, or if an error occurs while opening
32442 ** the journal file or writing the very first journal-header of a
32443 ** database transaction.
32444 ** 
32445 ** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this
32446 ** routine is called, it is a no-op (returns SQLITE_OK).
32447 **
32448 ** Otherwise, any active savepoints are released.
32449 **
32450 ** If the journal file is open, then it is "finalized". Once a journal 
32451 ** file has been finalized it is not possible to use it to roll back a 
32452 ** transaction. Nor will it be considered to be a hot-journal by this
32453 ** or any other database connection. Exactly how a journal is finalized
32454 ** depends on whether or not the pager is running in exclusive mode and
32455 ** the current journal-mode (Pager.journalMode value), as follows:
32456 **
32457 **   journalMode==MEMORY
32458 **     Journal file descriptor is simply closed. This destroys an 
32459 **     in-memory journal.
32460 **
32461 **   journalMode==TRUNCATE
32462 **     Journal file is truncated to zero bytes in size.
32463 **
32464 **   journalMode==PERSIST
32465 **     The first 28 bytes of the journal file are zeroed. This invalidates
32466 **     the first journal header in the file, and hence the entire journal
32467 **     file. An invalid journal file cannot be rolled back.
32468 **
32469 **   journalMode==DELETE
32470 **     The journal file is closed and deleted using sqlite3OsDelete().
32471 **
32472 **     If the pager is running in exclusive mode, this method of finalizing
32473 **     the journal file is never used. Instead, if the journalMode is
32474 **     DELETE and the pager is in exclusive mode, the method described under
32475 **     journalMode==PERSIST is used instead.
32476 **
32477 ** After the journal is finalized, if running in non-exclusive mode, the
32478 ** pager moves to PAGER_SHARED state (and downgrades the lock on the
32479 ** database file accordingly).
32480 **
32481 ** If the pager is running in exclusive mode and is in PAGER_SYNCED state,
32482 ** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in
32483 ** exclusive mode.
32484 **
32485 ** SQLITE_OK is returned if no error occurs. If an error occurs during
32486 ** any of the IO operations to finalize the journal file or unlock the
32487 ** database then the IO error code is returned to the user. If the 
32488 ** operation to finalize the journal file fails, then the code still
32489 ** tries to unlock the database file if not in exclusive mode. If the
32490 ** unlock operation fails as well, then the first error code related
32491 ** to the first error encountered (the journal finalization one) is
32492 ** returned.
32493 */
32494 static int pager_end_transaction(Pager *pPager, int hasMaster){
32495   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
32496   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
32497
32498   if( pPager->state<PAGER_RESERVED ){
32499     return SQLITE_OK;
32500   }
32501   releaseAllSavepoints(pPager);
32502
32503   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
32504   if( isOpen(pPager->jfd) ){
32505
32506     /* Finalize the journal file. */
32507     if( sqlite3IsMemJournal(pPager->jfd) ){
32508       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
32509       sqlite3OsClose(pPager->jfd);
32510     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
32511       if( pPager->journalOff==0 ){
32512         rc = SQLITE_OK;
32513       }else{
32514         rc = sqlite3OsTruncate(pPager->jfd, 0);
32515       }
32516       pPager->journalOff = 0;
32517       pPager->journalStarted = 0;
32518     }else if( pPager->exclusiveMode 
32519      || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
32520     ){
32521       rc = zeroJournalHdr(pPager, hasMaster);
32522       pager_error(pPager, rc);
32523       pPager->journalOff = 0;
32524       pPager->journalStarted = 0;
32525     }else{
32526       /* This branch may be executed with Pager.journalMode==MEMORY if
32527       ** a hot-journal was just rolled back. In this case the journal
32528       ** file should be closed and deleted. If this connection writes to
32529       ** the database file, it will do so using an in-memory journal.  */
32530       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
32531            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
32532       );
32533       sqlite3OsClose(pPager->jfd);
32534       if( !pPager->tempFile ){
32535         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
32536       }
32537     }
32538
32539 #ifdef SQLITE_CHECK_PAGES
32540     sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
32541 #endif
32542
32543     sqlite3PcacheCleanAll(pPager->pPCache);
32544     sqlite3BitvecDestroy(pPager->pInJournal);
32545     pPager->pInJournal = 0;
32546     pPager->nRec = 0;
32547   }
32548
32549   if( !pPager->exclusiveMode ){
32550     rc2 = osUnlock(pPager->fd, SHARED_LOCK);
32551     pPager->state = PAGER_SHARED;
32552     pPager->changeCountDone = 0;
32553   }else if( pPager->state==PAGER_SYNCED ){
32554     pPager->state = PAGER_EXCLUSIVE;
32555   }
32556   pPager->setMaster = 0;
32557   pPager->needSync = 0;
32558   pPager->dbModified = 0;
32559
32560   /* TODO: Is this optimal? Why is the db size invalidated here 
32561   ** when the database file is not unlocked? */
32562   pPager->dbOrigSize = 0;
32563   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
32564   if( !MEMDB ){
32565     pPager->dbSizeValid = 0;
32566   }
32567
32568   return (rc==SQLITE_OK?rc2:rc);
32569 }
32570
32571 /*
32572 ** Parameter aData must point to a buffer of pPager->pageSize bytes
32573 ** of data. Compute and return a checksum based ont the contents of the 
32574 ** page of data and the current value of pPager->cksumInit.
32575 **
32576 ** This is not a real checksum. It is really just the sum of the 
32577 ** random initial value (pPager->cksumInit) and every 200th byte
32578 ** of the page data, starting with byte offset (pPager->pageSize%200).
32579 ** Each byte is interpreted as an 8-bit unsigned integer.
32580 **
32581 ** Changing the formula used to compute this checksum results in an
32582 ** incompatible journal file format.
32583 **
32584 ** If journal corruption occurs due to a power failure, the most likely 
32585 ** scenario is that one end or the other of the record will be changed. 
32586 ** It is much less likely that the two ends of the journal record will be
32587 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
32588 ** though fast and simple, catches the mostly likely kind of corruption.
32589 */
32590 static u32 pager_cksum(Pager *pPager, const u8 *aData){
32591   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
32592   int i = pPager->pageSize-200;          /* Loop counter */
32593   while( i>0 ){
32594     cksum += aData[i];
32595     i -= 200;
32596   }
32597   return cksum;
32598 }
32599
32600 /*
32601 ** Read a single page from either the journal file (if isMainJrnl==1) or
32602 ** from the sub-journal (if isMainJrnl==0) and playback that page.
32603 ** The page begins at offset *pOffset into the file. The *pOffset
32604 ** value is increased to the start of the next page in the journal.
32605 **
32606 ** The isMainJrnl flag is true if this is the main rollback journal and
32607 ** false for the statement journal.  The main rollback journal uses
32608 ** checksums - the statement journal does not.
32609 **
32610 ** If the page number of the page record read from the (sub-)journal file
32611 ** is greater than the current value of Pager.dbSize, then playback is
32612 ** skipped and SQLITE_OK is returned.
32613 **
32614 ** If pDone is not NULL, then it is a record of pages that have already
32615 ** been played back.  If the page at *pOffset has already been played back
32616 ** (if the corresponding pDone bit is set) then skip the playback.
32617 ** Make sure the pDone bit corresponding to the *pOffset page is set
32618 ** prior to returning.
32619 **
32620 ** If the page record is successfully read from the (sub-)journal file
32621 ** and played back, then SQLITE_OK is returned. If an IO error occurs
32622 ** while reading the record from the (sub-)journal file or while writing
32623 ** to the database file, then the IO error code is returned. If data
32624 ** is successfully read from the (sub-)journal file but appears to be
32625 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
32626 ** two circumstances:
32627 ** 
32628 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
32629 **   * If the record is being rolled back from the main journal file
32630 **     and the checksum field does not match the record content.
32631 **
32632 ** Neither of these two scenarios are possible during a savepoint rollback.
32633 **
32634 ** If this is a savepoint rollback, then memory may have to be dynamically
32635 ** allocated by this function. If this is the case and an allocation fails,
32636 ** SQLITE_NOMEM is returned.
32637 */
32638 static int pager_playback_one_page(
32639   Pager *pPager,                /* The pager being played back */
32640   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
32641   int isUnsync,                 /* True if reading from unsynced main journal */
32642   i64 *pOffset,                 /* Offset of record to playback */
32643   int isSavepnt,                /* True for a savepoint rollback */
32644   Bitvec *pDone                 /* Bitvec of pages already played back */
32645 ){
32646   int rc;
32647   PgHdr *pPg;                   /* An existing page in the cache */
32648   Pgno pgno;                    /* The page number of a page in journal */
32649   u32 cksum;                    /* Checksum used for sanity checking */
32650   char *aData;                  /* Temporary storage for the page */
32651   sqlite3_file *jfd;            /* The file descriptor for the journal file */
32652
32653   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
32654   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
32655   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
32656   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
32657
32658   aData = pPager->pTmpSpace;
32659   assert( aData );         /* Temp storage must have already been allocated */
32660
32661   /* Read the page number and page data from the journal or sub-journal
32662   ** file. Return an error code to the caller if an IO error occurs.
32663   */
32664   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
32665   rc = read32bits(jfd, *pOffset, &pgno);
32666   if( rc!=SQLITE_OK ) return rc;
32667   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
32668   if( rc!=SQLITE_OK ) return rc;
32669   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
32670
32671   /* Sanity checking on the page.  This is more important that I originally
32672   ** thought.  If a power failure occurs while the journal is being written,
32673   ** it could cause invalid data to be written into the journal.  We need to
32674   ** detect this invalid data (with high probability) and ignore it.
32675   */
32676   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
32677     assert( !isSavepnt );
32678     return SQLITE_DONE;
32679   }
32680   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
32681     return SQLITE_OK;
32682   }
32683   if( isMainJrnl ){
32684     rc = read32bits(jfd, (*pOffset)-4, &cksum);
32685     if( rc ) return rc;
32686     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
32687       return SQLITE_DONE;
32688     }
32689   }
32690
32691   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
32692     return rc;
32693   }
32694
32695   assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
32696
32697   /* If the pager is in RESERVED state, then there must be a copy of this
32698   ** page in the pager cache. In this case just update the pager cache,
32699   ** not the database file. The page is left marked dirty in this case.
32700   **
32701   ** An exception to the above rule: If the database is in no-sync mode
32702   ** and a page is moved during an incremental vacuum then the page may
32703   ** not be in the pager cache. Later: if a malloc() or IO error occurs
32704   ** during a Movepage() call, then the page may not be in the cache
32705   ** either. So the condition described in the above paragraph is not
32706   ** assert()able.
32707   **
32708   ** If in EXCLUSIVE state, then we update the pager cache if it exists
32709   ** and the main file. The page is then marked not dirty.
32710   **
32711   ** Ticket #1171:  The statement journal might contain page content that is
32712   ** different from the page content at the start of the transaction.
32713   ** This occurs when a page is changed prior to the start of a statement
32714   ** then changed again within the statement.  When rolling back such a
32715   ** statement we must not write to the original database unless we know
32716   ** for certain that original page contents are synced into the main rollback
32717   ** journal.  Otherwise, a power loss might leave modified data in the
32718   ** database file without an entry in the rollback journal that can
32719   ** restore the database to its original form.  Two conditions must be
32720   ** met before writing to the database files. (1) the database must be
32721   ** locked.  (2) we know that the original page content is fully synced
32722   ** in the main journal either because the page is not in cache or else
32723   ** the page is marked as needSync==0.
32724   **
32725   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
32726   ** is possible to fail a statement on a database that does not yet exist.
32727   ** Do not attempt to write if database file has never been opened.
32728   */
32729   pPg = pager_lookup(pPager, pgno);
32730   assert( pPg || !MEMDB );
32731   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
32732            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
32733            (isMainJrnl?"main-journal":"sub-journal")
32734   ));
32735   if( (pPager->state>=PAGER_EXCLUSIVE)
32736    && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
32737    && isOpen(pPager->fd)
32738    && !isUnsync
32739   ){
32740     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
32741     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
32742     if( pgno>pPager->dbFileSize ){
32743       pPager->dbFileSize = pgno;
32744     }
32745     if( pPager->pBackup ){
32746       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
32747       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
32748       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
32749     }
32750   }else if( !isMainJrnl && pPg==0 ){
32751     /* If this is a rollback of a savepoint and data was not written to
32752     ** the database and the page is not in-memory, there is a potential
32753     ** problem. When the page is next fetched by the b-tree layer, it 
32754     ** will be read from the database file, which may or may not be 
32755     ** current. 
32756     **
32757     ** There are a couple of different ways this can happen. All are quite
32758     ** obscure. When running in synchronous mode, this can only happen 
32759     ** if the page is on the free-list at the start of the transaction, then
32760     ** populated, then moved using sqlite3PagerMovepage().
32761     **
32762     ** The solution is to add an in-memory page to the cache containing
32763     ** the data just read from the sub-journal. Mark the page as dirty 
32764     ** and if the pager requires a journal-sync, then mark the page as 
32765     ** requiring a journal-sync before it is written.
32766     */
32767     assert( isSavepnt );
32768     if( (rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1))!=SQLITE_OK ){
32769       return rc;
32770     }
32771     pPg->flags &= ~PGHDR_NEED_READ;
32772     sqlite3PcacheMakeDirty(pPg);
32773   }
32774   if( pPg ){
32775     /* No page should ever be explicitly rolled back that is in use, except
32776     ** for page 1 which is held in use in order to keep the lock on the
32777     ** database active. However such a page may be rolled back as a result
32778     ** of an internal error resulting in an automatic call to
32779     ** sqlite3PagerRollback().
32780     */
32781     void *pData;
32782     pData = pPg->pData;
32783     memcpy(pData, (u8*)aData, pPager->pageSize);
32784     pPager->xReiniter(pPg);
32785     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
32786       /* If the contents of this page were just restored from the main 
32787       ** journal file, then its content must be as they were when the 
32788       ** transaction was first opened. In this case we can mark the page
32789       ** as clean, since there will be no need to write it out to the.
32790       **
32791       ** There is one exception to this rule. If the page is being rolled
32792       ** back as part of a savepoint (or statement) rollback from an 
32793       ** unsynced portion of the main journal file, then it is not safe
32794       ** to mark the page as clean. This is because marking the page as
32795       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
32796       ** already in the journal file (recorded in Pager.pInJournal) and
32797       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
32798       ** again within this transaction, it will be marked as dirty but
32799       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
32800       ** be written out into the database file before its journal file
32801       ** segment is synced. If a crash occurs during or following this,
32802       ** database corruption may ensue.
32803       */
32804       sqlite3PcacheMakeClean(pPg);
32805     }
32806 #ifdef SQLITE_CHECK_PAGES
32807     pPg->pageHash = pager_pagehash(pPg);
32808 #endif
32809     /* If this was page 1, then restore the value of Pager.dbFileVers.
32810     ** Do this before any decoding. */
32811     if( pgno==1 ){
32812       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
32813     }
32814
32815     /* Decode the page just read from disk */
32816     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
32817     sqlite3PcacheRelease(pPg);
32818   }
32819   return rc;
32820 }
32821
32822 /*
32823 ** Parameter zMaster is the name of a master journal file. A single journal
32824 ** file that referred to the master journal file has just been rolled back.
32825 ** This routine checks if it is possible to delete the master journal file,
32826 ** and does so if it is.
32827 **
32828 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
32829 ** available for use within this function.
32830 **
32831 ** When a master journal file is created, it is populated with the names 
32832 ** of all of its child journals, one after another, formatted as utf-8 
32833 ** encoded text. The end of each child journal file is marked with a 
32834 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
32835 ** file for a transaction involving two databases might be:
32836 **
32837 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
32838 **
32839 ** A master journal file may only be deleted once all of its child 
32840 ** journals have been rolled back.
32841 **
32842 ** This function reads the contents of the master-journal file into 
32843 ** memory and loops through each of the child journal names. For
32844 ** each child journal, it checks if:
32845 **
32846 **   * if the child journal exists, and if so
32847 **   * if the child journal contains a reference to master journal 
32848 **     file zMaster
32849 **
32850 ** If a child journal can be found that matches both of the criteria
32851 ** above, this function returns without doing anything. Otherwise, if
32852 ** no such child journal can be found, file zMaster is deleted from
32853 ** the file-system using sqlite3OsDelete().
32854 **
32855 ** If an IO error within this function, an error code is returned. This
32856 ** function allocates memory by calling sqlite3Malloc(). If an allocation
32857 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
32858 ** occur, SQLITE_OK is returned.
32859 **
32860 ** TODO: This function allocates a single block of memory to load
32861 ** the entire contents of the master journal file. This could be
32862 ** a couple of kilobytes or so - potentially larger than the page 
32863 ** size.
32864 */
32865 static int pager_delmaster(Pager *pPager, const char *zMaster){
32866   sqlite3_vfs *pVfs = pPager->pVfs;
32867   int rc;                   /* Return code */
32868   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
32869   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
32870   char *zMasterJournal = 0; /* Contents of master journal file */
32871   i64 nMasterJournal;       /* Size of master journal file */
32872
32873   /* Allocate space for both the pJournal and pMaster file descriptors.
32874   ** If successful, open the master journal file for reading.
32875   */
32876   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
32877   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
32878   if( !pMaster ){
32879     rc = SQLITE_NOMEM;
32880   }else{
32881     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
32882     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
32883   }
32884   if( rc!=SQLITE_OK ) goto delmaster_out;
32885
32886   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
32887   if( rc!=SQLITE_OK ) goto delmaster_out;
32888
32889   if( nMasterJournal>0 ){
32890     char *zJournal;
32891     char *zMasterPtr = 0;
32892     int nMasterPtr = pVfs->mxPathname+1;
32893
32894     /* Load the entire master journal file into space obtained from
32895     ** sqlite3_malloc() and pointed to by zMasterJournal. 
32896     */
32897     zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
32898     if( !zMasterJournal ){
32899       rc = SQLITE_NOMEM;
32900       goto delmaster_out;
32901     }
32902     zMasterPtr = &zMasterJournal[nMasterJournal+1];
32903     rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
32904     if( rc!=SQLITE_OK ) goto delmaster_out;
32905     zMasterJournal[nMasterJournal] = 0;
32906
32907     zJournal = zMasterJournal;
32908     while( (zJournal-zMasterJournal)<nMasterJournal ){
32909       int exists;
32910       rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
32911       if( rc!=SQLITE_OK ){
32912         goto delmaster_out;
32913       }
32914       if( exists ){
32915         /* One of the journals pointed to by the master journal exists.
32916         ** Open it and check if it points at the master journal. If
32917         ** so, return without deleting the master journal file.
32918         */
32919         int c;
32920         int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
32921         rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
32922         if( rc!=SQLITE_OK ){
32923           goto delmaster_out;
32924         }
32925
32926         rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
32927         sqlite3OsClose(pJournal);
32928         if( rc!=SQLITE_OK ){
32929           goto delmaster_out;
32930         }
32931
32932         c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
32933         if( c ){
32934           /* We have a match. Do not delete the master journal file. */
32935           goto delmaster_out;
32936         }
32937       }
32938       zJournal += (sqlite3Strlen30(zJournal)+1);
32939     }
32940   }
32941   
32942   rc = sqlite3OsDelete(pVfs, zMaster, 0);
32943
32944 delmaster_out:
32945   if( zMasterJournal ){
32946     sqlite3_free(zMasterJournal);
32947   }  
32948   if( pMaster ){
32949     sqlite3OsClose(pMaster);
32950     assert( !isOpen(pJournal) );
32951   }
32952   sqlite3_free(pMaster);
32953   return rc;
32954 }
32955
32956
32957 /*
32958 ** This function is used to change the actual size of the database 
32959 ** file in the file-system. This only happens when committing a transaction,
32960 ** or rolling back a transaction (including rolling back a hot-journal).
32961 **
32962 ** If the main database file is not open, or an exclusive lock is not
32963 ** held, this function is a no-op. Otherwise, the size of the file is
32964 ** changed to nPage pages (nPage*pPager->pageSize bytes). If the file
32965 ** on disk is currently larger than nPage pages, then use the VFS
32966 ** xTruncate() method to truncate it.
32967 **
32968 ** Or, it might might be the case that the file on disk is smaller than 
32969 ** nPage pages. Some operating system implementations can get confused if 
32970 ** you try to truncate a file to some size that is larger than it 
32971 ** currently is, so detect this case and write a single zero byte to 
32972 ** the end of the new file instead.
32973 **
32974 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
32975 ** the database file, return the error code to the caller.
32976 */
32977 static int pager_truncate(Pager *pPager, Pgno nPage){
32978   int rc = SQLITE_OK;
32979   if( pPager->state>=PAGER_EXCLUSIVE && isOpen(pPager->fd) ){
32980     i64 currentSize, newSize;
32981     /* TODO: Is it safe to use Pager.dbFileSize here? */
32982     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
32983     newSize = pPager->pageSize*(i64)nPage;
32984     if( rc==SQLITE_OK && currentSize!=newSize ){
32985       if( currentSize>newSize ){
32986         rc = sqlite3OsTruncate(pPager->fd, newSize);
32987       }else{
32988         rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
32989       }
32990       if( rc==SQLITE_OK ){
32991         pPager->dbFileSize = nPage;
32992       }
32993     }
32994   }
32995   return rc;
32996 }
32997
32998 /*
32999 ** Set the value of the Pager.sectorSize variable for the given
33000 ** pager based on the value returned by the xSectorSize method
33001 ** of the open database file. The sector size will be used used 
33002 ** to determine the size and alignment of journal header and 
33003 ** master journal pointers within created journal files.
33004 **
33005 ** For temporary files the effective sector size is always 512 bytes.
33006 **
33007 ** Otherwise, for non-temporary files, the effective sector size is
33008 ** the value returned by the xSectorSize() method rounded up to 32 if
33009 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
33010 ** is greater than MAX_SECTOR_SIZE.
33011 */
33012 static void setSectorSize(Pager *pPager){
33013   assert( isOpen(pPager->fd) || pPager->tempFile );
33014
33015   if( !pPager->tempFile ){
33016     /* Sector size doesn't matter for temporary files. Also, the file
33017     ** may not have been opened yet, in which case the OsSectorSize()
33018     ** call will segfault.
33019     */
33020     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
33021   }
33022   if( pPager->sectorSize<32 ){
33023     pPager->sectorSize = 512;
33024   }
33025   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
33026     assert( MAX_SECTOR_SIZE>=512 );
33027     pPager->sectorSize = MAX_SECTOR_SIZE;
33028   }
33029 }
33030
33031 /*
33032 ** Playback the journal and thus restore the database file to
33033 ** the state it was in before we started making changes.  
33034 **
33035 ** The journal file format is as follows: 
33036 **
33037 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
33038 **  (2)  4 byte big-endian integer which is the number of valid page records
33039 **       in the journal.  If this value is 0xffffffff, then compute the
33040 **       number of page records from the journal size.
33041 **  (3)  4 byte big-endian integer which is the initial value for the 
33042 **       sanity checksum.
33043 **  (4)  4 byte integer which is the number of pages to truncate the
33044 **       database to during a rollback.
33045 **  (5)  4 byte big-endian integer which is the sector size.  The header
33046 **       is this many bytes in size.
33047 **  (6)  4 byte big-endian integer which is the page size.
33048 **  (7)  zero padding out to the next sector size.
33049 **  (8)  Zero or more pages instances, each as follows:
33050 **        +  4 byte page number.
33051 **        +  pPager->pageSize bytes of data.
33052 **        +  4 byte checksum
33053 **
33054 ** When we speak of the journal header, we mean the first 7 items above.
33055 ** Each entry in the journal is an instance of the 8th item.
33056 **
33057 ** Call the value from the second bullet "nRec".  nRec is the number of
33058 ** valid page entries in the journal.  In most cases, you can compute the
33059 ** value of nRec from the size of the journal file.  But if a power
33060 ** failure occurred while the journal was being written, it could be the
33061 ** case that the size of the journal file had already been increased but
33062 ** the extra entries had not yet made it safely to disk.  In such a case,
33063 ** the value of nRec computed from the file size would be too large.  For
33064 ** that reason, we always use the nRec value in the header.
33065 **
33066 ** If the nRec value is 0xffffffff it means that nRec should be computed
33067 ** from the file size.  This value is used when the user selects the
33068 ** no-sync option for the journal.  A power failure could lead to corruption
33069 ** in this case.  But for things like temporary table (which will be
33070 ** deleted when the power is restored) we don't care.  
33071 **
33072 ** If the file opened as the journal file is not a well-formed
33073 ** journal file then all pages up to the first corrupted page are rolled
33074 ** back (or no pages if the journal header is corrupted). The journal file
33075 ** is then deleted and SQLITE_OK returned, just as if no corruption had
33076 ** been encountered.
33077 **
33078 ** If an I/O or malloc() error occurs, the journal-file is not deleted
33079 ** and an error code is returned.
33080 **
33081 ** The isHot parameter indicates that we are trying to rollback a journal
33082 ** that might be a hot journal.  Or, it could be that the journal is 
33083 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
33084 ** If the journal really is hot, reset the pager cache prior rolling
33085 ** back any content.  If the journal is merely persistent, no reset is
33086 ** needed.
33087 */
33088 static int pager_playback(Pager *pPager, int isHot){
33089   sqlite3_vfs *pVfs = pPager->pVfs;
33090   i64 szJ;                 /* Size of the journal file in bytes */
33091   u32 nRec;                /* Number of Records in the journal */
33092   u32 u;                   /* Unsigned loop counter */
33093   Pgno mxPg = 0;           /* Size of the original file in pages */
33094   int rc;                  /* Result code of a subroutine */
33095   int res = 1;             /* Value returned by sqlite3OsAccess() */
33096   char *zMaster = 0;       /* Name of master journal file if any */
33097   int needPagerReset;      /* True to reset page prior to first page rollback */
33098
33099   /* Figure out how many records are in the journal.  Abort early if
33100   ** the journal is empty.
33101   */
33102   assert( isOpen(pPager->jfd) );
33103   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
33104   if( rc!=SQLITE_OK || szJ==0 ){
33105     goto end_playback;
33106   }
33107
33108   /* Read the master journal name from the journal, if it is present.
33109   ** If a master journal file name is specified, but the file is not
33110   ** present on disk, then the journal is not hot and does not need to be
33111   ** played back.
33112   **
33113   ** TODO: Technically the following is an error because it assumes that
33114   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
33115   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
33116   **  mxPathname is 512, which is the same as the minimum allowable value
33117   ** for pageSize.
33118   */
33119   zMaster = pPager->pTmpSpace;
33120   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
33121   if( rc==SQLITE_OK && zMaster[0] ){
33122     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
33123   }
33124   zMaster = 0;
33125   if( rc!=SQLITE_OK || !res ){
33126     goto end_playback;
33127   }
33128   pPager->journalOff = 0;
33129   needPagerReset = isHot;
33130
33131   /* This loop terminates either when a readJournalHdr() or 
33132   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
33133   ** occurs. 
33134   */
33135   while( 1 ){
33136     int isUnsync = 0;
33137
33138     /* Read the next journal header from the journal file.  If there are
33139     ** not enough bytes left in the journal file for a complete header, or
33140     ** it is corrupted, then a process must of failed while writing it.
33141     ** This indicates nothing more needs to be rolled back.
33142     */
33143     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
33144     if( rc!=SQLITE_OK ){ 
33145       if( rc==SQLITE_DONE ){
33146         rc = SQLITE_OK;
33147       }
33148       goto end_playback;
33149     }
33150
33151     /* If nRec is 0xffffffff, then this journal was created by a process
33152     ** working in no-sync mode. This means that the rest of the journal
33153     ** file consists of pages, there are no more journal headers. Compute
33154     ** the value of nRec based on this assumption.
33155     */
33156     if( nRec==0xffffffff ){
33157       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
33158       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
33159     }
33160
33161     /* If nRec is 0 and this rollback is of a transaction created by this
33162     ** process and if this is the final header in the journal, then it means
33163     ** that this part of the journal was being filled but has not yet been
33164     ** synced to disk.  Compute the number of pages based on the remaining
33165     ** size of the file.
33166     **
33167     ** The third term of the test was added to fix ticket #2565.
33168     ** When rolling back a hot journal, nRec==0 always means that the next
33169     ** chunk of the journal contains zero pages to be rolled back.  But
33170     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
33171     ** the journal, it means that the journal might contain additional
33172     ** pages that need to be rolled back and that the number of pages 
33173     ** should be computed based on the journal file size.
33174     */
33175     if( nRec==0 && !isHot &&
33176         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
33177       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
33178       isUnsync = 1;
33179     }
33180
33181     /* If this is the first header read from the journal, truncate the
33182     ** database file back to its original size.
33183     */
33184     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
33185       rc = pager_truncate(pPager, mxPg);
33186       if( rc!=SQLITE_OK ){
33187         goto end_playback;
33188       }
33189       pPager->dbSize = mxPg;
33190     }
33191
33192     /* Copy original pages out of the journal and back into the 
33193     ** database file and/or page cache.
33194     */
33195     for(u=0; u<nRec; u++){
33196       if( needPagerReset ){
33197         pager_reset(pPager);
33198         needPagerReset = 0;
33199       }
33200       rc = pager_playback_one_page(pPager,1,isUnsync,&pPager->journalOff,0,0);
33201       if( rc!=SQLITE_OK ){
33202         if( rc==SQLITE_DONE ){
33203           rc = SQLITE_OK;
33204           pPager->journalOff = szJ;
33205           break;
33206         }else{
33207           /* If we are unable to rollback, quit and return the error
33208           ** code.  This will cause the pager to enter the error state
33209           ** so that no further harm will be done.  Perhaps the next
33210           ** process to come along will be able to rollback the database.
33211           */
33212           goto end_playback;
33213         }
33214       }
33215     }
33216   }
33217   /*NOTREACHED*/
33218   assert( 0 );
33219
33220 end_playback:
33221   /* Following a rollback, the database file should be back in its original
33222   ** state prior to the start of the transaction, so invoke the
33223   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
33224   ** assertion that the transaction counter was modified.
33225   */
33226   assert(
33227     pPager->fd->pMethods==0 ||
33228     sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
33229   );
33230
33231   /* If this playback is happening automatically as a result of an IO or 
33232   ** malloc error that occurred after the change-counter was updated but 
33233   ** before the transaction was committed, then the change-counter 
33234   ** modification may just have been reverted. If this happens in exclusive 
33235   ** mode, then subsequent transactions performed by the connection will not
33236   ** update the change-counter at all. This may lead to cache inconsistency
33237   ** problems for other processes at some point in the future. So, just
33238   ** in case this has happened, clear the changeCountDone flag now.
33239   */
33240   pPager->changeCountDone = pPager->tempFile;
33241
33242   if( rc==SQLITE_OK ){
33243     zMaster = pPager->pTmpSpace;
33244     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
33245     testcase( rc!=SQLITE_OK );
33246   }
33247   if( rc==SQLITE_OK ){
33248     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
33249     testcase( rc!=SQLITE_OK );
33250   }
33251   if( rc==SQLITE_OK && zMaster[0] && res ){
33252     /* If there was a master journal and this routine will return success,
33253     ** see if it is possible to delete the master journal.
33254     */
33255     rc = pager_delmaster(pPager, zMaster);
33256     testcase( rc!=SQLITE_OK );
33257   }
33258
33259   /* The Pager.sectorSize variable may have been updated while rolling
33260   ** back a journal created by a process with a different sector size
33261   ** value. Reset it to the correct value for this process.
33262   */
33263   setSectorSize(pPager);
33264   return rc;
33265 }
33266
33267 /*
33268 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
33269 ** the entire master journal file. The case pSavepoint==NULL occurs when 
33270 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
33271 ** savepoint.
33272 **
33273 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
33274 ** being rolled back), then the rollback consists of up to three stages,
33275 ** performed in the order specified:
33276 **
33277 **   * Pages are played back from the main journal starting at byte
33278 **     offset PagerSavepoint.iOffset and continuing to 
33279 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
33280 **     file if PagerSavepoint.iHdrOffset is zero.
33281 **
33282 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
33283 **     back starting from the journal header immediately following 
33284 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
33285 **
33286 **   * Pages are then played back from the sub-journal file, starting
33287 **     with the PagerSavepoint.iSubRec and continuing to the end of
33288 **     the journal file.
33289 **
33290 ** Throughout the rollback process, each time a page is rolled back, the
33291 ** corresponding bit is set in a bitvec structure (variable pDone in the
33292 ** implementation below). This is used to ensure that a page is only
33293 ** rolled back the first time it is encountered in either journal.
33294 **
33295 ** If pSavepoint is NULL, then pages are only played back from the main
33296 ** journal file. There is no need for a bitvec in this case.
33297 **
33298 ** In either case, before playback commences the Pager.dbSize variable
33299 ** is reset to the value that it held at the start of the savepoint 
33300 ** (or transaction). No page with a page-number greater than this value
33301 ** is played back. If one is encountered it is simply skipped.
33302 */
33303 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
33304   i64 szJ;                 /* Effective size of the main journal */
33305   i64 iHdrOff;             /* End of first segment of main-journal records */
33306   int rc = SQLITE_OK;      /* Return code */
33307   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
33308
33309   assert( pPager->state>=PAGER_SHARED );
33310
33311   /* Allocate a bitvec to use to store the set of pages rolled back */
33312   if( pSavepoint ){
33313     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
33314     if( !pDone ){
33315       return SQLITE_NOMEM;
33316     }
33317   }
33318
33319   /* Set the database size back to the value it was before the savepoint 
33320   ** being reverted was opened.
33321   */
33322   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
33323
33324   /* Use pPager->journalOff as the effective size of the main rollback
33325   ** journal.  The actual file might be larger than this in
33326   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
33327   ** past pPager->journalOff is off-limits to us.
33328   */
33329   szJ = pPager->journalOff;
33330
33331   /* Begin by rolling back records from the main journal starting at
33332   ** PagerSavepoint.iOffset and continuing to the next journal header.
33333   ** There might be records in the main journal that have a page number
33334   ** greater than the current database size (pPager->dbSize) but those
33335   ** will be skipped automatically.  Pages are added to pDone as they
33336   ** are played back.
33337   */
33338   if( pSavepoint ){
33339     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
33340     pPager->journalOff = pSavepoint->iOffset;
33341     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
33342       rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
33343     }
33344     assert( rc!=SQLITE_DONE );
33345   }else{
33346     pPager->journalOff = 0;
33347   }
33348
33349   /* Continue rolling back records out of the main journal starting at
33350   ** the first journal header seen and continuing until the effective end
33351   ** of the main journal file.  Continue to skip out-of-range pages and
33352   ** continue adding pages rolled back to pDone.
33353   */
33354   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
33355     u32 ii;            /* Loop counter */
33356     u32 nJRec = 0;     /* Number of Journal Records */
33357     u32 dummy;
33358     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
33359     assert( rc!=SQLITE_DONE );
33360
33361     /*
33362     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
33363     ** test is related to ticket #2565.  See the discussion in the
33364     ** pager_playback() function for additional information.
33365     */
33366     if( nJRec==0 
33367      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
33368     ){
33369       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
33370     }
33371     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
33372       rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
33373     }
33374     assert( rc!=SQLITE_DONE );
33375   }
33376   assert( rc!=SQLITE_OK || pPager->journalOff==szJ );
33377
33378   /* Finally,  rollback pages from the sub-journal.  Page that were
33379   ** previously rolled back out of the main journal (and are hence in pDone)
33380   ** will be skipped.  Out-of-range pages are also skipped.
33381   */
33382   if( pSavepoint ){
33383     u32 ii;            /* Loop counter */
33384     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
33385     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
33386       assert( offset==ii*(4+pPager->pageSize) );
33387       rc = pager_playback_one_page(pPager, 0, 0, &offset, 1, pDone);
33388     }
33389     assert( rc!=SQLITE_DONE );
33390   }
33391
33392   sqlite3BitvecDestroy(pDone);
33393   if( rc==SQLITE_OK ){
33394     pPager->journalOff = szJ;
33395   }
33396   return rc;
33397 }
33398
33399 /*
33400 ** Change the maximum number of in-memory pages that are allowed.
33401 */
33402 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
33403   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
33404 }
33405
33406 /*
33407 ** Adjust the robustness of the database to damage due to OS crashes
33408 ** or power failures by changing the number of syncs()s when writing
33409 ** the rollback journal.  There are three levels:
33410 **
33411 **    OFF       sqlite3OsSync() is never called.  This is the default
33412 **              for temporary and transient files.
33413 **
33414 **    NORMAL    The journal is synced once before writes begin on the
33415 **              database.  This is normally adequate protection, but
33416 **              it is theoretically possible, though very unlikely,
33417 **              that an inopertune power failure could leave the journal
33418 **              in a state which would cause damage to the database
33419 **              when it is rolled back.
33420 **
33421 **    FULL      The journal is synced twice before writes begin on the
33422 **              database (with some additional information - the nRec field
33423 **              of the journal header - being written in between the two
33424 **              syncs).  If we assume that writing a
33425 **              single disk sector is atomic, then this mode provides
33426 **              assurance that the journal will not be corrupted to the
33427 **              point of causing damage to the database during rollback.
33428 **
33429 ** Numeric values associated with these states are OFF==1, NORMAL=2,
33430 ** and FULL=3.
33431 */
33432 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
33433 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
33434   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
33435   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
33436   pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
33437   if( pPager->noSync ) pPager->needSync = 0;
33438 }
33439 #endif
33440
33441 /*
33442 ** The following global variable is incremented whenever the library
33443 ** attempts to open a temporary file.  This information is used for
33444 ** testing and analysis only.  
33445 */
33446 #ifdef SQLITE_TEST
33447 SQLITE_API int sqlite3_opentemp_count = 0;
33448 #endif
33449
33450 /*
33451 ** Open a temporary file.
33452 **
33453 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
33454 ** or some other error code if we fail. The OS will automatically 
33455 ** delete the temporary file when it is closed.
33456 **
33457 ** The flags passed to the VFS layer xOpen() call are those specified
33458 ** by parameter vfsFlags ORed with the following:
33459 **
33460 **     SQLITE_OPEN_READWRITE
33461 **     SQLITE_OPEN_CREATE
33462 **     SQLITE_OPEN_EXCLUSIVE
33463 **     SQLITE_OPEN_DELETEONCLOSE
33464 */
33465 static int pagerOpentemp(
33466   Pager *pPager,        /* The pager object */
33467   sqlite3_file *pFile,  /* Write the file descriptor here */
33468   int vfsFlags          /* Flags passed through to the VFS */
33469 ){
33470   int rc;               /* Return code */
33471
33472 #ifdef SQLITE_TEST
33473   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
33474 #endif
33475
33476   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
33477             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
33478   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
33479   assert( rc!=SQLITE_OK || isOpen(pFile) );
33480   return rc;
33481 }
33482
33483 /*
33484 ** Set the busy handler function.
33485 **
33486 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
33487 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
33488 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
33489 ** lock. It does *not* invoke the busy handler when upgrading from
33490 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
33491 ** (which occurs during hot-journal rollback). Summary:
33492 **
33493 **   Transition                        | Invokes xBusyHandler
33494 **   --------------------------------------------------------
33495 **   NO_LOCK       -> SHARED_LOCK      | Yes
33496 **   SHARED_LOCK   -> RESERVED_LOCK    | No
33497 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
33498 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
33499 **
33500 ** If the busy-handler callback returns non-zero, the lock is 
33501 ** retried. If it returns zero, then the SQLITE_BUSY error is
33502 ** returned to the caller of the pager API function.
33503 */
33504 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
33505   Pager *pPager,                       /* Pager object */
33506   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
33507   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
33508 ){  
33509   pPager->xBusyHandler = xBusyHandler;
33510   pPager->pBusyHandlerArg = pBusyHandlerArg;
33511 }
33512
33513 /*
33514 ** Report the current page size and number of reserved bytes back
33515 ** to the codec.
33516 */
33517 #ifdef SQLITE_HAS_CODEC
33518 static void pagerReportSize(Pager *pPager){
33519   if( pPager->xCodecSizeChng ){
33520     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
33521                            (int)pPager->nReserve);
33522   }
33523 }
33524 #else
33525 # define pagerReportSize(X)     /* No-op if we do not support a codec */
33526 #endif
33527
33528 /*
33529 ** Change the page size used by the Pager object. The new page size 
33530 ** is passed in *pPageSize.
33531 **
33532 ** If the pager is in the error state when this function is called, it
33533 ** is a no-op. The value returned is the error state error code (i.e. 
33534 ** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL).
33535 **
33536 ** Otherwise, if all of the following are true:
33537 **
33538 **   * the new page size (value of *pPageSize) is valid (a power 
33539 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
33540 **
33541 **   * there are no outstanding page references, and
33542 **
33543 **   * the database is either not an in-memory database or it is
33544 **     an in-memory database that currently consists of zero pages.
33545 **
33546 ** then the pager object page size is set to *pPageSize.
33547 **
33548 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
33549 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
33550 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
33551 ** In all other cases, SQLITE_OK is returned.
33552 **
33553 ** If the page size is not changed, either because one of the enumerated
33554 ** conditions above is not true, the pager was in error state when this
33555 ** function was called, or because the memory allocation attempt failed, 
33556 ** then *pPageSize is set to the old, retained page size before returning.
33557 */
33558 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize, int nReserve){
33559   int rc = pPager->errCode;
33560
33561   if( rc==SQLITE_OK ){
33562     u16 pageSize = *pPageSize;
33563     assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
33564     if( (pPager->memDb==0 || pPager->dbSize==0)
33565      && sqlite3PcacheRefCount(pPager->pPCache)==0 
33566      && pageSize && pageSize!=pPager->pageSize 
33567     ){
33568       char *pNew = (char *)sqlite3PageMalloc(pageSize);
33569       if( !pNew ){
33570         rc = SQLITE_NOMEM;
33571       }else{
33572         pager_reset(pPager);
33573         pPager->pageSize = pageSize;
33574         sqlite3PageFree(pPager->pTmpSpace);
33575         pPager->pTmpSpace = pNew;
33576         sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
33577       }
33578     }
33579     *pPageSize = (u16)pPager->pageSize;
33580     if( nReserve<0 ) nReserve = pPager->nReserve;
33581     assert( nReserve>=0 && nReserve<1000 );
33582     pPager->nReserve = (i16)nReserve;
33583     pagerReportSize(pPager);
33584   }
33585   return rc;
33586 }
33587
33588 /*
33589 ** Return a pointer to the "temporary page" buffer held internally
33590 ** by the pager.  This is a buffer that is big enough to hold the
33591 ** entire content of a database page.  This buffer is used internally
33592 ** during rollback and will be overwritten whenever a rollback
33593 ** occurs.  But other modules are free to use it too, as long as
33594 ** no rollbacks are happening.
33595 */
33596 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
33597   return pPager->pTmpSpace;
33598 }
33599
33600 /*
33601 ** Attempt to set the maximum database page count if mxPage is positive. 
33602 ** Make no changes if mxPage is zero or negative.  And never reduce the
33603 ** maximum page count below the current size of the database.
33604 **
33605 ** Regardless of mxPage, return the current maximum page count.
33606 */
33607 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
33608   if( mxPage>0 ){
33609     pPager->mxPgno = mxPage;
33610   }
33611   sqlite3PagerPagecount(pPager, 0);
33612   return pPager->mxPgno;
33613 }
33614
33615 /*
33616 ** The following set of routines are used to disable the simulated
33617 ** I/O error mechanism.  These routines are used to avoid simulated
33618 ** errors in places where we do not care about errors.
33619 **
33620 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
33621 ** and generate no code.
33622 */
33623 #ifdef SQLITE_TEST
33624 SQLITE_API extern int sqlite3_io_error_pending;
33625 SQLITE_API extern int sqlite3_io_error_hit;
33626 static int saved_cnt;
33627 void disable_simulated_io_errors(void){
33628   saved_cnt = sqlite3_io_error_pending;
33629   sqlite3_io_error_pending = -1;
33630 }
33631 void enable_simulated_io_errors(void){
33632   sqlite3_io_error_pending = saved_cnt;
33633 }
33634 #else
33635 # define disable_simulated_io_errors()
33636 # define enable_simulated_io_errors()
33637 #endif
33638
33639 /*
33640 ** Read the first N bytes from the beginning of the file into memory
33641 ** that pDest points to. 
33642 **
33643 ** If the pager was opened on a transient file (zFilename==""), or
33644 ** opened on a file less than N bytes in size, the output buffer is
33645 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
33646 ** function is used to read database headers, and a new transient or
33647 ** zero sized database has a header than consists entirely of zeroes.
33648 **
33649 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
33650 ** the error code is returned to the caller and the contents of the
33651 ** output buffer undefined.
33652 */
33653 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
33654   int rc = SQLITE_OK;
33655   memset(pDest, 0, N);
33656   assert( isOpen(pPager->fd) || pPager->tempFile );
33657   if( isOpen(pPager->fd) ){
33658     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
33659     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
33660     if( rc==SQLITE_IOERR_SHORT_READ ){
33661       rc = SQLITE_OK;
33662     }
33663   }
33664   return rc;
33665 }
33666
33667 /*
33668 ** Return the total number of pages in the database file associated 
33669 ** with pPager. Normally, this is calculated as (<db file size>/<page-size>).
33670 ** However, if the file is between 1 and <page-size> bytes in size, then 
33671 ** this is considered a 1 page file.
33672 **
33673 ** If the pager is in error state when this function is called, then the
33674 ** error state error code is returned and *pnPage left unchanged. Or,
33675 ** if the file system has to be queried for the size of the file and
33676 ** the query attempt returns an IO error, the IO error code is returned
33677 ** and *pnPage is left unchanged.
33678 **
33679 ** Otherwise, if everything is successful, then SQLITE_OK is returned
33680 ** and *pnPage is set to the number of pages in the database.
33681 */
33682 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
33683   Pgno nPage;               /* Value to return via *pnPage */
33684
33685   /* If the pager is already in the error state, return the error code. */
33686   if( pPager->errCode ){
33687     return pPager->errCode;
33688   }
33689
33690   /* Determine the number of pages in the file. Store this in nPage. */
33691   if( pPager->dbSizeValid ){
33692     nPage = pPager->dbSize;
33693   }else{
33694     int rc;                 /* Error returned by OsFileSize() */
33695     i64 n = 0;              /* File size in bytes returned by OsFileSize() */
33696
33697     assert( isOpen(pPager->fd) || pPager->tempFile );
33698     if( isOpen(pPager->fd) && (0 != (rc = sqlite3OsFileSize(pPager->fd, &n))) ){
33699       pager_error(pPager, rc);
33700       return rc;
33701     }
33702     if( n>0 && n<pPager->pageSize ){
33703       nPage = 1;
33704     }else{
33705       nPage = (Pgno)(n / pPager->pageSize);
33706     }
33707     if( pPager->state!=PAGER_UNLOCK ){
33708       pPager->dbSize = nPage;
33709       pPager->dbFileSize = nPage;
33710       pPager->dbSizeValid = 1;
33711     }
33712   }
33713
33714   /* If the current number of pages in the file is greater than the 
33715   ** configured maximum pager number, increase the allowed limit so
33716   ** that the file can be read.
33717   */
33718   if( nPage>pPager->mxPgno ){
33719     pPager->mxPgno = (Pgno)nPage;
33720   }
33721
33722   /* Set the output variable and return SQLITE_OK */
33723   if( pnPage ){
33724     *pnPage = nPage;
33725   }
33726   return SQLITE_OK;
33727 }
33728
33729
33730 /*
33731 ** Try to obtain a lock of type locktype on the database file. If
33732 ** a similar or greater lock is already held, this function is a no-op
33733 ** (returning SQLITE_OK immediately).
33734 **
33735 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
33736 ** the busy callback if the lock is currently not available. Repeat 
33737 ** until the busy callback returns false or until the attempt to 
33738 ** obtain the lock succeeds.
33739 **
33740 ** Return SQLITE_OK on success and an error code if we cannot obtain
33741 ** the lock. If the lock is obtained successfully, set the Pager.state 
33742 ** variable to locktype before returning.
33743 */
33744 static int pager_wait_on_lock(Pager *pPager, int locktype){
33745   int rc;                              /* Return code */
33746
33747   /* The OS lock values must be the same as the Pager lock values */
33748   assert( PAGER_SHARED==SHARED_LOCK );
33749   assert( PAGER_RESERVED==RESERVED_LOCK );
33750   assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
33751
33752   /* If the file is currently unlocked then the size must be unknown. It
33753   ** must not have been modified at this point.
33754   */
33755   assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );
33756   assert( pPager->state>=PAGER_SHARED || pPager->dbModified==0 );
33757
33758   /* Check that this is either a no-op (because the requested lock is 
33759   ** already held, or one of the transistions that the busy-handler
33760   ** may be invoked during, according to the comment above
33761   ** sqlite3PagerSetBusyhandler().
33762   */
33763   assert( (pPager->state>=locktype)
33764        || (pPager->state==PAGER_UNLOCK && locktype==PAGER_SHARED)
33765        || (pPager->state==PAGER_RESERVED && locktype==PAGER_EXCLUSIVE)
33766   );
33767
33768   if( pPager->state>=locktype ){
33769     rc = SQLITE_OK;
33770   }else{
33771     do {
33772       rc = sqlite3OsLock(pPager->fd, locktype);
33773     }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
33774     if( rc==SQLITE_OK ){
33775       pPager->state = (u8)locktype;
33776       IOTRACE(("LOCK %p %d\n", pPager, locktype))
33777     }
33778   }
33779   return rc;
33780 }
33781
33782 /*
33783 ** Function assertTruncateConstraint(pPager) checks that one of the 
33784 ** following is true for all dirty pages currently in the page-cache:
33785 **
33786 **   a) The page number is less than or equal to the size of the 
33787 **      current database image, in pages, OR
33788 **
33789 **   b) if the page content were written at this time, it would not
33790 **      be necessary to write the current content out to the sub-journal
33791 **      (as determined by function subjRequiresPage()).
33792 **
33793 ** If the condition asserted by this function were not true, and the
33794 ** dirty page were to be discarded from the cache via the pagerStress()
33795 ** routine, pagerStress() would not write the current page content to
33796 ** the database file. If a savepoint transaction were rolled back after
33797 ** this happened, the correct behaviour would be to restore the current
33798 ** content of the page. However, since this content is not present in either
33799 ** the database file or the portion of the rollback journal and 
33800 ** sub-journal rolled back the content could not be restored and the
33801 ** database image would become corrupt. It is therefore fortunate that 
33802 ** this circumstance cannot arise.
33803 */
33804 #if defined(SQLITE_DEBUG)
33805 static void assertTruncateConstraintCb(PgHdr *pPg){
33806   assert( pPg->flags&PGHDR_DIRTY );
33807   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
33808 }
33809 static void assertTruncateConstraint(Pager *pPager){
33810   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
33811 }
33812 #else
33813 # define assertTruncateConstraint(pPager)
33814 #endif
33815
33816 /*
33817 ** Truncate the in-memory database file image to nPage pages. This 
33818 ** function does not actually modify the database file on disk. It 
33819 ** just sets the internal state of the pager object so that the 
33820 ** truncation will be done when the current transaction is committed.
33821 */
33822 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
33823   assert( pPager->dbSizeValid );
33824   assert( pPager->dbSize>=nPage );
33825   assert( pPager->state>=PAGER_RESERVED );
33826   pPager->dbSize = nPage;
33827   assertTruncateConstraint(pPager);
33828 }
33829
33830 /*
33831 ** Shutdown the page cache.  Free all memory and close all files.
33832 **
33833 ** If a transaction was in progress when this routine is called, that
33834 ** transaction is rolled back.  All outstanding pages are invalidated
33835 ** and their memory is freed.  Any attempt to use a page associated
33836 ** with this page cache after this function returns will likely
33837 ** result in a coredump.
33838 **
33839 ** This function always succeeds. If a transaction is active an attempt
33840 ** is made to roll it back. If an error occurs during the rollback 
33841 ** a hot journal may be left in the filesystem but no error is returned
33842 ** to the caller.
33843 */
33844 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
33845   disable_simulated_io_errors();
33846   sqlite3BeginBenignMalloc();
33847   pPager->errCode = 0;
33848   pPager->exclusiveMode = 0;
33849   pager_reset(pPager);
33850   if( MEMDB ){
33851     pager_unlock(pPager);
33852   }else{
33853     /* Set Pager.journalHdr to -1 for the benefit of the pager_playback() 
33854     ** call which may be made from within pagerUnlockAndRollback(). If it
33855     ** is not -1, then the unsynced portion of an open journal file may
33856     ** be played back into the database. If a power failure occurs while
33857     ** this is happening, the database may become corrupt.
33858     */
33859     pPager->journalHdr = -1;
33860     pagerUnlockAndRollback(pPager);
33861   }
33862   sqlite3EndBenignMalloc();
33863   enable_simulated_io_errors();
33864   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
33865   IOTRACE(("CLOSE %p\n", pPager))
33866   sqlite3OsClose(pPager->fd);
33867   sqlite3PageFree(pPager->pTmpSpace);
33868   sqlite3PcacheClose(pPager->pPCache);
33869
33870 #ifdef SQLITE_HAS_CODEC
33871   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
33872 #endif
33873
33874   assert( !pPager->aSavepoint && !pPager->pInJournal );
33875   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
33876
33877   sqlite3_free(pPager);
33878   return SQLITE_OK;
33879 }
33880
33881 #if !defined(NDEBUG) || defined(SQLITE_TEST)
33882 /*
33883 ** Return the page number for page pPg.
33884 */
33885 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
33886   return pPg->pgno;
33887 }
33888 #endif
33889
33890 /*
33891 ** Increment the reference count for page pPg.
33892 */
33893 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
33894   sqlite3PcacheRef(pPg);
33895 }
33896
33897 /*
33898 ** Sync the journal. In other words, make sure all the pages that have
33899 ** been written to the journal have actually reached the surface of the
33900 ** disk and can be restored in the event of a hot-journal rollback.
33901 **
33902 ** If the Pager.needSync flag is not set, then this function is a
33903 ** no-op. Otherwise, the actions required depend on the journal-mode
33904 ** and the device characteristics of the the file-system, as follows:
33905 **
33906 **   * If the journal file is an in-memory journal file, no action need
33907 **     be taken.
33908 **
33909 **   * Otherwise, if the device does not support the SAFE_APPEND property,
33910 **     then the nRec field of the most recently written journal header
33911 **     is updated to contain the number of journal records that have
33912 **     been written following it. If the pager is operating in full-sync
33913 **     mode, then the journal file is synced before this field is updated.
33914 **
33915 **   * If the device does not support the SEQUENTIAL property, then 
33916 **     journal file is synced.
33917 **
33918 ** Or, in pseudo-code:
33919 **
33920 **   if( NOT <in-memory journal> ){
33921 **     if( NOT SAFE_APPEND ){
33922 **       if( <full-sync mode> ) xSync(<journal file>);
33923 **       <update nRec field>
33924 **     } 
33925 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
33926 **   }
33927 **
33928 ** The Pager.needSync flag is never be set for temporary files, or any
33929 ** file operating in no-sync mode (Pager.noSync set to non-zero).
33930 **
33931 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
33932 ** page currently held in memory before returning SQLITE_OK. If an IO
33933 ** error is encountered, then the IO error code is returned to the caller.
33934 */
33935 static int syncJournal(Pager *pPager){
33936   if( pPager->needSync ){
33937     assert( !pPager->tempFile );
33938     if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
33939       int rc;                              /* Return code */
33940       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
33941       assert( isOpen(pPager->jfd) );
33942
33943       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
33944         /* This block deals with an obscure problem. If the last connection
33945         ** that wrote to this database was operating in persistent-journal
33946         ** mode, then the journal file may at this point actually be larger
33947         ** than Pager.journalOff bytes. If the next thing in the journal
33948         ** file happens to be a journal-header (written as part of the
33949         ** previous connections transaction), and a crash or power-failure 
33950         ** occurs after nRec is updated but before this connection writes 
33951         ** anything else to the journal file (or commits/rolls back its 
33952         ** transaction), then SQLite may become confused when doing the 
33953         ** hot-journal rollback following recovery. It may roll back all
33954         ** of this connections data, then proceed to rolling back the old,
33955         ** out-of-date data that follows it. Database corruption.
33956         **
33957         ** To work around this, if the journal file does appear to contain
33958         ** a valid header following Pager.journalOff, then write a 0x00
33959         ** byte to the start of it to prevent it from being recognized.
33960         **
33961         ** Variable iNextHdrOffset is set to the offset at which this
33962         ** problematic header will occur, if it exists. aMagic is used 
33963         ** as a temporary buffer to inspect the first couple of bytes of
33964         ** the potential journal header.
33965         */
33966         i64 iNextHdrOffset;
33967         u8 aMagic[8];
33968         u8 zHeader[sizeof(aJournalMagic)+4];
33969
33970         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
33971         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
33972
33973         iNextHdrOffset = journalHdrOffset(pPager);
33974         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
33975         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
33976           static const u8 zerobyte = 0;
33977           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
33978         }
33979         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
33980           return rc;
33981         }
33982
33983         /* Write the nRec value into the journal file header. If in
33984         ** full-synchronous mode, sync the journal first. This ensures that
33985         ** all data has really hit the disk before nRec is updated to mark
33986         ** it as a candidate for rollback.
33987         **
33988         ** This is not required if the persistent media supports the
33989         ** SAFE_APPEND property. Because in this case it is not possible 
33990         ** for garbage data to be appended to the file, the nRec field
33991         ** is populated with 0xFFFFFFFF when the journal header is written
33992         ** and never needs to be updated.
33993         */
33994         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
33995           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
33996           IOTRACE(("JSYNC %p\n", pPager))
33997           rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
33998           if( rc!=SQLITE_OK ) return rc;
33999         }
34000         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
34001         rc = sqlite3OsWrite(
34002             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
34003         );
34004         if( rc!=SQLITE_OK ) return rc;
34005       }
34006       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
34007         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
34008         IOTRACE(("JSYNC %p\n", pPager))
34009         rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
34010           (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
34011         );
34012         if( rc!=SQLITE_OK ) return rc;
34013       }
34014     }
34015
34016     /* The journal file was just successfully synced. Set Pager.needSync 
34017     ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess.
34018     */
34019     pPager->needSync = 0;
34020     pPager->journalStarted = 1;
34021     sqlite3PcacheClearSyncFlags(pPager->pPCache);
34022   }
34023
34024   return SQLITE_OK;
34025 }
34026
34027 /*
34028 ** The argument is the first in a linked list of dirty pages connected
34029 ** by the PgHdr.pDirty pointer. This function writes each one of the
34030 ** in-memory pages in the list to the database file. The argument may
34031 ** be NULL, representing an empty list. In this case this function is
34032 ** a no-op.
34033 **
34034 ** The pager must hold at least a RESERVED lock when this function
34035 ** is called. Before writing anything to the database file, this lock
34036 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
34037 ** SQLITE_BUSY is returned and no data is written to the database file.
34038 ** 
34039 ** If the pager is a temp-file pager and the actual file-system file
34040 ** is not yet open, it is created and opened before any data is 
34041 ** written out.
34042 **
34043 ** Once the lock has been upgraded and, if necessary, the file opened,
34044 ** the pages are written out to the database file in list order. Writing
34045 ** a page is skipped if it meets either of the following criteria:
34046 **
34047 **   * The page number is greater than Pager.dbSize, or
34048 **   * The PGHDR_DONT_WRITE flag is set on the page.
34049 **
34050 ** If writing out a page causes the database file to grow, Pager.dbFileSize
34051 ** is updated accordingly. If page 1 is written out, then the value cached
34052 ** in Pager.dbFileVers[] is updated to match the new value stored in
34053 ** the database file.
34054 **
34055 ** If everything is successful, SQLITE_OK is returned. If an IO error 
34056 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
34057 ** be obtained, SQLITE_BUSY is returned.
34058 */
34059 static int pager_write_pagelist(PgHdr *pList){
34060   Pager *pPager;                       /* Pager object */
34061   int rc;                              /* Return code */
34062
34063   if( NEVER(pList==0) ) return SQLITE_OK;
34064   pPager = pList->pPager;
34065
34066   /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
34067   ** database file. If there is already an EXCLUSIVE lock, the following
34068   ** call is a no-op.
34069   **
34070   ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
34071   ** through an intermediate state PENDING.   A PENDING lock prevents new
34072   ** readers from attaching to the database but is unsufficient for us to
34073   ** write.  The idea of a PENDING lock is to prevent new readers from
34074   ** coming in while we wait for existing readers to clear.
34075   **
34076   ** While the pager is in the RESERVED state, the original database file
34077   ** is unchanged and we can rollback without having to playback the
34078   ** journal into the original database file.  Once we transition to
34079   ** EXCLUSIVE, it means the database file has been changed and any rollback
34080   ** will require a journal playback.
34081   */
34082   assert( pPager->state>=PAGER_RESERVED );
34083   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
34084
34085   /* If the file is a temp-file has not yet been opened, open it now. It
34086   ** is not possible for rc to be other than SQLITE_OK if this branch
34087   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
34088   */
34089   if( !isOpen(pPager->fd) ){
34090     assert( pPager->tempFile && rc==SQLITE_OK );
34091     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
34092   }
34093
34094   while( rc==SQLITE_OK && pList ){
34095     Pgno pgno = pList->pgno;
34096
34097     /* If there are dirty pages in the page cache with page numbers greater
34098     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
34099     ** make the file smaller (presumably by auto-vacuum code). Do not write
34100     ** any such pages to the file.
34101     **
34102     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
34103     ** set (set by sqlite3PagerDontWrite()).  Note that if compiled with
34104     ** SQLITE_SECURE_DELETE the PGHDR_DONT_WRITE bit is never set and so
34105     ** the second test is always true.
34106     */
34107     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
34108       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
34109       char *pData;                                   /* Data to write */    
34110
34111       /* Encode the database */
34112       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
34113
34114       /* Write out the page data. */
34115       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
34116
34117       /* If page 1 was just written, update Pager.dbFileVers to match
34118       ** the value now stored in the database file. If writing this 
34119       ** page caused the database file to grow, update dbFileSize. 
34120       */
34121       if( pgno==1 ){
34122         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
34123       }
34124       if( pgno>pPager->dbFileSize ){
34125         pPager->dbFileSize = pgno;
34126       }
34127
34128       /* Update any backup objects copying the contents of this pager. */
34129       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
34130
34131       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
34132                    PAGERID(pPager), pgno, pager_pagehash(pList)));
34133       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
34134       PAGER_INCR(sqlite3_pager_writedb_count);
34135       PAGER_INCR(pPager->nWrite);
34136     }else{
34137       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
34138     }
34139 #ifdef SQLITE_CHECK_PAGES
34140     pList->pageHash = pager_pagehash(pList);
34141 #endif
34142     pList = pList->pDirty;
34143   }
34144
34145   return rc;
34146 }
34147
34148 /*
34149 ** Append a record of the current state of page pPg to the sub-journal. 
34150 ** It is the callers responsibility to use subjRequiresPage() to check 
34151 ** that it is really required before calling this function.
34152 **
34153 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
34154 ** for all open savepoints before returning.
34155 **
34156 ** This function returns SQLITE_OK if everything is successful, an IO
34157 ** error code if the attempt to write to the sub-journal fails, or 
34158 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
34159 ** bitvec.
34160 */
34161 static int subjournalPage(PgHdr *pPg){
34162   int rc = SQLITE_OK;
34163   Pager *pPager = pPg->pPager;
34164   if( isOpen(pPager->sjfd) ){
34165     void *pData = pPg->pData;
34166     i64 offset = pPager->nSubRec*(4+pPager->pageSize);
34167     char *pData2;
34168
34169     CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
34170     PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
34171   
34172     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
34173     rc = write32bits(pPager->sjfd, offset, pPg->pgno);
34174     if( rc==SQLITE_OK ){
34175       rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
34176     }
34177   }
34178   if( rc==SQLITE_OK ){
34179     pPager->nSubRec++;
34180     assert( pPager->nSavepoint>0 );
34181     rc = addToSavepointBitvecs(pPager, pPg->pgno);
34182   }
34183   return rc;
34184 }
34185
34186
34187 /*
34188 ** This function is called by the pcache layer when it has reached some
34189 ** soft memory limit. The first argument is a pointer to a Pager object
34190 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
34191 ** database). The second argument is a reference to a page that is 
34192 ** currently dirty but has no outstanding references. The page
34193 ** is always associated with the Pager object passed as the first 
34194 ** argument.
34195 **
34196 ** The job of this function is to make pPg clean by writing its contents
34197 ** out to the database file, if possible. This may involve syncing the
34198 ** journal file. 
34199 **
34200 ** If successful, sqlite3PcacheMakeClean() is called on the page and
34201 ** SQLITE_OK returned. If an IO error occurs while trying to make the
34202 ** page clean, the IO error code is returned. If the page cannot be
34203 ** made clean for some other reason, but no error occurs, then SQLITE_OK
34204 ** is returned by sqlite3PcacheMakeClean() is not called.
34205 */
34206 static int pagerStress(void *p, PgHdr *pPg){
34207   Pager *pPager = (Pager *)p;
34208   int rc = SQLITE_OK;
34209
34210   assert( pPg->pPager==pPager );
34211   assert( pPg->flags&PGHDR_DIRTY );
34212
34213   /* The doNotSync flag is set by the sqlite3PagerWrite() function while it
34214   ** is journalling a set of two or more database pages that are stored
34215   ** on the same disk sector. Syncing the journal is not allowed while
34216   ** this is happening as it is important that all members of such a
34217   ** set of pages are synced to disk together. So, if the page this function
34218   ** is trying to make clean will require a journal sync and the doNotSync
34219   ** flag is set, return without doing anything. The pcache layer will
34220   ** just have to go ahead and allocate a new page buffer instead of
34221   ** reusing pPg.
34222   **
34223   ** Similarly, if the pager has already entered the error state, do not
34224   ** try to write the contents of pPg to disk.
34225   */
34226   if( NEVER(pPager->errCode)
34227    || (pPager->doNotSync && pPg->flags&PGHDR_NEED_SYNC)
34228   ){
34229     return SQLITE_OK;
34230   }
34231
34232   /* Sync the journal file if required. */
34233   if( pPg->flags&PGHDR_NEED_SYNC ){
34234     rc = syncJournal(pPager);
34235     if( rc==SQLITE_OK && pPager->fullSync && 
34236       !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
34237       !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
34238     ){
34239       pPager->nRec = 0;
34240       rc = writeJournalHdr(pPager);
34241     }
34242   }
34243
34244   /* If the page number of this page is larger than the current size of
34245   ** the database image, it may need to be written to the sub-journal.
34246   ** This is because the call to pager_write_pagelist() below will not
34247   ** actually write data to the file in this case.
34248   **
34249   ** Consider the following sequence of events:
34250   **
34251   **   BEGIN;
34252   **     <journal page X>
34253   **     <modify page X>
34254   **     SAVEPOINT sp;
34255   **       <shrink database file to Y pages>
34256   **       pagerStress(page X)
34257   **     ROLLBACK TO sp;
34258   **
34259   ** If (X>Y), then when pagerStress is called page X will not be written
34260   ** out to the database file, but will be dropped from the cache. Then,
34261   ** following the "ROLLBACK TO sp" statement, reading page X will read
34262   ** data from the database file. This will be the copy of page X as it
34263   ** was when the transaction started, not as it was when "SAVEPOINT sp"
34264   ** was executed.
34265   **
34266   ** The solution is to write the current data for page X into the 
34267   ** sub-journal file now (if it is not already there), so that it will
34268   ** be restored to its current value when the "ROLLBACK TO sp" is 
34269   ** executed.
34270   */
34271   if( NEVER(
34272       rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
34273   ) ){
34274     rc = subjournalPage(pPg);
34275   }
34276
34277   /* Write the contents of the page out to the database file. */
34278   if( rc==SQLITE_OK ){
34279     pPg->pDirty = 0;
34280     rc = pager_write_pagelist(pPg);
34281   }
34282
34283   /* Mark the page as clean. */
34284   if( rc==SQLITE_OK ){
34285     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
34286     sqlite3PcacheMakeClean(pPg);
34287   }
34288
34289   return pager_error(pPager, rc);
34290 }
34291
34292
34293 /*
34294 ** Allocate and initialize a new Pager object and put a pointer to it
34295 ** in *ppPager. The pager should eventually be freed by passing it
34296 ** to sqlite3PagerClose().
34297 **
34298 ** The zFilename argument is the path to the database file to open.
34299 ** If zFilename is NULL then a randomly-named temporary file is created
34300 ** and used as the file to be cached. Temporary files are be deleted
34301 ** automatically when they are closed. If zFilename is ":memory:" then 
34302 ** all information is held in cache. It is never written to disk. 
34303 ** This can be used to implement an in-memory database.
34304 **
34305 ** The nExtra parameter specifies the number of bytes of space allocated
34306 ** along with each page reference. This space is available to the user
34307 ** via the sqlite3PagerGetExtra() API.
34308 **
34309 ** The flags argument is used to specify properties that affect the
34310 ** operation of the pager. It should be passed some bitwise combination
34311 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
34312 **
34313 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
34314 ** of the xOpen() method of the supplied VFS when opening files. 
34315 **
34316 ** If the pager object is allocated and the specified file opened 
34317 ** successfully, SQLITE_OK is returned and *ppPager set to point to
34318 ** the new pager object. If an error occurs, *ppPager is set to NULL
34319 ** and error code returned. This function may return SQLITE_NOMEM
34320 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
34321 ** various SQLITE_IO_XXX errors.
34322 */
34323 SQLITE_PRIVATE int sqlite3PagerOpen(
34324   sqlite3_vfs *pVfs,       /* The virtual file system to use */
34325   Pager **ppPager,         /* OUT: Return the Pager structure here */
34326   const char *zFilename,   /* Name of the database file to open */
34327   int nExtra,              /* Extra bytes append to each in-memory page */
34328   int flags,               /* flags controlling this file */
34329   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
34330   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
34331 ){
34332   u8 *pPtr;
34333   Pager *pPager = 0;       /* Pager object to allocate and return */
34334   int rc = SQLITE_OK;      /* Return code */
34335   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
34336   int memDb = 0;           /* True if this is an in-memory file */
34337   int readOnly = 0;        /* True if this is a read-only file */
34338   int journalFileSize;     /* Bytes to allocate for each journal fd */
34339   char *zPathname = 0;     /* Full path to database file */
34340   int nPathname = 0;       /* Number of bytes in zPathname */
34341   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
34342   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
34343   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
34344   u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
34345
34346   /* Figure out how much space is required for each journal file-handle
34347   ** (there are two of them, the main journal and the sub-journal). This
34348   ** is the maximum space required for an in-memory journal file handle 
34349   ** and a regular journal file-handle. Note that a "regular journal-handle"
34350   ** may be a wrapper capable of caching the first portion of the journal
34351   ** file in memory to implement the atomic-write optimization (see 
34352   ** source file journal.c).
34353   */
34354   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
34355     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
34356   }else{
34357     journalFileSize = ROUND8(sqlite3MemJournalSize());
34358   }
34359
34360   /* Set the output variable to NULL in case an error occurs. */
34361   *ppPager = 0;
34362
34363   /* Compute and store the full pathname in an allocated buffer pointed
34364   ** to by zPathname, length nPathname. Or, if this is a temporary file,
34365   ** leave both nPathname and zPathname set to 0.
34366   */
34367   if( zFilename && zFilename[0] ){
34368     nPathname = pVfs->mxPathname+1;
34369     zPathname = sqlite3Malloc(nPathname*2);
34370     if( zPathname==0 ){
34371       return SQLITE_NOMEM;
34372     }
34373 #ifndef SQLITE_OMIT_MEMORYDB
34374     if( strcmp(zFilename,":memory:")==0 ){
34375       memDb = 1;
34376       zPathname[0] = 0;
34377     }else
34378 #endif
34379     {
34380       zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
34381       rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
34382     }
34383
34384     nPathname = sqlite3Strlen30(zPathname);
34385     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
34386       /* This branch is taken when the journal path required by
34387       ** the database being opened will be more than pVfs->mxPathname
34388       ** bytes in length. This means the database cannot be opened,
34389       ** as it will not be possible to open the journal file or even
34390       ** check for a hot-journal before reading.
34391       */
34392       rc = SQLITE_CANTOPEN;
34393     }
34394     if( rc!=SQLITE_OK ){
34395       sqlite3_free(zPathname);
34396       return rc;
34397     }
34398   }
34399
34400   /* Allocate memory for the Pager structure, PCache object, the
34401   ** three file descriptors, the database file name and the journal 
34402   ** file name. The layout in memory is as follows:
34403   **
34404   **     Pager object                    (sizeof(Pager) bytes)
34405   **     PCache object                   (sqlite3PcacheSize() bytes)
34406   **     Database file handle            (pVfs->szOsFile bytes)
34407   **     Sub-journal file handle         (journalFileSize bytes)
34408   **     Main journal file handle        (journalFileSize bytes)
34409   **     Database file name              (nPathname+1 bytes)
34410   **     Journal file name               (nPathname+8+1 bytes)
34411   */
34412   pPtr = (u8 *)sqlite3MallocZero(
34413     ROUND8(sizeof(*pPager)) +      /* Pager structure */
34414     ROUND8(pcacheSize) +           /* PCache object */
34415     ROUND8(pVfs->szOsFile) +       /* The main db file */
34416     journalFileSize * 2 +          /* The two journal files */ 
34417     nPathname + 1 +                /* zFilename */
34418     nPathname + 8 + 1              /* zJournal */
34419   );
34420   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
34421   if( !pPtr ){
34422     sqlite3_free(zPathname);
34423     return SQLITE_NOMEM;
34424   }
34425   pPager =              (Pager*)(pPtr);
34426   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
34427   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
34428   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
34429   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
34430   pPager->zFilename =    (char*)(pPtr += journalFileSize);
34431   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
34432
34433   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
34434   if( zPathname ){
34435     pPager->zJournal =   (char*)(pPtr += nPathname + 1);
34436     memcpy(pPager->zFilename, zPathname, nPathname);
34437     memcpy(pPager->zJournal, zPathname, nPathname);
34438     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
34439     if( pPager->zFilename[0]==0 ) pPager->zJournal[0] = 0;
34440     sqlite3_free(zPathname);
34441   }
34442   pPager->pVfs = pVfs;
34443   pPager->vfsFlags = vfsFlags;
34444
34445   /* Open the pager file.
34446   */
34447   if( zFilename && zFilename[0] && !memDb ){
34448     int fout = 0;                    /* VFS flags returned by xOpen() */
34449     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
34450     readOnly = (fout&SQLITE_OPEN_READONLY);
34451
34452     /* If the file was successfully opened for read/write access,
34453     ** choose a default page size in case we have to create the
34454     ** database file. The default page size is the maximum of:
34455     **
34456     **    + SQLITE_DEFAULT_PAGE_SIZE,
34457     **    + The value returned by sqlite3OsSectorSize()
34458     **    + The largest page size that can be written atomically.
34459     */
34460     if( rc==SQLITE_OK && !readOnly ){
34461       setSectorSize(pPager);
34462       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
34463       if( szPageDflt<pPager->sectorSize ){
34464         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
34465           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
34466         }else{
34467           szPageDflt = (u16)pPager->sectorSize;
34468         }
34469       }
34470 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
34471       {
34472         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
34473         int ii;
34474         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
34475         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
34476         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
34477         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
34478           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
34479             szPageDflt = ii;
34480           }
34481         }
34482       }
34483 #endif
34484     }
34485   }else{
34486     /* If a temporary file is requested, it is not opened immediately.
34487     ** In this case we accept the default page size and delay actually
34488     ** opening the file until the first call to OsWrite().
34489     **
34490     ** This branch is also run for an in-memory database. An in-memory
34491     ** database is the same as a temp-file that is never written out to
34492     ** disk and uses an in-memory rollback journal.
34493     */ 
34494     tempFile = 1;
34495     pPager->state = PAGER_EXCLUSIVE;
34496     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
34497   }
34498
34499   /* The following call to PagerSetPagesize() serves to set the value of 
34500   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
34501   */
34502   if( rc==SQLITE_OK ){
34503     assert( pPager->memDb==0 );
34504     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
34505     testcase( rc!=SQLITE_OK );
34506   }
34507
34508   /* If an error occurred in either of the blocks above, free the 
34509   ** Pager structure and close the file.
34510   */
34511   if( rc!=SQLITE_OK ){
34512     assert( !pPager->pTmpSpace );
34513     sqlite3OsClose(pPager->fd);
34514     sqlite3_free(pPager);
34515     return rc;
34516   }
34517
34518   /* Initialize the PCache object. */
34519   assert( nExtra<1000 );
34520   nExtra = ROUND8(nExtra);
34521   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
34522                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
34523
34524   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
34525   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
34526
34527   pPager->useJournal = (u8)useJournal;
34528   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
34529   /* pPager->stmtOpen = 0; */
34530   /* pPager->stmtInUse = 0; */
34531   /* pPager->nRef = 0; */
34532   pPager->dbSizeValid = (u8)memDb;
34533   /* pPager->stmtSize = 0; */
34534   /* pPager->stmtJSize = 0; */
34535   /* pPager->nPage = 0; */
34536   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
34537   /* pPager->state = PAGER_UNLOCK; */
34538   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
34539   /* pPager->errMask = 0; */
34540   pPager->tempFile = (u8)tempFile;
34541   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
34542           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
34543   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
34544   pPager->exclusiveMode = (u8)tempFile; 
34545   pPager->changeCountDone = pPager->tempFile;
34546   pPager->memDb = (u8)memDb;
34547   pPager->readOnly = (u8)readOnly;
34548   /* pPager->needSync = 0; */
34549   assert( useJournal || pPager->tempFile );
34550   pPager->noSync = pPager->tempFile;
34551   pPager->fullSync = pPager->noSync ?0:1;
34552   pPager->sync_flags = SQLITE_SYNC_NORMAL;
34553   /* pPager->pFirst = 0; */
34554   /* pPager->pFirstSynced = 0; */
34555   /* pPager->pLast = 0; */
34556   pPager->nExtra = (u16)nExtra;
34557   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
34558   assert( isOpen(pPager->fd) || tempFile );
34559   setSectorSize(pPager);
34560   if( !useJournal ){
34561     pPager->journalMode = PAGER_JOURNALMODE_OFF;
34562   }else if( memDb ){
34563     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
34564   }
34565   /* pPager->xBusyHandler = 0; */
34566   /* pPager->pBusyHandlerArg = 0; */
34567   pPager->xReiniter = xReinit;
34568   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
34569   *ppPager = pPager;
34570   return SQLITE_OK;
34571 }
34572
34573
34574
34575 /*
34576 ** This function is called after transitioning from PAGER_UNLOCK to
34577 ** PAGER_SHARED state. It tests if there is a hot journal present in
34578 ** the file-system for the given pager. A hot journal is one that 
34579 ** needs to be played back. According to this function, a hot-journal
34580 ** file exists if the following criteria are met:
34581 **
34582 **   * The journal file exists in the file system, and
34583 **   * No process holds a RESERVED or greater lock on the database file, and
34584 **   * The database file itself is greater than 0 bytes in size, and
34585 **   * The first byte of the journal file exists and is not 0x00.
34586 **
34587 ** If the current size of the database file is 0 but a journal file
34588 ** exists, that is probably an old journal left over from a prior
34589 ** database with the same name. In this case the journal file is
34590 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
34591 ** is returned.
34592 **
34593 ** This routine does not check if there is a master journal filename
34594 ** at the end of the file. If there is, and that master journal file
34595 ** does not exist, then the journal file is not really hot. In this
34596 ** case this routine will return a false-positive. The pager_playback()
34597 ** routine will discover that the journal file is not really hot and 
34598 ** will not roll it back. 
34599 **
34600 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
34601 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
34602 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
34603 ** to determine whether or not a hot-journal file exists, the IO error
34604 ** code is returned and the value of *pExists is undefined.
34605 */
34606 static int hasHotJournal(Pager *pPager, int *pExists){
34607   sqlite3_vfs * const pVfs = pPager->pVfs;
34608   int rc;                       /* Return code */
34609   int exists;                   /* True if a journal file is present */
34610
34611   assert( pPager!=0 );
34612   assert( pPager->useJournal );
34613   assert( isOpen(pPager->fd) );
34614   assert( !isOpen(pPager->jfd) );
34615   assert( pPager->state <= PAGER_SHARED );
34616
34617   *pExists = 0;
34618   rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
34619   if( rc==SQLITE_OK && exists ){
34620     int locked;                 /* True if some process holds a RESERVED lock */
34621
34622     /* Race condition here:  Another process might have been holding the
34623     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
34624     ** call above, but then delete the journal and drop the lock before
34625     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
34626     ** is the case, this routine might think there is a hot journal when
34627     ** in fact there is none.  This results in a false-positive which will
34628     ** be dealt with by the playback routine.  Ticket #3883.
34629     */
34630     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
34631     if( rc==SQLITE_OK && !locked ){
34632       int nPage;
34633
34634       /* Check the size of the database file. If it consists of 0 pages,
34635       ** then delete the journal file. See the header comment above for 
34636       ** the reasoning here.  Delete the obsolete journal file under
34637       ** a RESERVED lock to avoid race conditions and to avoid violating
34638       ** [H33020].
34639       */
34640       rc = sqlite3PagerPagecount(pPager, &nPage);
34641       if( rc==SQLITE_OK ){
34642         if( nPage==0 ){
34643           sqlite3BeginBenignMalloc();
34644           if( sqlite3OsLock(pPager->fd, RESERVED_LOCK)==SQLITE_OK ){
34645             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
34646             sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
34647           }
34648           sqlite3EndBenignMalloc();
34649         }else{
34650           /* The journal file exists and no other connection has a reserved
34651           ** or greater lock on the database file. Now check that there is
34652           ** at least one non-zero bytes at the start of the journal file.
34653           ** If there is, then we consider this journal to be hot. If not, 
34654           ** it can be ignored.
34655           */
34656           int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
34657           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
34658           if( rc==SQLITE_OK ){
34659             u8 first = 0;
34660             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
34661             if( rc==SQLITE_IOERR_SHORT_READ ){
34662               rc = SQLITE_OK;
34663             }
34664             sqlite3OsClose(pPager->jfd);
34665             *pExists = (first!=0);
34666           }else if( rc==SQLITE_CANTOPEN ){
34667             /* If we cannot open the rollback journal file in order to see if
34668             ** its has a zero header, that might be due to an I/O error, or
34669             ** it might be due to the race condition described above and in
34670             ** ticket #3883.  Either way, assume that the journal is hot.
34671             ** This might be a false positive.  But if it is, then the
34672             ** automatic journal playback and recovery mechanism will deal
34673             ** with it under an EXCLUSIVE lock where we do not need to
34674             ** worry so much with race conditions.
34675             */
34676             *pExists = 1;
34677             rc = SQLITE_OK;
34678           }
34679         }
34680       }
34681     }
34682   }
34683
34684   return rc;
34685 }
34686
34687 /*
34688 ** Read the content for page pPg out of the database file and into 
34689 ** pPg->pData. A shared lock or greater must be held on the database
34690 ** file before this function is called.
34691 **
34692 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
34693 ** the value read from the database file.
34694 **
34695 ** If an IO error occurs, then the IO error is returned to the caller.
34696 ** Otherwise, SQLITE_OK is returned.
34697 */
34698 static int readDbPage(PgHdr *pPg){
34699   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
34700   Pgno pgno = pPg->pgno;       /* Page number to read */
34701   int rc;                      /* Return code */
34702   i64 iOffset;                 /* Byte offset of file to read from */
34703
34704   assert( pPager->state>=PAGER_SHARED && !MEMDB );
34705   assert( isOpen(pPager->fd) );
34706
34707   if( NEVER(!isOpen(pPager->fd)) ){
34708     assert( pPager->tempFile );
34709     memset(pPg->pData, 0, pPager->pageSize);
34710     return SQLITE_OK;
34711   }
34712   iOffset = (pgno-1)*(i64)pPager->pageSize;
34713   rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
34714   if( rc==SQLITE_IOERR_SHORT_READ ){
34715     rc = SQLITE_OK;
34716   }
34717   if( pgno==1 ){
34718     u8 *dbFileVers = &((u8*)pPg->pData)[24];
34719     memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
34720   }
34721   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
34722
34723   PAGER_INCR(sqlite3_pager_readdb_count);
34724   PAGER_INCR(pPager->nRead);
34725   IOTRACE(("PGIN %p %d\n", pPager, pgno));
34726   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
34727                PAGERID(pPager), pgno, pager_pagehash(pPg)));
34728
34729   return rc;
34730 }
34731
34732 /*
34733 ** This function is called to obtain a shared lock on the database file.
34734 ** It is illegal to call sqlite3PagerAcquire() until after this function
34735 ** has been successfully called. If a shared-lock is already held when
34736 ** this function is called, it is a no-op.
34737 **
34738 ** The following operations are also performed by this function.
34739 **
34740 **   1) If the pager is currently in PAGER_UNLOCK state (no lock held
34741 **      on the database file), then an attempt is made to obtain a
34742 **      SHARED lock on the database file. Immediately after obtaining
34743 **      the SHARED lock, the file-system is checked for a hot-journal,
34744 **      which is played back if present. Following any hot-journal 
34745 **      rollback, the contents of the cache are validated by checking
34746 **      the 'change-counter' field of the database file header and
34747 **      discarded if they are found to be invalid.
34748 **
34749 **   2) If the pager is running in exclusive-mode, and there are currently
34750 **      no outstanding references to any pages, and is in the error state,
34751 **      then an attempt is made to clear the error state by discarding
34752 **      the contents of the page cache and rolling back any open journal
34753 **      file.
34754 **
34755 ** If the operation described by (2) above is not attempted, and if the
34756 ** pager is in an error state other than SQLITE_FULL when this is called,
34757 ** the error state error code is returned. It is permitted to read the
34758 ** database when in SQLITE_FULL error state.
34759 **
34760 ** Otherwise, if everything is successful, SQLITE_OK is returned. If an
34761 ** IO error occurs while locking the database, checking for a hot-journal
34762 ** file or rolling back a journal file, the IO error code is returned.
34763 */
34764 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
34765   int rc = SQLITE_OK;                /* Return code */
34766   int isErrorReset = 0;              /* True if recovering from error state */
34767
34768   /* This routine is only called from b-tree and only when there are no
34769   ** outstanding pages */
34770   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
34771   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
34772
34773   /* If this database is in an error-state, now is a chance to clear
34774   ** the error. Discard the contents of the pager-cache and rollback
34775   ** any hot journal in the file-system.
34776   */
34777   if( pPager->errCode ){
34778     if( isOpen(pPager->jfd) || pPager->zJournal ){
34779       isErrorReset = 1;
34780     }
34781     pPager->errCode = SQLITE_OK;
34782     pager_reset(pPager);
34783   }
34784
34785   if( pPager->state==PAGER_UNLOCK || isErrorReset ){
34786     sqlite3_vfs * const pVfs = pPager->pVfs;
34787     int isHotJournal = 0;
34788     assert( !MEMDB );
34789     assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
34790     if( pPager->noReadlock ){
34791       assert( pPager->readOnly );
34792       pPager->state = PAGER_SHARED;
34793     }else{
34794       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
34795       if( rc!=SQLITE_OK ){
34796         assert( pPager->state==PAGER_UNLOCK );
34797         return pager_error(pPager, rc);
34798       }
34799     }
34800     assert( pPager->state>=SHARED_LOCK );
34801
34802     /* If a journal file exists, and there is no RESERVED lock on the
34803     ** database file, then it either needs to be played back or deleted.
34804     */
34805     if( !isErrorReset ){
34806       assert( pPager->state <= PAGER_SHARED );
34807       rc = hasHotJournal(pPager, &isHotJournal);
34808       if( rc!=SQLITE_OK ){
34809         goto failed;
34810       }
34811     }
34812     if( isErrorReset || isHotJournal ){
34813       /* Get an EXCLUSIVE lock on the database file. At this point it is
34814       ** important that a RESERVED lock is not obtained on the way to the
34815       ** EXCLUSIVE lock. If it were, another process might open the
34816       ** database file, detect the RESERVED lock, and conclude that the
34817       ** database is safe to read while this process is still rolling the 
34818       ** hot-journal back.
34819       ** 
34820       ** Because the intermediate RESERVED lock is not requested, any
34821       ** other process attempting to access the database file will get to 
34822       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
34823       ** on the database file.
34824       */
34825       if( pPager->state<EXCLUSIVE_LOCK ){
34826         rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
34827         if( rc!=SQLITE_OK ){
34828           rc = pager_error(pPager, rc);
34829           goto failed;
34830         }
34831         pPager->state = PAGER_EXCLUSIVE;
34832       }
34833  
34834       /* Open the journal for read/write access. This is because in 
34835       ** exclusive-access mode the file descriptor will be kept open and
34836       ** possibly used for a transaction later on. On some systems, the
34837       ** OsTruncate() call used in exclusive-access mode also requires
34838       ** a read/write file handle.
34839       */
34840       if( !isOpen(pPager->jfd) ){
34841         int res;
34842         rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
34843         if( rc==SQLITE_OK ){
34844           if( res ){
34845             int fout = 0;
34846             int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
34847             assert( !pPager->tempFile );
34848             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
34849             assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
34850             if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
34851               rc = SQLITE_CANTOPEN;
34852               sqlite3OsClose(pPager->jfd);
34853             }
34854           }else{
34855             /* If the journal does not exist, it usually means that some 
34856             ** other connection managed to get in and roll it back before 
34857             ** this connection obtained the exclusive lock above. Or, it 
34858             ** may mean that the pager was in the error-state when this
34859             ** function was called and the journal file does not exist.  */
34860             rc = pager_end_transaction(pPager, 0);
34861           }
34862         }
34863       }
34864       if( rc!=SQLITE_OK ){
34865         goto failed;
34866       }
34867
34868       /* TODO: Why are these cleared here? Is it necessary? */
34869       pPager->journalStarted = 0;
34870       pPager->journalOff = 0;
34871       pPager->setMaster = 0;
34872       pPager->journalHdr = 0;
34873  
34874       /* Playback and delete the journal.  Drop the database write
34875       ** lock and reacquire the read lock. Purge the cache before
34876       ** playing back the hot-journal so that we don't end up with
34877       ** an inconsistent cache.
34878       */
34879       if( isOpen(pPager->jfd) ){
34880         rc = pager_playback(pPager, 1);
34881         if( rc!=SQLITE_OK ){
34882           rc = pager_error(pPager, rc);
34883           goto failed;
34884         }
34885       }
34886       assert( (pPager->state==PAGER_SHARED)
34887            || (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
34888       );
34889     }
34890
34891     if( pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0 ){
34892       /* The shared-lock has just been acquired on the database file
34893       ** and there are already pages in the cache (from a previous
34894       ** read or write transaction).  Check to see if the database
34895       ** has been modified.  If the database has changed, flush the
34896       ** cache.
34897       **
34898       ** Database changes is detected by looking at 15 bytes beginning
34899       ** at offset 24 into the file.  The first 4 of these 16 bytes are
34900       ** a 32-bit counter that is incremented with each change.  The
34901       ** other bytes change randomly with each file change when
34902       ** a codec is in use.
34903       ** 
34904       ** There is a vanishingly small chance that a change will not be 
34905       ** detected.  The chance of an undetected change is so small that
34906       ** it can be neglected.
34907       */
34908       char dbFileVers[sizeof(pPager->dbFileVers)];
34909       sqlite3PagerPagecount(pPager, 0);
34910
34911       if( pPager->errCode ){
34912         rc = pPager->errCode;
34913         goto failed;
34914       }
34915
34916       assert( pPager->dbSizeValid );
34917       if( pPager->dbSize>0 ){
34918         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
34919         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
34920         if( rc!=SQLITE_OK ){
34921           goto failed;
34922         }
34923       }else{
34924         memset(dbFileVers, 0, sizeof(dbFileVers));
34925       }
34926
34927       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
34928         pager_reset(pPager);
34929       }
34930     }
34931     assert( pPager->exclusiveMode || pPager->state==PAGER_SHARED );
34932   }
34933
34934  failed:
34935   if( rc!=SQLITE_OK ){
34936     /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
34937     pager_unlock(pPager);
34938   }
34939   return rc;
34940 }
34941
34942 /*
34943 ** If the reference count has reached zero, rollback any active
34944 ** transaction and unlock the pager.
34945 **
34946 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
34947 ** the rollback journal, the unlock is not performed and there is
34948 ** nothing to rollback, so this routine is a no-op.
34949 */ 
34950 static void pagerUnlockIfUnused(Pager *pPager){
34951   if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
34952    && (!pPager->exclusiveMode || pPager->journalOff>0) 
34953   ){
34954     pagerUnlockAndRollback(pPager);
34955   }
34956 }
34957
34958 /*
34959 ** Acquire a reference to page number pgno in pager pPager (a page
34960 ** reference has type DbPage*). If the requested reference is 
34961 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
34962 **
34963 ** If the requested page is already in the cache, it is returned. 
34964 ** Otherwise, a new page object is allocated and populated with data
34965 ** read from the database file. In some cases, the pcache module may
34966 ** choose not to allocate a new page object and may reuse an existing
34967 ** object with no outstanding references.
34968 **
34969 ** The extra data appended to a page is always initialized to zeros the 
34970 ** first time a page is loaded into memory. If the page requested is 
34971 ** already in the cache when this function is called, then the extra
34972 ** data is left as it was when the page object was last used.
34973 **
34974 ** If the database image is smaller than the requested page or if a 
34975 ** non-zero value is passed as the noContent parameter and the 
34976 ** requested page is not already stored in the cache, then no 
34977 ** actual disk read occurs. In this case the memory image of the 
34978 ** page is initialized to all zeros. 
34979 **
34980 ** If noContent is true, it means that we do not care about the contents
34981 ** of the page. This occurs in two seperate scenarios:
34982 **
34983 **   a) When reading a free-list leaf page from the database, and
34984 **
34985 **   b) When a savepoint is being rolled back and we need to load
34986 **      a new page into the cache to populate with the data read
34987 **      from the savepoint journal.
34988 **
34989 ** If noContent is true, then the data returned is zeroed instead of
34990 ** being read from the database. Additionally, the bits corresponding
34991 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
34992 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
34993 ** savepoints are set. This means if the page is made writable at any
34994 ** point in the future, using a call to sqlite3PagerWrite(), its contents
34995 ** will not be journaled. This saves IO.
34996 **
34997 ** The acquisition might fail for several reasons.  In all cases,
34998 ** an appropriate error code is returned and *ppPage is set to NULL.
34999 **
35000 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
35001 ** to find a page in the in-memory cache first.  If the page is not already
35002 ** in memory, this routine goes to disk to read it in whereas Lookup()
35003 ** just returns 0.  This routine acquires a read-lock the first time it
35004 ** has to go to disk, and could also playback an old journal if necessary.
35005 ** Since Lookup() never goes to disk, it never has to deal with locks
35006 ** or journal files.
35007 */
35008 SQLITE_PRIVATE int sqlite3PagerAcquire(
35009   Pager *pPager,      /* The pager open on the database file */
35010   Pgno pgno,          /* Page number to fetch */
35011   DbPage **ppPage,    /* Write a pointer to the page here */
35012   int noContent       /* Do not bother reading content from disk if true */
35013 ){
35014   int rc;
35015   PgHdr *pPg;
35016
35017   assert( assert_pager_state(pPager) );
35018   assert( pPager->state>PAGER_UNLOCK );
35019
35020   if( pgno==0 ){
35021     return SQLITE_CORRUPT_BKPT;
35022   }
35023
35024   /* If the pager is in the error state, return an error immediately. 
35025   ** Otherwise, request the page from the PCache layer. */
35026   if( pPager->errCode!=SQLITE_OK && pPager->errCode!=SQLITE_FULL ){
35027     rc = pPager->errCode;
35028   }else{
35029     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
35030   }
35031
35032   if( rc!=SQLITE_OK ){
35033     /* Either the call to sqlite3PcacheFetch() returned an error or the
35034     ** pager was already in the error-state when this function was called.
35035     ** Set pPg to 0 and jump to the exception handler.  */
35036     pPg = 0;
35037     goto pager_acquire_err;
35038   }
35039   assert( (*ppPage)->pgno==pgno );
35040   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
35041
35042   if( (*ppPage)->pPager ){
35043     /* In this case the pcache already contains an initialized copy of
35044     ** the page. Return without further ado.  */
35045     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
35046     PAGER_INCR(pPager->nHit);
35047     return SQLITE_OK;
35048
35049   }else{
35050     /* The pager cache has created a new page. Its content needs to 
35051     ** be initialized.  */
35052     int nMax;
35053
35054     PAGER_INCR(pPager->nMiss);
35055     pPg = *ppPage;
35056     pPg->pPager = pPager;
35057
35058     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
35059     ** number greater than this, or the unused locking-page, is requested. */
35060     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
35061       rc = SQLITE_CORRUPT_BKPT;
35062       goto pager_acquire_err;
35063     }
35064
35065     rc = sqlite3PagerPagecount(pPager, &nMax);
35066     if( rc!=SQLITE_OK ){
35067       goto pager_acquire_err;
35068     }
35069
35070     if( MEMDB || nMax<(int)pgno || noContent ){
35071       if( pgno>pPager->mxPgno ){
35072         rc = SQLITE_FULL;
35073         goto pager_acquire_err;
35074       }
35075       if( noContent ){
35076         /* Failure to set the bits in the InJournal bit-vectors is benign.
35077         ** It merely means that we might do some extra work to journal a 
35078         ** page that does not need to be journaled.  Nevertheless, be sure 
35079         ** to test the case where a malloc error occurs while trying to set 
35080         ** a bit in a bit vector.
35081         */
35082         sqlite3BeginBenignMalloc();
35083         if( pgno<=pPager->dbOrigSize ){
35084           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
35085           testcase( rc==SQLITE_NOMEM );
35086         }
35087         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
35088         testcase( rc==SQLITE_NOMEM );
35089         sqlite3EndBenignMalloc();
35090       }
35091       memset(pPg->pData, 0, pPager->pageSize);
35092       IOTRACE(("ZERO %p %d\n", pPager, pgno));
35093     }else{
35094       assert( pPg->pPager==pPager );
35095       rc = readDbPage(pPg);
35096       if( rc!=SQLITE_OK ){
35097         goto pager_acquire_err;
35098       }
35099     }
35100 #ifdef SQLITE_CHECK_PAGES
35101     pPg->pageHash = pager_pagehash(pPg);
35102 #endif
35103   }
35104
35105   return SQLITE_OK;
35106
35107 pager_acquire_err:
35108   assert( rc!=SQLITE_OK );
35109   if( pPg ){
35110     sqlite3PcacheDrop(pPg);
35111   }
35112   pagerUnlockIfUnused(pPager);
35113
35114   *ppPage = 0;
35115   return rc;
35116 }
35117
35118 /*
35119 ** Acquire a page if it is already in the in-memory cache.  Do
35120 ** not read the page from disk.  Return a pointer to the page,
35121 ** or 0 if the page is not in cache. Also, return 0 if the 
35122 ** pager is in PAGER_UNLOCK state when this function is called,
35123 ** or if the pager is in an error state other than SQLITE_FULL.
35124 **
35125 ** See also sqlite3PagerGet().  The difference between this routine
35126 ** and sqlite3PagerGet() is that _get() will go to the disk and read
35127 ** in the page if the page is not already in cache.  This routine
35128 ** returns NULL if the page is not in cache or if a disk I/O error 
35129 ** has ever happened.
35130 */
35131 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
35132   PgHdr *pPg = 0;
35133   assert( pPager!=0 );
35134   assert( pgno!=0 );
35135   assert( pPager->pPCache!=0 );
35136   assert( pPager->state > PAGER_UNLOCK );
35137   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
35138   return pPg;
35139 }
35140
35141 /*
35142 ** Release a page reference.
35143 **
35144 ** If the number of references to the page drop to zero, then the
35145 ** page is added to the LRU list.  When all references to all pages
35146 ** are released, a rollback occurs and the lock on the database is
35147 ** removed.
35148 */
35149 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
35150   if( pPg ){
35151     Pager *pPager = pPg->pPager;
35152     sqlite3PcacheRelease(pPg);
35153     pagerUnlockIfUnused(pPager);
35154   }
35155 }
35156
35157 /*
35158 ** If the main journal file has already been opened, ensure that the
35159 ** sub-journal file is open too. If the main journal is not open,
35160 ** this function is a no-op.
35161 **
35162 ** SQLITE_OK is returned if everything goes according to plan. 
35163 ** An SQLITE_IOERR_XXX error code is returned if a call to 
35164 ** sqlite3OsOpen() fails.
35165 */
35166 static int openSubJournal(Pager *pPager){
35167   int rc = SQLITE_OK;
35168   if( isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ){
35169     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
35170       sqlite3MemJournalOpen(pPager->sjfd);
35171     }else{
35172       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
35173     }
35174   }
35175   return rc;
35176 }
35177
35178 /*
35179 ** This function is called at the start of every write transaction.
35180 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
35181 ** file when this routine is called.
35182 **
35183 ** Open the journal file for pager pPager and write a journal header
35184 ** to the start of it. If there are active savepoints, open the sub-journal
35185 ** as well. This function is only used when the journal file is being 
35186 ** opened to write a rollback log for a transaction. It is not used 
35187 ** when opening a hot journal file to roll it back.
35188 **
35189 ** If the journal file is already open (as it may be in exclusive mode),
35190 ** then this function just writes a journal header to the start of the
35191 ** already open file. 
35192 **
35193 ** Whether or not the journal file is opened by this function, the
35194 ** Pager.pInJournal bitvec structure is allocated.
35195 **
35196 ** Return SQLITE_OK if everything is successful. Otherwise, return 
35197 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
35198 ** an IO error code if opening or writing the journal file fails.
35199 */
35200 static int pager_open_journal(Pager *pPager){
35201   int rc = SQLITE_OK;                        /* Return code */
35202   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
35203
35204   assert( pPager->state>=PAGER_RESERVED );
35205   assert( pPager->useJournal );
35206   assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF );
35207   assert( pPager->pInJournal==0 );
35208   
35209   /* If already in the error state, this function is a no-op.  But on
35210   ** the other hand, this routine is never called if we are already in
35211   ** an error state. */
35212   if( NEVER(pPager->errCode) ) return pPager->errCode;
35213
35214   /* TODO: Is it really possible to get here with dbSizeValid==0? If not,
35215   ** the call to PagerPagecount() can be removed.
35216   */
35217   testcase( pPager->dbSizeValid==0 );
35218   sqlite3PagerPagecount(pPager, 0);
35219
35220   pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
35221   if( pPager->pInJournal==0 ){
35222     return SQLITE_NOMEM;
35223   }
35224
35225   /* Open the journal file if it is not already open. */
35226   if( !isOpen(pPager->jfd) ){
35227     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
35228       sqlite3MemJournalOpen(pPager->jfd);
35229     }else{
35230       const int flags =                   /* VFS flags to open journal file */
35231         SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
35232         (pPager->tempFile ? 
35233           (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
35234           (SQLITE_OPEN_MAIN_JOURNAL)
35235         );
35236 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
35237       rc = sqlite3JournalOpen(
35238           pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
35239       );
35240 #else
35241       rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
35242 #endif
35243     }
35244     assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
35245   }
35246
35247
35248   /* Write the first journal header to the journal file and open 
35249   ** the sub-journal if necessary.
35250   */
35251   if( rc==SQLITE_OK ){
35252     /* TODO: Check if all of these are really required. */
35253     pPager->dbOrigSize = pPager->dbSize;
35254     pPager->journalStarted = 0;
35255     pPager->needSync = 0;
35256     pPager->nRec = 0;
35257     pPager->journalOff = 0;
35258     pPager->setMaster = 0;
35259     pPager->journalHdr = 0;
35260     rc = writeJournalHdr(pPager);
35261   }
35262   if( rc==SQLITE_OK && pPager->nSavepoint ){
35263     rc = openSubJournal(pPager);
35264   }
35265
35266   if( rc!=SQLITE_OK ){
35267     sqlite3BitvecDestroy(pPager->pInJournal);
35268     pPager->pInJournal = 0;
35269   }
35270   return rc;
35271 }
35272
35273 /*
35274 ** Begin a write-transaction on the specified pager object. If a 
35275 ** write-transaction has already been opened, this function is a no-op.
35276 **
35277 ** If the exFlag argument is false, then acquire at least a RESERVED
35278 ** lock on the database file. If exFlag is true, then acquire at least
35279 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
35280 ** functions need be called.
35281 **
35282 ** If this is not a temporary or in-memory file and, the journal file is 
35283 ** opened if it has not been already. For a temporary file, the opening 
35284 ** of the journal file is deferred until there is an actual need to 
35285 ** write to the journal. TODO: Why handle temporary files differently?
35286 **
35287 ** If the journal file is opened (or if it is already open), then a
35288 ** journal-header is written to the start of it.
35289 **
35290 ** If the subjInMemory argument is non-zero, then any sub-journal opened
35291 ** within this transaction will be opened as an in-memory file. This
35292 ** has no effect if the sub-journal is already opened (as it may be when
35293 ** running in exclusive mode) or if the transaction does not require a
35294 ** sub-journal. If the subjInMemory argument is zero, then any required
35295 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
35296 ** or using a temporary file otherwise.
35297 */
35298 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
35299   int rc = SQLITE_OK;
35300   assert( pPager->state!=PAGER_UNLOCK );
35301   pPager->subjInMemory = (u8)subjInMemory;
35302   if( pPager->state==PAGER_SHARED ){
35303     assert( pPager->pInJournal==0 );
35304     assert( !MEMDB && !pPager->tempFile );
35305
35306     /* Obtain a RESERVED lock on the database file. If the exFlag parameter
35307     ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
35308     ** busy-handler callback can be used when upgrading to the EXCLUSIVE
35309     ** lock, but not when obtaining the RESERVED lock.
35310     */
35311     rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
35312     if( rc==SQLITE_OK ){
35313       pPager->state = PAGER_RESERVED;
35314       if( exFlag ){
35315         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
35316       }
35317     }
35318
35319     /* If the required locks were successfully obtained, open the journal
35320     ** file and write the first journal-header to it.
35321     */
35322     if( rc==SQLITE_OK && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
35323       rc = pager_open_journal(pPager);
35324     }
35325   }else if( isOpen(pPager->jfd) && pPager->journalOff==0 ){
35326     /* This happens when the pager was in exclusive-access mode the last
35327     ** time a (read or write) transaction was successfully concluded
35328     ** by this connection. Instead of deleting the journal file it was 
35329     ** kept open and either was truncated to 0 bytes or its header was
35330     ** overwritten with zeros.
35331     */
35332     assert( pPager->nRec==0 );
35333     assert( pPager->dbOrigSize==0 );
35334     assert( pPager->pInJournal==0 );
35335     rc = pager_open_journal(pPager);
35336   }
35337
35338   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
35339   assert( !isOpen(pPager->jfd) || pPager->journalOff>0 || rc!=SQLITE_OK );
35340   if( rc!=SQLITE_OK ){
35341     assert( !pPager->dbModified );
35342     /* Ignore any IO error that occurs within pager_end_transaction(). The
35343     ** purpose of this call is to reset the internal state of the pager
35344     ** sub-system. It doesn't matter if the journal-file is not properly
35345     ** finalized at this point (since it is not a valid journal file anyway).
35346     */
35347     pager_end_transaction(pPager, 0);
35348   }
35349   return rc;
35350 }
35351
35352 /*
35353 ** Mark a single data page as writeable. The page is written into the 
35354 ** main journal or sub-journal as required. If the page is written into
35355 ** one of the journals, the corresponding bit is set in the 
35356 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
35357 ** of any open savepoints as appropriate.
35358 */
35359 static int pager_write(PgHdr *pPg){
35360   void *pData = pPg->pData;
35361   Pager *pPager = pPg->pPager;
35362   int rc = SQLITE_OK;
35363
35364   /* This routine is not called unless a transaction has already been
35365   ** started.
35366   */
35367   assert( pPager->state>=PAGER_RESERVED );
35368
35369   /* If an error has been previously detected, we should not be
35370   ** calling this routine.  Repeat the error for robustness.
35371   */
35372   if( NEVER(pPager->errCode) )  return pPager->errCode;
35373
35374   /* Higher-level routines never call this function if database is not
35375   ** writable.  But check anyway, just for robustness. */
35376   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
35377
35378   assert( !pPager->setMaster );
35379
35380   CHECK_PAGE(pPg);
35381
35382   /* Mark the page as dirty.  If the page has already been written
35383   ** to the journal then we can return right away.
35384   */
35385   sqlite3PcacheMakeDirty(pPg);
35386   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
35387     pPager->dbModified = 1;
35388   }else{
35389
35390     /* If we get this far, it means that the page needs to be
35391     ** written to the transaction journal or the ckeckpoint journal
35392     ** or both.
35393     **
35394     ** Higher level routines should have already started a transaction,
35395     ** which means they have acquired the necessary locks and opened
35396     ** a rollback journal.  Double-check to makes sure this is the case.
35397     */
35398     rc = sqlite3PagerBegin(pPager, 0, pPager->subjInMemory);
35399     if( NEVER(rc!=SQLITE_OK) ){
35400       return rc;
35401     }
35402     if( !isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
35403       assert( pPager->useJournal );
35404       rc = pager_open_journal(pPager);
35405       if( rc!=SQLITE_OK ) return rc;
35406     }
35407     pPager->dbModified = 1;
35408   
35409     /* The transaction journal now exists and we have a RESERVED or an
35410     ** EXCLUSIVE lock on the main database file.  Write the current page to
35411     ** the transaction journal if it is not there already.
35412     */
35413     if( !pageInJournal(pPg) && isOpen(pPager->jfd) ){
35414       if( pPg->pgno<=pPager->dbOrigSize ){
35415         u32 cksum;
35416         char *pData2;
35417
35418         /* We should never write to the journal file the page that
35419         ** contains the database locks.  The following assert verifies
35420         ** that we do not. */
35421         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
35422         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
35423         cksum = pager_cksum(pPager, (u8*)pData2);
35424         rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
35425         if( rc==SQLITE_OK ){
35426           rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
35427                               pPager->journalOff + 4);
35428           pPager->journalOff += pPager->pageSize+4;
35429         }
35430         if( rc==SQLITE_OK ){
35431           rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
35432           pPager->journalOff += 4;
35433         }
35434         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
35435                  pPager->journalOff, pPager->pageSize));
35436         PAGER_INCR(sqlite3_pager_writej_count);
35437         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
35438              PAGERID(pPager), pPg->pgno, 
35439              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
35440
35441         /* Even if an IO or diskfull error occurred while journalling the
35442         ** page in the block above, set the need-sync flag for the page.
35443         ** Otherwise, when the transaction is rolled back, the logic in
35444         ** playback_one_page() will think that the page needs to be restored
35445         ** in the database file. And if an IO error occurs while doing so,
35446         ** then corruption may follow.
35447         */
35448         if( !pPager->noSync ){
35449           pPg->flags |= PGHDR_NEED_SYNC;
35450           pPager->needSync = 1;
35451         }
35452
35453         /* An error has occurred writing to the journal file. The 
35454         ** transaction will be rolled back by the layer above.
35455         */
35456         if( rc!=SQLITE_OK ){
35457           return rc;
35458         }
35459
35460         pPager->nRec++;
35461         assert( pPager->pInJournal!=0 );
35462         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
35463         testcase( rc==SQLITE_NOMEM );
35464         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
35465         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
35466         if( rc!=SQLITE_OK ){
35467           assert( rc==SQLITE_NOMEM );
35468           return rc;
35469         }
35470       }else{
35471         if( !pPager->journalStarted && !pPager->noSync ){
35472           pPg->flags |= PGHDR_NEED_SYNC;
35473           pPager->needSync = 1;
35474         }
35475         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
35476                 PAGERID(pPager), pPg->pgno,
35477                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
35478       }
35479     }
35480   
35481     /* If the statement journal is open and the page is not in it,
35482     ** then write the current page to the statement journal.  Note that
35483     ** the statement journal format differs from the standard journal format
35484     ** in that it omits the checksums and the header.
35485     */
35486     if( subjRequiresPage(pPg) ){
35487       rc = subjournalPage(pPg);
35488     }
35489   }
35490
35491   /* Update the database size and return.
35492   */
35493   assert( pPager->state>=PAGER_SHARED );
35494   if( pPager->dbSize<pPg->pgno ){
35495     pPager->dbSize = pPg->pgno;
35496   }
35497   return rc;
35498 }
35499
35500 /*
35501 ** Mark a data page as writeable. This routine must be called before 
35502 ** making changes to a page. The caller must check the return value 
35503 ** of this function and be careful not to change any page data unless 
35504 ** this routine returns SQLITE_OK.
35505 **
35506 ** The difference between this function and pager_write() is that this
35507 ** function also deals with the special case where 2 or more pages
35508 ** fit on a single disk sector. In this case all co-resident pages
35509 ** must have been written to the journal file before returning.
35510 **
35511 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
35512 ** as appropriate. Otherwise, SQLITE_OK.
35513 */
35514 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
35515   int rc = SQLITE_OK;
35516
35517   PgHdr *pPg = pDbPage;
35518   Pager *pPager = pPg->pPager;
35519   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
35520
35521   if( nPagePerSector>1 ){
35522     Pgno nPageCount;          /* Total number of pages in database file */
35523     Pgno pg1;                 /* First page of the sector pPg is located on. */
35524     int nPage;                /* Number of pages starting at pg1 to journal */
35525     int ii;                   /* Loop counter */
35526     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
35527
35528     /* Set the doNotSync flag to 1. This is because we cannot allow a journal
35529     ** header to be written between the pages journaled by this function.
35530     */
35531     assert( !MEMDB );
35532     assert( pPager->doNotSync==0 );
35533     pPager->doNotSync = 1;
35534
35535     /* This trick assumes that both the page-size and sector-size are
35536     ** an integer power of 2. It sets variable pg1 to the identifier
35537     ** of the first page of the sector pPg is located on.
35538     */
35539     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
35540
35541     sqlite3PagerPagecount(pPager, (int *)&nPageCount);
35542     if( pPg->pgno>nPageCount ){
35543       nPage = (pPg->pgno - pg1)+1;
35544     }else if( (pg1+nPagePerSector-1)>nPageCount ){
35545       nPage = nPageCount+1-pg1;
35546     }else{
35547       nPage = nPagePerSector;
35548     }
35549     assert(nPage>0);
35550     assert(pg1<=pPg->pgno);
35551     assert((pg1+nPage)>pPg->pgno);
35552
35553     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
35554       Pgno pg = pg1+ii;
35555       PgHdr *pPage;
35556       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
35557         if( pg!=PAGER_MJ_PGNO(pPager) ){
35558           rc = sqlite3PagerGet(pPager, pg, &pPage);
35559           if( rc==SQLITE_OK ){
35560             rc = pager_write(pPage);
35561             if( pPage->flags&PGHDR_NEED_SYNC ){
35562               needSync = 1;
35563               assert(pPager->needSync);
35564             }
35565             sqlite3PagerUnref(pPage);
35566           }
35567         }
35568       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
35569         if( pPage->flags&PGHDR_NEED_SYNC ){
35570           needSync = 1;
35571         }
35572         sqlite3PagerUnref(pPage);
35573       }
35574     }
35575
35576     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
35577     ** starting at pg1, then it needs to be set for all of them. Because
35578     ** writing to any of these nPage pages may damage the others, the
35579     ** journal file must contain sync()ed copies of all of them
35580     ** before any of them can be written out to the database file.
35581     */
35582     if( rc==SQLITE_OK && needSync ){
35583       assert( !MEMDB && pPager->noSync==0 );
35584       for(ii=0; ii<nPage; ii++){
35585         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
35586         if( pPage ){
35587           pPage->flags |= PGHDR_NEED_SYNC;
35588           sqlite3PagerUnref(pPage);
35589         }
35590       }
35591       assert(pPager->needSync);
35592     }
35593
35594     assert( pPager->doNotSync==1 );
35595     pPager->doNotSync = 0;
35596   }else{
35597     rc = pager_write(pDbPage);
35598   }
35599   return rc;
35600 }
35601
35602 /*
35603 ** Return TRUE if the page given in the argument was previously passed
35604 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
35605 ** to change the content of the page.
35606 */
35607 #ifndef NDEBUG
35608 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
35609   return pPg->flags&PGHDR_DIRTY;
35610 }
35611 #endif
35612
35613 #ifndef SQLITE_SECURE_DELETE
35614 /*
35615 ** A call to this routine tells the pager that it is not necessary to
35616 ** write the information on page pPg back to the disk, even though
35617 ** that page might be marked as dirty.  This happens, for example, when
35618 ** the page has been added as a leaf of the freelist and so its
35619 ** content no longer matters.
35620 **
35621 ** The overlying software layer calls this routine when all of the data
35622 ** on the given page is unused. The pager marks the page as clean so
35623 ** that it does not get written to disk.
35624 **
35625 ** Tests show that this optimization can quadruple the speed of large 
35626 ** DELETE operations.
35627 */
35628 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
35629   Pager *pPager = pPg->pPager;
35630   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
35631     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
35632     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
35633     pPg->flags |= PGHDR_DONT_WRITE;
35634 #ifdef SQLITE_CHECK_PAGES
35635     pPg->pageHash = pager_pagehash(pPg);
35636 #endif
35637   }
35638 }
35639 #endif /* !defined(SQLITE_SECURE_DELETE) */
35640
35641 /*
35642 ** This routine is called to increment the value of the database file 
35643 ** change-counter, stored as a 4-byte big-endian integer starting at 
35644 ** byte offset 24 of the pager file.
35645 **
35646 ** If the isDirectMode flag is zero, then this is done by calling 
35647 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
35648 ** page data. In this case the file will be updated when the current
35649 ** transaction is committed.
35650 **
35651 ** The isDirectMode flag may only be non-zero if the library was compiled
35652 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
35653 ** if isDirect is non-zero, then the database file is updated directly
35654 ** by writing an updated version of page 1 using a call to the 
35655 ** sqlite3OsWrite() function.
35656 */
35657 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
35658   int rc = SQLITE_OK;
35659
35660   /* Declare and initialize constant integer 'isDirect'. If the
35661   ** atomic-write optimization is enabled in this build, then isDirect
35662   ** is initialized to the value passed as the isDirectMode parameter
35663   ** to this function. Otherwise, it is always set to zero.
35664   **
35665   ** The idea is that if the atomic-write optimization is not
35666   ** enabled at compile time, the compiler can omit the tests of
35667   ** 'isDirect' below, as well as the block enclosed in the
35668   ** "if( isDirect )" condition.
35669   */
35670 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
35671 # define DIRECT_MODE 0
35672   assert( isDirectMode==0 );
35673   UNUSED_PARAMETER(isDirectMode);
35674 #else
35675 # define DIRECT_MODE isDirectMode
35676 #endif
35677
35678   assert( pPager->state>=PAGER_RESERVED );
35679   if( !pPager->changeCountDone && pPager->dbSize>0 ){
35680     PgHdr *pPgHdr;                /* Reference to page 1 */
35681     u32 change_counter;           /* Initial value of change-counter field */
35682
35683     assert( !pPager->tempFile && isOpen(pPager->fd) );
35684
35685     /* Open page 1 of the file for writing. */
35686     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
35687     assert( pPgHdr==0 || rc==SQLITE_OK );
35688
35689     /* If page one was fetched successfully, and this function is not
35690     ** operating in direct-mode, make page 1 writable.  When not in 
35691     ** direct mode, page 1 is always held in cache and hence the PagerGet()
35692     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
35693     */
35694     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
35695       rc = sqlite3PagerWrite(pPgHdr);
35696     }
35697
35698     if( rc==SQLITE_OK ){
35699       /* Increment the value just read and write it back to byte 24. */
35700       change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
35701       change_counter++;
35702       put32bits(((char*)pPgHdr->pData)+24, change_counter);
35703
35704       /* If running in direct mode, write the contents of page 1 to the file. */
35705       if( DIRECT_MODE ){
35706         const void *zBuf = pPgHdr->pData;
35707         assert( pPager->dbFileSize>0 );
35708         rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
35709         if( rc==SQLITE_OK ){
35710           pPager->changeCountDone = 1;
35711         }
35712       }else{
35713         pPager->changeCountDone = 1;
35714       }
35715     }
35716
35717     /* Release the page reference. */
35718     sqlite3PagerUnref(pPgHdr);
35719   }
35720   return rc;
35721 }
35722
35723 /*
35724 ** Sync the pager file to disk. This is a no-op for in-memory files
35725 ** or pages with the Pager.noSync flag set.
35726 **
35727 ** If successful, or called on a pager for which it is a no-op, this
35728 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
35729 */
35730 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
35731   int rc;                              /* Return code */
35732   assert( !MEMDB );
35733   if( pPager->noSync ){
35734     rc = SQLITE_OK;
35735   }else{
35736     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
35737   }
35738   return rc;
35739 }
35740
35741 /*
35742 ** Sync the database file for the pager pPager. zMaster points to the name
35743 ** of a master journal file that should be written into the individual
35744 ** journal file. zMaster may be NULL, which is interpreted as no master
35745 ** journal (a single database transaction).
35746 **
35747 ** This routine ensures that:
35748 **
35749 **   * The database file change-counter is updated,
35750 **   * the journal is synced (unless the atomic-write optimization is used),
35751 **   * all dirty pages are written to the database file, 
35752 **   * the database file is truncated (if required), and
35753 **   * the database file synced. 
35754 **
35755 ** The only thing that remains to commit the transaction is to finalize 
35756 ** (delete, truncate or zero the first part of) the journal file (or 
35757 ** delete the master journal file if specified).
35758 **
35759 ** Note that if zMaster==NULL, this does not overwrite a previous value
35760 ** passed to an sqlite3PagerCommitPhaseOne() call.
35761 **
35762 ** If the final parameter - noSync - is true, then the database file itself
35763 ** is not synced. The caller must call sqlite3PagerSync() directly to
35764 ** sync the database file before calling CommitPhaseTwo() to delete the
35765 ** journal file in this case.
35766 */
35767 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
35768   Pager *pPager,                  /* Pager object */
35769   const char *zMaster,            /* If not NULL, the master journal name */
35770   int noSync                      /* True to omit the xSync on the db file */
35771 ){
35772   int rc = SQLITE_OK;             /* Return code */
35773
35774   /* The dbOrigSize is never set if journal_mode=OFF */
35775   assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF || pPager->dbOrigSize==0 );
35776
35777   /* If a prior error occurred, this routine should not be called.  ROLLBACK
35778   ** is the appropriate response to an error, not COMMIT.  Guard against
35779   ** coding errors by repeating the prior error. */
35780   if( NEVER(pPager->errCode) ) return pPager->errCode;
35781
35782   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
35783       pPager->zFilename, zMaster, pPager->dbSize));
35784
35785   if( MEMDB && pPager->dbModified ){
35786     /* If this is an in-memory db, or no pages have been written to, or this
35787     ** function has already been called, it is mostly a no-op.  However, any
35788     ** backup in progress needs to be restarted.
35789     */
35790     sqlite3BackupRestart(pPager->pBackup);
35791   }else if( pPager->state!=PAGER_SYNCED && pPager->dbModified ){
35792
35793     /* The following block updates the change-counter. Exactly how it
35794     ** does this depends on whether or not the atomic-update optimization
35795     ** was enabled at compile time, and if this transaction meets the 
35796     ** runtime criteria to use the operation: 
35797     **
35798     **    * The file-system supports the atomic-write property for
35799     **      blocks of size page-size, and 
35800     **    * This commit is not part of a multi-file transaction, and
35801     **    * Exactly one page has been modified and store in the journal file.
35802     **
35803     ** If the optimization was not enabled at compile time, then the
35804     ** pager_incr_changecounter() function is called to update the change
35805     ** counter in 'indirect-mode'. If the optimization is compiled in but
35806     ** is not applicable to this transaction, call sqlite3JournalCreate()
35807     ** to make sure the journal file has actually been created, then call
35808     ** pager_incr_changecounter() to update the change-counter in indirect
35809     ** mode. 
35810     **
35811     ** Otherwise, if the optimization is both enabled and applicable,
35812     ** then call pager_incr_changecounter() to update the change-counter
35813     ** in 'direct' mode. In this case the journal file will never be
35814     ** created for this transaction.
35815     */
35816 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
35817     PgHdr *pPg;
35818     assert( isOpen(pPager->jfd) || pPager->journalMode==PAGER_JOURNALMODE_OFF );
35819     if( !zMaster && isOpen(pPager->jfd) 
35820      && pPager->journalOff==jrnlBufferSize(pPager) 
35821      && pPager->dbSize>=pPager->dbFileSize
35822      && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
35823     ){
35824       /* Update the db file change counter via the direct-write method. The 
35825       ** following call will modify the in-memory representation of page 1 
35826       ** to include the updated change counter and then write page 1 
35827       ** directly to the database file. Because of the atomic-write 
35828       ** property of the host file-system, this is safe.
35829       */
35830       rc = pager_incr_changecounter(pPager, 1);
35831     }else{
35832       rc = sqlite3JournalCreate(pPager->jfd);
35833       if( rc==SQLITE_OK ){
35834         rc = pager_incr_changecounter(pPager, 0);
35835       }
35836     }
35837 #else
35838     rc = pager_incr_changecounter(pPager, 0);
35839 #endif
35840     if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35841
35842     /* If this transaction has made the database smaller, then all pages
35843     ** being discarded by the truncation must be written to the journal
35844     ** file. This can only happen in auto-vacuum mode.
35845     **
35846     ** Before reading the pages with page numbers larger than the 
35847     ** current value of Pager.dbSize, set dbSize back to the value
35848     ** that it took at the start of the transaction. Otherwise, the
35849     ** calls to sqlite3PagerGet() return zeroed pages instead of 
35850     ** reading data from the database file.
35851     **
35852     ** When journal_mode==OFF the dbOrigSize is always zero, so this
35853     ** block never runs if journal_mode=OFF.
35854     */
35855 #ifndef SQLITE_OMIT_AUTOVACUUM
35856     if( pPager->dbSize<pPager->dbOrigSize 
35857      && ALWAYS(pPager->journalMode!=PAGER_JOURNALMODE_OFF)
35858     ){
35859       Pgno i;                                   /* Iterator variable */
35860       const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
35861       const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
35862       pPager->dbSize = pPager->dbOrigSize;
35863       for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
35864         if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
35865           PgHdr *pPage;             /* Page to journal */
35866           rc = sqlite3PagerGet(pPager, i, &pPage);
35867           if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35868           rc = sqlite3PagerWrite(pPage);
35869           sqlite3PagerUnref(pPage);
35870           if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35871         }
35872       } 
35873       pPager->dbSize = dbSize;
35874     }
35875 #endif
35876
35877     /* Write the master journal name into the journal file. If a master 
35878     ** journal file name has already been written to the journal file, 
35879     ** or if zMaster is NULL (no master journal), then this call is a no-op.
35880     */
35881     rc = writeMasterJournal(pPager, zMaster);
35882     if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35883
35884     /* Sync the journal file. If the atomic-update optimization is being
35885     ** used, this call will not create the journal file or perform any
35886     ** real IO.
35887     */
35888     rc = syncJournal(pPager);
35889     if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35890
35891     /* Write all dirty pages to the database file. */
35892     rc = pager_write_pagelist(sqlite3PcacheDirtyList(pPager->pPCache));
35893     if( rc!=SQLITE_OK ){
35894       assert( rc!=SQLITE_IOERR_BLOCKED );
35895       goto commit_phase_one_exit;
35896     }
35897     sqlite3PcacheCleanAll(pPager->pPCache);
35898
35899     /* If the file on disk is not the same size as the database image,
35900     ** then use pager_truncate to grow or shrink the file here.
35901     */
35902     if( pPager->dbSize!=pPager->dbFileSize ){
35903       Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
35904       assert( pPager->state>=PAGER_EXCLUSIVE );
35905       rc = pager_truncate(pPager, nNew);
35906       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35907     }
35908
35909     /* Finally, sync the database file. */
35910     if( !pPager->noSync && !noSync ){
35911       rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
35912     }
35913     IOTRACE(("DBSYNC %p\n", pPager))
35914
35915     pPager->state = PAGER_SYNCED;
35916   }
35917
35918 commit_phase_one_exit:
35919   return rc;
35920 }
35921
35922
35923 /*
35924 ** When this function is called, the database file has been completely
35925 ** updated to reflect the changes made by the current transaction and
35926 ** synced to disk. The journal file still exists in the file-system 
35927 ** though, and if a failure occurs at this point it will eventually
35928 ** be used as a hot-journal and the current transaction rolled back.
35929 **
35930 ** This function finalizes the journal file, either by deleting, 
35931 ** truncating or partially zeroing it, so that it cannot be used 
35932 ** for hot-journal rollback. Once this is done the transaction is
35933 ** irrevocably committed.
35934 **
35935 ** If an error occurs, an IO error code is returned and the pager
35936 ** moves into the error state. Otherwise, SQLITE_OK is returned.
35937 */
35938 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
35939   int rc = SQLITE_OK;                  /* Return code */
35940
35941   /* This routine should not be called if a prior error has occurred.
35942   ** But if (due to a coding error elsewhere in the system) it does get
35943   ** called, just return the same error code without doing anything. */
35944   if( NEVER(pPager->errCode) ) return pPager->errCode;
35945
35946   /* This function should not be called if the pager is not in at least
35947   ** PAGER_RESERVED state. And indeed SQLite never does this. But it is
35948   ** nice to have this defensive test here anyway.
35949   */
35950   if( NEVER(pPager->state<PAGER_RESERVED) ) return SQLITE_ERROR;
35951
35952   /* An optimization. If the database was not actually modified during
35953   ** this transaction, the pager is running in exclusive-mode and is
35954   ** using persistent journals, then this function is a no-op.
35955   **
35956   ** The start of the journal file currently contains a single journal 
35957   ** header with the nRec field set to 0. If such a journal is used as
35958   ** a hot-journal during hot-journal rollback, 0 changes will be made
35959   ** to the database file. So there is no need to zero the journal 
35960   ** header. Since the pager is in exclusive mode, there is no need
35961   ** to drop any locks either.
35962   */
35963   if( pPager->dbModified==0 && pPager->exclusiveMode 
35964    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
35965   ){
35966     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
35967     return SQLITE_OK;
35968   }
35969
35970   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
35971   assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dbModified );
35972   rc = pager_end_transaction(pPager, pPager->setMaster);
35973   return pager_error(pPager, rc);
35974 }
35975
35976 /*
35977 ** Rollback all changes. The database falls back to PAGER_SHARED mode.
35978 **
35979 ** This function performs two tasks:
35980 **
35981 **   1) It rolls back the journal file, restoring all database file and 
35982 **      in-memory cache pages to the state they were in when the transaction
35983 **      was opened, and
35984 **   2) It finalizes the journal file, so that it is not used for hot
35985 **      rollback at any point in the future.
35986 **
35987 ** subject to the following qualifications:
35988 **
35989 ** * If the journal file is not yet open when this function is called,
35990 **   then only (2) is performed. In this case there is no journal file
35991 **   to roll back.
35992 **
35993 ** * If in an error state other than SQLITE_FULL, then task (1) is 
35994 **   performed. If successful, task (2). Regardless of the outcome
35995 **   of either, the error state error code is returned to the caller
35996 **   (i.e. either SQLITE_IOERR or SQLITE_CORRUPT).
35997 **
35998 ** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether
35999 **   or not (1) is succussful, also attempt (2). If successful, return
36000 **   SQLITE_OK. Otherwise, enter the error state and return the first 
36001 **   error code encountered. 
36002 **
36003 **   In this case there is no chance that the database was written to. 
36004 **   So is safe to finalize the journal file even if the playback 
36005 **   (operation 1) failed. However the pager must enter the error state
36006 **   as the contents of the in-memory cache are now suspect.
36007 **
36008 ** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only
36009 **   attempt (2) if (1) is successful. Return SQLITE_OK if successful,
36010 **   otherwise enter the error state and return the error code from the 
36011 **   failing operation.
36012 **
36013 **   In this case the database file may have been written to. So if the
36014 **   playback operation did not succeed it would not be safe to finalize
36015 **   the journal file. It needs to be left in the file-system so that
36016 **   some other process can use it to restore the database state (by
36017 **   hot-journal rollback).
36018 */
36019 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
36020   int rc = SQLITE_OK;                  /* Return code */
36021   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
36022   if( !pPager->dbModified || !isOpen(pPager->jfd) ){
36023     rc = pager_end_transaction(pPager, pPager->setMaster);
36024   }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
36025     if( pPager->state>=PAGER_EXCLUSIVE ){
36026       pager_playback(pPager, 0);
36027     }
36028     rc = pPager->errCode;
36029   }else{
36030     if( pPager->state==PAGER_RESERVED ){
36031       int rc2;
36032       rc = pager_playback(pPager, 0);
36033       rc2 = pager_end_transaction(pPager, pPager->setMaster);
36034       if( rc==SQLITE_OK ){
36035         rc = rc2;
36036       }
36037     }else{
36038       rc = pager_playback(pPager, 0);
36039     }
36040
36041     if( !MEMDB ){
36042       pPager->dbSizeValid = 0;
36043     }
36044
36045     /* If an error occurs during a ROLLBACK, we can no longer trust the pager
36046     ** cache. So call pager_error() on the way out to make any error 
36047     ** persistent.
36048     */
36049     rc = pager_error(pPager, rc);
36050   }
36051   return rc;
36052 }
36053
36054 /*
36055 ** Return TRUE if the database file is opened read-only.  Return FALSE
36056 ** if the database is (in theory) writable.
36057 */
36058 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
36059   return pPager->readOnly;
36060 }
36061
36062 /*
36063 ** Return the number of references to the pager.
36064 */
36065 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
36066   return sqlite3PcacheRefCount(pPager->pPCache);
36067 }
36068
36069 /*
36070 ** Return the number of references to the specified page.
36071 */
36072 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
36073   return sqlite3PcachePageRefcount(pPage);
36074 }
36075
36076 #ifdef SQLITE_TEST
36077 /*
36078 ** This routine is used for testing and analysis only.
36079 */
36080 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
36081   static int a[11];
36082   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
36083   a[1] = sqlite3PcachePagecount(pPager->pPCache);
36084   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
36085   a[3] = pPager->dbSizeValid ? (int) pPager->dbSize : -1;
36086   a[4] = pPager->state;
36087   a[5] = pPager->errCode;
36088   a[6] = pPager->nHit;
36089   a[7] = pPager->nMiss;
36090   a[8] = 0;  /* Used to be pPager->nOvfl */
36091   a[9] = pPager->nRead;
36092   a[10] = pPager->nWrite;
36093   return a;
36094 }
36095 #endif
36096
36097 /*
36098 ** Return true if this is an in-memory pager.
36099 */
36100 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
36101   return MEMDB;
36102 }
36103
36104 /*
36105 ** Check that there are at least nSavepoint savepoints open. If there are
36106 ** currently less than nSavepoints open, then open one or more savepoints
36107 ** to make up the difference. If the number of savepoints is already
36108 ** equal to nSavepoint, then this function is a no-op.
36109 **
36110 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
36111 ** occurs while opening the sub-journal file, then an IO error code is
36112 ** returned. Otherwise, SQLITE_OK.
36113 */
36114 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
36115   int rc = SQLITE_OK;                       /* Return code */
36116   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
36117
36118   if( nSavepoint>nCurrent && pPager->useJournal ){
36119     int ii;                                 /* Iterator variable */
36120     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
36121
36122     /* Either there is no active journal or the sub-journal is open or 
36123     ** the journal is always stored in memory */
36124     assert( pPager->nSavepoint==0 || isOpen(pPager->sjfd) ||
36125             pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
36126
36127     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
36128     ** if the allocation fails. Otherwise, zero the new portion in case a 
36129     ** malloc failure occurs while populating it in the for(...) loop below.
36130     */
36131     aNew = (PagerSavepoint *)sqlite3Realloc(
36132         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
36133     );
36134     if( !aNew ){
36135       return SQLITE_NOMEM;
36136     }
36137     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
36138     pPager->aSavepoint = aNew;
36139     pPager->nSavepoint = nSavepoint;
36140
36141     /* Populate the PagerSavepoint structures just allocated. */
36142     for(ii=nCurrent; ii<nSavepoint; ii++){
36143       assert( pPager->dbSizeValid );
36144       aNew[ii].nOrig = pPager->dbSize;
36145       if( isOpen(pPager->jfd) && ALWAYS(pPager->journalOff>0) ){
36146         aNew[ii].iOffset = pPager->journalOff;
36147       }else{
36148         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
36149       }
36150       aNew[ii].iSubRec = pPager->nSubRec;
36151       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
36152       if( !aNew[ii].pInSavepoint ){
36153         return SQLITE_NOMEM;
36154       }
36155     }
36156
36157     /* Open the sub-journal, if it is not already opened. */
36158     rc = openSubJournal(pPager);
36159     assertTruncateConstraint(pPager);
36160   }
36161
36162   return rc;
36163 }
36164
36165 /*
36166 ** This function is called to rollback or release (commit) a savepoint.
36167 ** The savepoint to release or rollback need not be the most recently 
36168 ** created savepoint.
36169 **
36170 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
36171 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
36172 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
36173 ** that have occurred since the specified savepoint was created.
36174 **
36175 ** The savepoint to rollback or release is identified by parameter 
36176 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
36177 ** (the first created). A value of (Pager.nSavepoint-1) means operate
36178 ** on the most recently created savepoint. If iSavepoint is greater than
36179 ** (Pager.nSavepoint-1), then this function is a no-op.
36180 **
36181 ** If a negative value is passed to this function, then the current
36182 ** transaction is rolled back. This is different to calling 
36183 ** sqlite3PagerRollback() because this function does not terminate
36184 ** the transaction or unlock the database, it just restores the 
36185 ** contents of the database to its original state. 
36186 **
36187 ** In any case, all savepoints with an index greater than iSavepoint 
36188 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
36189 ** then savepoint iSavepoint is also destroyed.
36190 **
36191 ** This function may return SQLITE_NOMEM if a memory allocation fails,
36192 ** or an IO error code if an IO error occurs while rolling back a 
36193 ** savepoint. If no errors occur, SQLITE_OK is returned.
36194 */ 
36195 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
36196   int rc = SQLITE_OK;
36197
36198   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
36199   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
36200
36201   if( iSavepoint<pPager->nSavepoint ){
36202     int ii;            /* Iterator variable */
36203     int nNew;          /* Number of remaining savepoints after this op. */
36204
36205     /* Figure out how many savepoints will still be active after this
36206     ** operation. Store this value in nNew. Then free resources associated 
36207     ** with any savepoints that are destroyed by this operation.
36208     */
36209     nNew = iSavepoint + (op==SAVEPOINT_ROLLBACK);
36210     for(ii=nNew; ii<pPager->nSavepoint; ii++){
36211       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
36212     }
36213     pPager->nSavepoint = nNew;
36214
36215     /* If this is a rollback operation, playback the specified savepoint.
36216     ** If this is a temp-file, it is possible that the journal file has
36217     ** not yet been opened. In this case there have been no changes to
36218     ** the database file, so the playback operation can be skipped.
36219     */
36220     if( op==SAVEPOINT_ROLLBACK && isOpen(pPager->jfd) ){
36221       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
36222       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
36223       assert(rc!=SQLITE_DONE);
36224     }
36225   
36226     /* If this is a release of the outermost savepoint, truncate 
36227     ** the sub-journal to zero bytes in size. */
36228     if( nNew==0 && op==SAVEPOINT_RELEASE && isOpen(pPager->sjfd) ){
36229       assert( rc==SQLITE_OK );
36230       rc = sqlite3OsTruncate(pPager->sjfd, 0);
36231       pPager->nSubRec = 0;
36232     }
36233   }
36234   return rc;
36235 }
36236
36237 /*
36238 ** Return the full pathname of the database file.
36239 */
36240 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
36241   return pPager->zFilename;
36242 }
36243
36244 /*
36245 ** Return the VFS structure for the pager.
36246 */
36247 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
36248   return pPager->pVfs;
36249 }
36250
36251 /*
36252 ** Return the file handle for the database file associated
36253 ** with the pager.  This might return NULL if the file has
36254 ** not yet been opened.
36255 */
36256 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
36257   return pPager->fd;
36258 }
36259
36260 /*
36261 ** Return the full pathname of the journal file.
36262 */
36263 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
36264   return pPager->zJournal;
36265 }
36266
36267 /*
36268 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
36269 ** if fsync()s are executed normally.
36270 */
36271 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
36272   return pPager->noSync;
36273 }
36274
36275 #ifdef SQLITE_HAS_CODEC
36276 /*
36277 ** Set or retrieve the codec for this pager
36278 */
36279 static void sqlite3PagerSetCodec(
36280   Pager *pPager,
36281   void *(*xCodec)(void*,void*,Pgno,int),
36282   void (*xCodecSizeChng)(void*,int,int),
36283   void (*xCodecFree)(void*),
36284   void *pCodec
36285 ){
36286   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
36287   pPager->xCodec = pPager->memDb ? 0 : xCodec;
36288   pPager->xCodecSizeChng = xCodecSizeChng;
36289   pPager->xCodecFree = xCodecFree;
36290   pPager->pCodec = pCodec;
36291   pagerReportSize(pPager);
36292 }
36293 static void *sqlite3PagerGetCodec(Pager *pPager){
36294   return pPager->pCodec;
36295 }
36296 #endif
36297
36298 #ifndef SQLITE_OMIT_AUTOVACUUM
36299 /*
36300 ** Move the page pPg to location pgno in the file.
36301 **
36302 ** There must be no references to the page previously located at
36303 ** pgno (which we call pPgOld) though that page is allowed to be
36304 ** in cache.  If the page previously located at pgno is not already
36305 ** in the rollback journal, it is not put there by by this routine.
36306 **
36307 ** References to the page pPg remain valid. Updating any
36308 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
36309 ** allocated along with the page) is the responsibility of the caller.
36310 **
36311 ** A transaction must be active when this routine is called. It used to be
36312 ** required that a statement transaction was not active, but this restriction
36313 ** has been removed (CREATE INDEX needs to move a page when a statement
36314 ** transaction is active).
36315 **
36316 ** If the fourth argument, isCommit, is non-zero, then this page is being
36317 ** moved as part of a database reorganization just before the transaction 
36318 ** is being committed. In this case, it is guaranteed that the database page 
36319 ** pPg refers to will not be written to again within this transaction.
36320 **
36321 ** This function may return SQLITE_NOMEM or an IO error code if an error
36322 ** occurs. Otherwise, it returns SQLITE_OK.
36323 */
36324 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
36325   PgHdr *pPgOld;               /* The page being overwritten. */
36326   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
36327   int rc;                      /* Return code */
36328   Pgno origPgno;               /* The original page number */
36329
36330   assert( pPg->nRef>0 );
36331
36332   /* In order to be able to rollback, an in-memory database must journal
36333   ** the page we are moving from.
36334   */
36335   if( MEMDB ){
36336     rc = sqlite3PagerWrite(pPg);
36337     if( rc ) return rc;
36338   }
36339
36340   /* If the page being moved is dirty and has not been saved by the latest
36341   ** savepoint, then save the current contents of the page into the 
36342   ** sub-journal now. This is required to handle the following scenario:
36343   **
36344   **   BEGIN;
36345   **     <journal page X, then modify it in memory>
36346   **     SAVEPOINT one;
36347   **       <Move page X to location Y>
36348   **     ROLLBACK TO one;
36349   **
36350   ** If page X were not written to the sub-journal here, it would not
36351   ** be possible to restore its contents when the "ROLLBACK TO one"
36352   ** statement were is processed.
36353   **
36354   ** subjournalPage() may need to allocate space to store pPg->pgno into
36355   ** one or more savepoint bitvecs. This is the reason this function
36356   ** may return SQLITE_NOMEM.
36357   */
36358   if( pPg->flags&PGHDR_DIRTY
36359    && subjRequiresPage(pPg)
36360    && SQLITE_OK!=(rc = subjournalPage(pPg))
36361   ){
36362     return rc;
36363   }
36364
36365   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
36366       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
36367   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
36368
36369   /* If the journal needs to be sync()ed before page pPg->pgno can
36370   ** be written to, store pPg->pgno in local variable needSyncPgno.
36371   **
36372   ** If the isCommit flag is set, there is no need to remember that
36373   ** the journal needs to be sync()ed before database page pPg->pgno 
36374   ** can be written to. The caller has already promised not to write to it.
36375   */
36376   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
36377     needSyncPgno = pPg->pgno;
36378     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
36379     assert( pPg->flags&PGHDR_DIRTY );
36380     assert( pPager->needSync );
36381   }
36382
36383   /* If the cache contains a page with page-number pgno, remove it
36384   ** from its hash chain. Also, if the PgHdr.needSync was set for 
36385   ** page pgno before the 'move' operation, it needs to be retained 
36386   ** for the page moved there.
36387   */
36388   pPg->flags &= ~PGHDR_NEED_SYNC;
36389   pPgOld = pager_lookup(pPager, pgno);
36390   assert( !pPgOld || pPgOld->nRef==1 );
36391   if( pPgOld ){
36392     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
36393     if( MEMDB ){
36394       /* Do not discard pages from an in-memory database since we might
36395       ** need to rollback later.  Just move the page out of the way. */
36396       assert( pPager->dbSizeValid );
36397       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
36398     }else{
36399       sqlite3PcacheDrop(pPgOld);
36400     }
36401   }
36402
36403   origPgno = pPg->pgno;
36404   sqlite3PcacheMove(pPg, pgno);
36405   sqlite3PcacheMakeDirty(pPg);
36406   pPager->dbModified = 1;
36407
36408   if( needSyncPgno ){
36409     /* If needSyncPgno is non-zero, then the journal file needs to be 
36410     ** sync()ed before any data is written to database file page needSyncPgno.
36411     ** Currently, no such page exists in the page-cache and the 
36412     ** "is journaled" bitvec flag has been set. This needs to be remedied by
36413     ** loading the page into the pager-cache and setting the PgHdr.needSync 
36414     ** flag.
36415     **
36416     ** If the attempt to load the page into the page-cache fails, (due
36417     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
36418     ** array. Otherwise, if the page is loaded and written again in
36419     ** this transaction, it may be written to the database file before
36420     ** it is synced into the journal file. This way, it may end up in
36421     ** the journal file twice, but that is not a problem.
36422     **
36423     ** The sqlite3PagerGet() call may cause the journal to sync. So make
36424     ** sure the Pager.needSync flag is set too.
36425     */
36426     PgHdr *pPgHdr;
36427     assert( pPager->needSync );
36428     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
36429     if( rc!=SQLITE_OK ){
36430       if( needSyncPgno<=pPager->dbOrigSize ){
36431         assert( pPager->pTmpSpace!=0 );
36432         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
36433       }
36434       return rc;
36435     }
36436     pPager->needSync = 1;
36437     assert( pPager->noSync==0 && !MEMDB );
36438     pPgHdr->flags |= PGHDR_NEED_SYNC;
36439     sqlite3PcacheMakeDirty(pPgHdr);
36440     sqlite3PagerUnref(pPgHdr);
36441   }
36442
36443   /*
36444   ** For an in-memory database, make sure the original page continues
36445   ** to exist, in case the transaction needs to roll back.  Use pPgOld
36446   ** as the original page since it has already been allocated.
36447   */
36448   if( MEMDB ){
36449     sqlite3PcacheMove(pPgOld, origPgno);
36450     sqlite3PagerUnref(pPgOld);
36451   }
36452
36453   return SQLITE_OK;
36454 }
36455 #endif
36456
36457 /*
36458 ** Return a pointer to the data for the specified page.
36459 */
36460 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
36461   assert( pPg->nRef>0 || pPg->pPager->memDb );
36462   return pPg->pData;
36463 }
36464
36465 /*
36466 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
36467 ** allocated along with the specified page.
36468 */
36469 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
36470   return pPg->pExtra;
36471 }
36472
36473 /*
36474 ** Get/set the locking-mode for this pager. Parameter eMode must be one
36475 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
36476 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
36477 ** the locking-mode is set to the value specified.
36478 **
36479 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
36480 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
36481 ** locking-mode.
36482 */
36483 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
36484   assert( eMode==PAGER_LOCKINGMODE_QUERY
36485             || eMode==PAGER_LOCKINGMODE_NORMAL
36486             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
36487   assert( PAGER_LOCKINGMODE_QUERY<0 );
36488   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
36489   if( eMode>=0 && !pPager->tempFile ){
36490     pPager->exclusiveMode = (u8)eMode;
36491   }
36492   return (int)pPager->exclusiveMode;
36493 }
36494
36495 /*
36496 ** Get/set the journal-mode for this pager. Parameter eMode must be one of:
36497 **
36498 **    PAGER_JOURNALMODE_QUERY
36499 **    PAGER_JOURNALMODE_DELETE
36500 **    PAGER_JOURNALMODE_TRUNCATE
36501 **    PAGER_JOURNALMODE_PERSIST
36502 **    PAGER_JOURNALMODE_OFF
36503 **    PAGER_JOURNALMODE_MEMORY
36504 **
36505 ** If the parameter is not _QUERY, then the journal_mode is set to the
36506 ** value specified if the change is allowed.  The change is disallowed
36507 ** for the following reasons:
36508 **
36509 **   *  An in-memory database can only have its journal_mode set to _OFF
36510 **      or _MEMORY.
36511 **
36512 **   *  The journal mode may not be changed while a transaction is active.
36513 **
36514 ** The returned indicate the current (possibly updated) journal-mode.
36515 */
36516 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
36517   assert( eMode==PAGER_JOURNALMODE_QUERY
36518             || eMode==PAGER_JOURNALMODE_DELETE
36519             || eMode==PAGER_JOURNALMODE_TRUNCATE
36520             || eMode==PAGER_JOURNALMODE_PERSIST
36521             || eMode==PAGER_JOURNALMODE_OFF 
36522             || eMode==PAGER_JOURNALMODE_MEMORY );
36523   assert( PAGER_JOURNALMODE_QUERY<0 );
36524   if( eMode>=0
36525    && (!MEMDB || eMode==PAGER_JOURNALMODE_MEMORY 
36526               || eMode==PAGER_JOURNALMODE_OFF)
36527    && !pPager->dbModified
36528    && (!isOpen(pPager->jfd) || 0==pPager->journalOff)
36529   ){
36530     if( isOpen(pPager->jfd) ){
36531       sqlite3OsClose(pPager->jfd);
36532     }
36533     pPager->journalMode = (u8)eMode;
36534   }
36535   return (int)pPager->journalMode;
36536 }
36537
36538 /*
36539 ** Get/set the size-limit used for persistent journal files.
36540 **
36541 ** Setting the size limit to -1 means no limit is enforced.
36542 ** An attempt to set a limit smaller than -1 is a no-op.
36543 */
36544 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
36545   if( iLimit>=-1 ){
36546     pPager->journalSizeLimit = iLimit;
36547   }
36548   return pPager->journalSizeLimit;
36549 }
36550
36551 /*
36552 ** Return a pointer to the pPager->pBackup variable. The backup module
36553 ** in backup.c maintains the content of this variable. This module
36554 ** uses it opaquely as an argument to sqlite3BackupRestart() and
36555 ** sqlite3BackupUpdate() only.
36556 */
36557 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
36558   return &pPager->pBackup;
36559 }
36560
36561 #endif /* SQLITE_OMIT_DISKIO */
36562
36563 /************** End of pager.c ***********************************************/
36564 /************** Begin file btmutex.c *****************************************/
36565 /*
36566 ** 2007 August 27
36567 **
36568 ** The author disclaims copyright to this source code.  In place of
36569 ** a legal notice, here is a blessing:
36570 **
36571 **    May you do good and not evil.
36572 **    May you find forgiveness for yourself and forgive others.
36573 **    May you share freely, never taking more than you give.
36574 **
36575 *************************************************************************
36576 **
36577 ** This file contains code used to implement mutexes on Btree objects.
36578 ** This code really belongs in btree.c.  But btree.c is getting too
36579 ** big and we want to break it down some.  This packaged seemed like
36580 ** a good breakout.
36581 */
36582 /************** Include btreeInt.h in the middle of btmutex.c ****************/
36583 /************** Begin file btreeInt.h ****************************************/
36584 /*
36585 ** 2004 April 6
36586 **
36587 ** The author disclaims copyright to this source code.  In place of
36588 ** a legal notice, here is a blessing:
36589 **
36590 **    May you do good and not evil.
36591 **    May you find forgiveness for yourself and forgive others.
36592 **    May you share freely, never taking more than you give.
36593 **
36594 *************************************************************************
36595 ** This file implements a external (disk-based) database using BTrees.
36596 ** For a detailed discussion of BTrees, refer to
36597 **
36598 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
36599 **     "Sorting And Searching", pages 473-480. Addison-Wesley
36600 **     Publishing Company, Reading, Massachusetts.
36601 **
36602 ** The basic idea is that each page of the file contains N database
36603 ** entries and N+1 pointers to subpages.
36604 **
36605 **   ----------------------------------------------------------------
36606 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
36607 **   ----------------------------------------------------------------
36608 **
36609 ** All of the keys on the page that Ptr(0) points to have values less
36610 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
36611 ** values greater than Key(0) and less than Key(1).  All of the keys
36612 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
36613 ** so forth.
36614 **
36615 ** Finding a particular key requires reading O(log(M)) pages from the 
36616 ** disk where M is the number of entries in the tree.
36617 **
36618 ** In this implementation, a single file can hold one or more separate 
36619 ** BTrees.  Each BTree is identified by the index of its root page.  The
36620 ** key and data for any entry are combined to form the "payload".  A
36621 ** fixed amount of payload can be carried directly on the database
36622 ** page.  If the payload is larger than the preset amount then surplus
36623 ** bytes are stored on overflow pages.  The payload for an entry
36624 ** and the preceding pointer are combined to form a "Cell".  Each 
36625 ** page has a small header which contains the Ptr(N) pointer and other
36626 ** information such as the size of key and data.
36627 **
36628 ** FORMAT DETAILS
36629 **
36630 ** The file is divided into pages.  The first page is called page 1,
36631 ** the second is page 2, and so forth.  A page number of zero indicates
36632 ** "no such page".  The page size can be any power of 2 between 512 and 32768.
36633 ** Each page can be either a btree page, a freelist page, an overflow
36634 ** page, or a pointer-map page.
36635 **
36636 ** The first page is always a btree page.  The first 100 bytes of the first
36637 ** page contain a special header (the "file header") that describes the file.
36638 ** The format of the file header is as follows:
36639 **
36640 **   OFFSET   SIZE    DESCRIPTION
36641 **      0      16     Header string: "SQLite format 3\000"
36642 **     16       2     Page size in bytes.  
36643 **     18       1     File format write version
36644 **     19       1     File format read version
36645 **     20       1     Bytes of unused space at the end of each page
36646 **     21       1     Max embedded payload fraction
36647 **     22       1     Min embedded payload fraction
36648 **     23       1     Min leaf payload fraction
36649 **     24       4     File change counter
36650 **     28       4     Reserved for future use
36651 **     32       4     First freelist page
36652 **     36       4     Number of freelist pages in the file
36653 **     40      60     15 4-byte meta values passed to higher layers
36654 **
36655 **     40       4     Schema cookie
36656 **     44       4     File format of schema layer
36657 **     48       4     Size of page cache
36658 **     52       4     Largest root-page (auto/incr_vacuum)
36659 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
36660 **     60       4     User version
36661 **     64       4     Incremental vacuum mode
36662 **     68       4     unused
36663 **     72       4     unused
36664 **     76       4     unused
36665 **
36666 ** All of the integer values are big-endian (most significant byte first).
36667 **
36668 ** The file change counter is incremented when the database is changed
36669 ** This counter allows other processes to know when the file has changed
36670 ** and thus when they need to flush their cache.
36671 **
36672 ** The max embedded payload fraction is the amount of the total usable
36673 ** space in a page that can be consumed by a single cell for standard
36674 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
36675 ** is to limit the maximum cell size so that at least 4 cells will fit
36676 ** on one page.  Thus the default max embedded payload fraction is 64.
36677 **
36678 ** If the payload for a cell is larger than the max payload, then extra
36679 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
36680 ** as many bytes as possible are moved into the overflow pages without letting
36681 ** the cell size drop below the min embedded payload fraction.
36682 **
36683 ** The min leaf payload fraction is like the min embedded payload fraction
36684 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
36685 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
36686 ** not specified in the header.
36687 **
36688 ** Each btree pages is divided into three sections:  The header, the
36689 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
36690 ** file header that occurs before the page header.
36691 **
36692 **      |----------------|
36693 **      | file header    |   100 bytes.  Page 1 only.
36694 **      |----------------|
36695 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
36696 **      |----------------|
36697 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
36698 **      | array          |   |  Grows downward
36699 **      |                |   v
36700 **      |----------------|
36701 **      | unallocated    |
36702 **      | space          |
36703 **      |----------------|   ^  Grows upwards
36704 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
36705 **      | area           |   |  and free space fragments.
36706 **      |----------------|
36707 **
36708 ** The page headers looks like this:
36709 **
36710 **   OFFSET   SIZE     DESCRIPTION
36711 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
36712 **      1       2      byte offset to the first freeblock
36713 **      3       2      number of cells on this page
36714 **      5       2      first byte of the cell content area
36715 **      7       1      number of fragmented free bytes
36716 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
36717 **
36718 ** The flags define the format of this btree page.  The leaf flag means that
36719 ** this page has no children.  The zerodata flag means that this page carries
36720 ** only keys and no data.  The intkey flag means that the key is a integer
36721 ** which is stored in the key size entry of the cell header rather than in
36722 ** the payload area.
36723 **
36724 ** The cell pointer array begins on the first byte after the page header.
36725 ** The cell pointer array contains zero or more 2-byte numbers which are
36726 ** offsets from the beginning of the page to the cell content in the cell
36727 ** content area.  The cell pointers occur in sorted order.  The system strives
36728 ** to keep free space after the last cell pointer so that new cells can
36729 ** be easily added without having to defragment the page.
36730 **
36731 ** Cell content is stored at the very end of the page and grows toward the
36732 ** beginning of the page.
36733 **
36734 ** Unused space within the cell content area is collected into a linked list of
36735 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
36736 ** to the first freeblock is given in the header.  Freeblocks occur in
36737 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
36738 ** any group of 3 or fewer unused bytes in the cell content area cannot
36739 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
36740 ** a fragment.  The total number of bytes in all fragments is recorded.
36741 ** in the page header at offset 7.
36742 **
36743 **    SIZE    DESCRIPTION
36744 **      2     Byte offset of the next freeblock
36745 **      2     Bytes in this freeblock
36746 **
36747 ** Cells are of variable length.  Cells are stored in the cell content area at
36748 ** the end of the page.  Pointers to the cells are in the cell pointer array
36749 ** that immediately follows the page header.  Cells is not necessarily
36750 ** contiguous or in order, but cell pointers are contiguous and in order.
36751 **
36752 ** Cell content makes use of variable length integers.  A variable
36753 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
36754 ** byte are used.  The integer consists of all bytes that have bit 8 set and
36755 ** the first byte with bit 8 clear.  The most significant byte of the integer
36756 ** appears first.  A variable-length integer may not be more than 9 bytes long.
36757 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
36758 ** allows a 64-bit integer to be encoded in 9 bytes.
36759 **
36760 **    0x00                      becomes  0x00000000
36761 **    0x7f                      becomes  0x0000007f
36762 **    0x81 0x00                 becomes  0x00000080
36763 **    0x82 0x00                 becomes  0x00000100
36764 **    0x80 0x7f                 becomes  0x0000007f
36765 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
36766 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
36767 **
36768 ** Variable length integers are used for rowids and to hold the number of
36769 ** bytes of key and data in a btree cell.
36770 **
36771 ** The content of a cell looks like this:
36772 **
36773 **    SIZE    DESCRIPTION
36774 **      4     Page number of the left child. Omitted if leaf flag is set.
36775 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
36776 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
36777 **      *     Payload
36778 **      4     First page of the overflow chain.  Omitted if no overflow
36779 **
36780 ** Overflow pages form a linked list.  Each page except the last is completely
36781 ** filled with data (pagesize - 4 bytes).  The last page can have as little
36782 ** as 1 byte of data.
36783 **
36784 **    SIZE    DESCRIPTION
36785 **      4     Page number of next overflow page
36786 **      *     Data
36787 **
36788 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
36789 ** file header points to the first in a linked list of trunk page.  Each trunk
36790 ** page points to multiple leaf pages.  The content of a leaf page is
36791 ** unspecified.  A trunk page looks like this:
36792 **
36793 **    SIZE    DESCRIPTION
36794 **      4     Page number of next trunk page
36795 **      4     Number of leaf pointers on this page
36796 **      *     zero or more pages numbers of leaves
36797 */
36798
36799
36800 /* The following value is the maximum cell size assuming a maximum page
36801 ** size give above.
36802 */
36803 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
36804
36805 /* The maximum number of cells on a single page of the database.  This
36806 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
36807 ** plus 2 bytes for the index to the cell in the page header).  Such
36808 ** small cells will be rare, but they are possible.
36809 */
36810 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
36811
36812 /* Forward declarations */
36813 typedef struct MemPage MemPage;
36814 typedef struct BtLock BtLock;
36815
36816 /*
36817 ** This is a magic string that appears at the beginning of every
36818 ** SQLite database in order to identify the file as a real database.
36819 **
36820 ** You can change this value at compile-time by specifying a
36821 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
36822 ** header must be exactly 16 bytes including the zero-terminator so
36823 ** the string itself should be 15 characters long.  If you change
36824 ** the header, then your custom library will not be able to read 
36825 ** databases generated by the standard tools and the standard tools
36826 ** will not be able to read databases created by your custom library.
36827 */
36828 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
36829 #  define SQLITE_FILE_HEADER "SQLite format 3"
36830 #endif
36831
36832 /*
36833 ** Page type flags.  An ORed combination of these flags appear as the
36834 ** first byte of on-disk image of every BTree page.
36835 */
36836 #define PTF_INTKEY    0x01
36837 #define PTF_ZERODATA  0x02
36838 #define PTF_LEAFDATA  0x04
36839 #define PTF_LEAF      0x08
36840
36841 /*
36842 ** As each page of the file is loaded into memory, an instance of the following
36843 ** structure is appended and initialized to zero.  This structure stores
36844 ** information about the page that is decoded from the raw file page.
36845 **
36846 ** The pParent field points back to the parent page.  This allows us to
36847 ** walk up the BTree from any leaf to the root.  Care must be taken to
36848 ** unref() the parent page pointer when this page is no longer referenced.
36849 ** The pageDestructor() routine handles that chore.
36850 **
36851 ** Access to all fields of this structure is controlled by the mutex
36852 ** stored in MemPage.pBt->mutex.
36853 */
36854 struct MemPage {
36855   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
36856   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
36857   u8 intKey;           /* True if intkey flag is set */
36858   u8 leaf;             /* True if leaf flag is set */
36859   u8 hasData;          /* True if this page stores data */
36860   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
36861   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
36862   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
36863   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
36864   u16 cellOffset;      /* Index in aData of first cell pointer */
36865   u16 nFree;           /* Number of free bytes on the page */
36866   u16 nCell;           /* Number of cells on this page, local and ovfl */
36867   u16 maskPage;        /* Mask for page offset */
36868   struct _OvflCell {   /* Cells that will not fit on aData[] */
36869     u8 *pCell;          /* Pointers to the body of the overflow cell */
36870     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
36871   } aOvfl[5];
36872   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
36873   u8 *aData;           /* Pointer to disk image of the page data */
36874   DbPage *pDbPage;     /* Pager page handle */
36875   Pgno pgno;           /* Page number for this page */
36876 };
36877
36878 /*
36879 ** The in-memory image of a disk page has the auxiliary information appended
36880 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
36881 ** that extra information.
36882 */
36883 #define EXTRA_SIZE sizeof(MemPage)
36884
36885 /*
36886 ** A linked list of the following structures is stored at BtShared.pLock.
36887 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
36888 ** is opened on the table with root page BtShared.iTable. Locks are removed
36889 ** from this list when a transaction is committed or rolled back, or when
36890 ** a btree handle is closed.
36891 */
36892 struct BtLock {
36893   Btree *pBtree;        /* Btree handle holding this lock */
36894   Pgno iTable;          /* Root page of table */
36895   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
36896   BtLock *pNext;        /* Next in BtShared.pLock list */
36897 };
36898
36899 /* Candidate values for BtLock.eLock */
36900 #define READ_LOCK     1
36901 #define WRITE_LOCK    2
36902
36903 /* A Btree handle
36904 **
36905 ** A database connection contains a pointer to an instance of
36906 ** this object for every database file that it has open.  This structure
36907 ** is opaque to the database connection.  The database connection cannot
36908 ** see the internals of this structure and only deals with pointers to
36909 ** this structure.
36910 **
36911 ** For some database files, the same underlying database cache might be 
36912 ** shared between multiple connections.  In that case, each connection
36913 ** has it own instance of this object.  But each instance of this object
36914 ** points to the same BtShared object.  The database cache and the
36915 ** schema associated with the database file are all contained within
36916 ** the BtShared object.
36917 **
36918 ** All fields in this structure are accessed under sqlite3.mutex.
36919 ** The pBt pointer itself may not be changed while there exists cursors 
36920 ** in the referenced BtShared that point back to this Btree since those
36921 ** cursors have to do go through this Btree to find their BtShared and
36922 ** they often do so without holding sqlite3.mutex.
36923 */
36924 struct Btree {
36925   sqlite3 *db;       /* The database connection holding this btree */
36926   BtShared *pBt;     /* Sharable content of this btree */
36927   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
36928   u8 sharable;       /* True if we can share pBt with another db */
36929   u8 locked;         /* True if db currently has pBt locked */
36930   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
36931   int nBackup;       /* Number of backup operations reading this btree */
36932   Btree *pNext;      /* List of other sharable Btrees from the same db */
36933   Btree *pPrev;      /* Back pointer of the same list */
36934 #ifndef SQLITE_OMIT_SHARED_CACHE
36935   BtLock lock;       /* Object used to lock page 1 */
36936 #endif
36937 };
36938
36939 /*
36940 ** Btree.inTrans may take one of the following values.
36941 **
36942 ** If the shared-data extension is enabled, there may be multiple users
36943 ** of the Btree structure. At most one of these may open a write transaction,
36944 ** but any number may have active read transactions.
36945 */
36946 #define TRANS_NONE  0
36947 #define TRANS_READ  1
36948 #define TRANS_WRITE 2
36949
36950 /*
36951 ** An instance of this object represents a single database file.
36952 ** 
36953 ** A single database file can be in use as the same time by two
36954 ** or more database connections.  When two or more connections are
36955 ** sharing the same database file, each connection has it own
36956 ** private Btree object for the file and each of those Btrees points
36957 ** to this one BtShared object.  BtShared.nRef is the number of
36958 ** connections currently sharing this database file.
36959 **
36960 ** Fields in this structure are accessed under the BtShared.mutex
36961 ** mutex, except for nRef and pNext which are accessed under the
36962 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
36963 ** may not be modified once it is initially set as long as nRef>0.
36964 ** The pSchema field may be set once under BtShared.mutex and
36965 ** thereafter is unchanged as long as nRef>0.
36966 **
36967 ** isPending:
36968 **
36969 **   If a BtShared client fails to obtain a write-lock on a database
36970 **   table (because there exists one or more read-locks on the table),
36971 **   the shared-cache enters 'pending-lock' state and isPending is
36972 **   set to true.
36973 **
36974 **   The shared-cache leaves the 'pending lock' state when either of
36975 **   the following occur:
36976 **
36977 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
36978 **     2) The number of locks held by other connections drops to zero.
36979 **
36980 **   while in the 'pending-lock' state, no connection may start a new
36981 **   transaction.
36982 **
36983 **   This feature is included to help prevent writer-starvation.
36984 */
36985 struct BtShared {
36986   Pager *pPager;        /* The page cache */
36987   sqlite3 *db;          /* Database connection currently using this Btree */
36988   BtCursor *pCursor;    /* A list of all open cursors */
36989   MemPage *pPage1;      /* First page of the database */
36990   u8 readOnly;          /* True if the underlying file is readonly */
36991   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
36992 #ifndef SQLITE_OMIT_AUTOVACUUM
36993   u8 autoVacuum;        /* True if auto-vacuum is enabled */
36994   u8 incrVacuum;        /* True if incr-vacuum is enabled */
36995 #endif
36996   u16 pageSize;         /* Total number of bytes on a page */
36997   u16 usableSize;       /* Number of usable bytes on each page */
36998   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
36999   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
37000   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
37001   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
37002   u8 inTransaction;     /* Transaction state */
37003   int nTransaction;     /* Number of open transactions (read + write) */
37004   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
37005   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
37006   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
37007   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
37008 #ifndef SQLITE_OMIT_SHARED_CACHE
37009   int nRef;             /* Number of references to this structure */
37010   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
37011   BtLock *pLock;        /* List of locks held on this shared-btree struct */
37012   Btree *pWriter;       /* Btree with currently open write transaction */
37013   u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
37014   u8 isPending;         /* If waiting for read-locks to clear */
37015 #endif
37016   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
37017 };
37018
37019 /*
37020 ** An instance of the following structure is used to hold information
37021 ** about a cell.  The parseCellPtr() function fills in this structure
37022 ** based on information extract from the raw disk page.
37023 */
37024 typedef struct CellInfo CellInfo;
37025 struct CellInfo {
37026   u8 *pCell;     /* Pointer to the start of cell content */
37027   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
37028   u32 nData;     /* Number of bytes of data */
37029   u32 nPayload;  /* Total amount of payload */
37030   u16 nHeader;   /* Size of the cell content header in bytes */
37031   u16 nLocal;    /* Amount of payload held locally */
37032   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
37033   u16 nSize;     /* Size of the cell content on the main b-tree page */
37034 };
37035
37036 /*
37037 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
37038 ** this will be declared corrupt. This value is calculated based on a
37039 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
37040 ** root-node and 3 for all other internal nodes.
37041 **
37042 ** If a tree that appears to be taller than this is encountered, it is
37043 ** assumed that the database is corrupt.
37044 */
37045 #define BTCURSOR_MAX_DEPTH 20
37046
37047 /*
37048 ** A cursor is a pointer to a particular entry within a particular
37049 ** b-tree within a database file.
37050 **
37051 ** The entry is identified by its MemPage and the index in
37052 ** MemPage.aCell[] of the entry.
37053 **
37054 ** A single database file can shared by two more database connections,
37055 ** but cursors cannot be shared.  Each cursor is associated with a
37056 ** particular database connection identified BtCursor.pBtree.db.
37057 **
37058 ** Fields in this structure are accessed under the BtShared.mutex
37059 ** found at self->pBt->mutex. 
37060 */
37061 struct BtCursor {
37062   Btree *pBtree;            /* The Btree to which this cursor belongs */
37063   BtShared *pBt;            /* The BtShared this cursor points to */
37064   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
37065   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
37066   Pgno pgnoRoot;            /* The root page of this tree */
37067   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
37068   CellInfo info;            /* A parse of the cell we are pointing at */
37069   u8 wrFlag;                /* True if writable */
37070   u8 atLast;                /* Cursor pointing to the last entry */
37071   u8 validNKey;             /* True if info.nKey is valid */
37072   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
37073   void *pKey;      /* Saved key that was cursor's last known position */
37074   i64 nKey;        /* Size of pKey, or last integer key */
37075   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
37076 #ifndef SQLITE_OMIT_INCRBLOB
37077   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
37078   Pgno *aOverflow;          /* Cache of overflow page locations */
37079 #endif
37080   i16 iPage;                            /* Index of current page in apPage */
37081   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
37082   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
37083 };
37084
37085 /*
37086 ** Potential values for BtCursor.eState.
37087 **
37088 ** CURSOR_VALID:
37089 **   Cursor points to a valid entry. getPayload() etc. may be called.
37090 **
37091 ** CURSOR_INVALID:
37092 **   Cursor does not point to a valid entry. This can happen (for example) 
37093 **   because the table is empty or because BtreeCursorFirst() has not been
37094 **   called.
37095 **
37096 ** CURSOR_REQUIRESEEK:
37097 **   The table that this cursor was opened on still exists, but has been 
37098 **   modified since the cursor was last used. The cursor position is saved
37099 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
37100 **   this state, restoreCursorPosition() can be called to attempt to
37101 **   seek the cursor to the saved position.
37102 **
37103 ** CURSOR_FAULT:
37104 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
37105 **   on a different connection that shares the BtShared cache with this
37106 **   cursor.  The error has left the cache in an inconsistent state.
37107 **   Do nothing else with this cursor.  Any attempt to use the cursor
37108 **   should return the error code stored in BtCursor.skip
37109 */
37110 #define CURSOR_INVALID           0
37111 #define CURSOR_VALID             1
37112 #define CURSOR_REQUIRESEEK       2
37113 #define CURSOR_FAULT             3
37114
37115 /* 
37116 ** The database page the PENDING_BYTE occupies. This page is never used.
37117 */
37118 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
37119
37120 /*
37121 ** These macros define the location of the pointer-map entry for a 
37122 ** database page. The first argument to each is the number of usable
37123 ** bytes on each page of the database (often 1024). The second is the
37124 ** page number to look up in the pointer map.
37125 **
37126 ** PTRMAP_PAGENO returns the database page number of the pointer-map
37127 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
37128 ** the offset of the requested map entry.
37129 **
37130 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
37131 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
37132 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
37133 ** this test.
37134 */
37135 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
37136 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
37137 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
37138
37139 /*
37140 ** The pointer map is a lookup table that identifies the parent page for
37141 ** each child page in the database file.  The parent page is the page that
37142 ** contains a pointer to the child.  Every page in the database contains
37143 ** 0 or 1 parent pages.  (In this context 'database page' refers
37144 ** to any page that is not part of the pointer map itself.)  Each pointer map
37145 ** entry consists of a single byte 'type' and a 4 byte parent page number.
37146 ** The PTRMAP_XXX identifiers below are the valid types.
37147 **
37148 ** The purpose of the pointer map is to facility moving pages from one
37149 ** position in the file to another as part of autovacuum.  When a page
37150 ** is moved, the pointer in its parent must be updated to point to the
37151 ** new location.  The pointer map is used to locate the parent page quickly.
37152 **
37153 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
37154 **                  used in this case.
37155 **
37156 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
37157 **                  is not used in this case.
37158 **
37159 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
37160 **                   overflow pages. The page number identifies the page that
37161 **                   contains the cell with a pointer to this overflow page.
37162 **
37163 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
37164 **                   overflow pages. The page-number identifies the previous
37165 **                   page in the overflow page list.
37166 **
37167 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
37168 **               identifies the parent page in the btree.
37169 */
37170 #define PTRMAP_ROOTPAGE 1
37171 #define PTRMAP_FREEPAGE 2
37172 #define PTRMAP_OVERFLOW1 3
37173 #define PTRMAP_OVERFLOW2 4
37174 #define PTRMAP_BTREE 5
37175
37176 /* A bunch of assert() statements to check the transaction state variables
37177 ** of handle p (type Btree*) are internally consistent.
37178 */
37179 #define btreeIntegrity(p) \
37180   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
37181   assert( p->pBt->inTransaction>=p->inTrans ); 
37182
37183
37184 /*
37185 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
37186 ** if the database supports auto-vacuum or not. Because it is used
37187 ** within an expression that is an argument to another macro 
37188 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
37189 ** So, this macro is defined instead.
37190 */
37191 #ifndef SQLITE_OMIT_AUTOVACUUM
37192 #define ISAUTOVACUUM (pBt->autoVacuum)
37193 #else
37194 #define ISAUTOVACUUM 0
37195 #endif
37196
37197
37198 /*
37199 ** This structure is passed around through all the sanity checking routines
37200 ** in order to keep track of some global state information.
37201 */
37202 typedef struct IntegrityCk IntegrityCk;
37203 struct IntegrityCk {
37204   BtShared *pBt;    /* The tree being checked out */
37205   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
37206   Pgno nPage;       /* Number of pages in the database */
37207   int *anRef;       /* Number of times each page is referenced */
37208   int mxErr;        /* Stop accumulating errors when this reaches zero */
37209   int nErr;         /* Number of messages written to zErrMsg so far */
37210   int mallocFailed; /* A memory allocation error has occurred */
37211   StrAccum errMsg;  /* Accumulate the error message text here */
37212 };
37213
37214 /*
37215 ** Read or write a two- and four-byte big-endian integer values.
37216 */
37217 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
37218 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
37219 #define get4byte sqlite3Get4byte
37220 #define put4byte sqlite3Put4byte
37221
37222 /************** End of btreeInt.h ********************************************/
37223 /************** Continuing where we left off in btmutex.c ********************/
37224 #ifndef SQLITE_OMIT_SHARED_CACHE
37225 #if SQLITE_THREADSAFE
37226
37227 /*
37228 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
37229 ** set BtShared.db to the database handle associated with p and the
37230 ** p->locked boolean to true.
37231 */
37232 static void lockBtreeMutex(Btree *p){
37233   assert( p->locked==0 );
37234   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
37235   assert( sqlite3_mutex_held(p->db->mutex) );
37236
37237   sqlite3_mutex_enter(p->pBt->mutex);
37238   p->pBt->db = p->db;
37239   p->locked = 1;
37240 }
37241
37242 /*
37243 ** Release the BtShared mutex associated with B-Tree handle p and
37244 ** clear the p->locked boolean.
37245 */
37246 static void unlockBtreeMutex(Btree *p){
37247   assert( p->locked==1 );
37248   assert( sqlite3_mutex_held(p->pBt->mutex) );
37249   assert( sqlite3_mutex_held(p->db->mutex) );
37250   assert( p->db==p->pBt->db );
37251
37252   sqlite3_mutex_leave(p->pBt->mutex);
37253   p->locked = 0;
37254 }
37255
37256 /*
37257 ** Enter a mutex on the given BTree object.
37258 **
37259 ** If the object is not sharable, then no mutex is ever required
37260 ** and this routine is a no-op.  The underlying mutex is non-recursive.
37261 ** But we keep a reference count in Btree.wantToLock so the behavior
37262 ** of this interface is recursive.
37263 **
37264 ** To avoid deadlocks, multiple Btrees are locked in the same order
37265 ** by all database connections.  The p->pNext is a list of other
37266 ** Btrees belonging to the same database connection as the p Btree
37267 ** which need to be locked after p.  If we cannot get a lock on
37268 ** p, then first unlock all of the others on p->pNext, then wait
37269 ** for the lock to become available on p, then relock all of the
37270 ** subsequent Btrees that desire a lock.
37271 */
37272 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
37273   Btree *pLater;
37274
37275   /* Some basic sanity checking on the Btree.  The list of Btrees
37276   ** connected by pNext and pPrev should be in sorted order by
37277   ** Btree.pBt value. All elements of the list should belong to
37278   ** the same connection. Only shared Btrees are on the list. */
37279   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
37280   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
37281   assert( p->pNext==0 || p->pNext->db==p->db );
37282   assert( p->pPrev==0 || p->pPrev->db==p->db );
37283   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
37284
37285   /* Check for locking consistency */
37286   assert( !p->locked || p->wantToLock>0 );
37287   assert( p->sharable || p->wantToLock==0 );
37288
37289   /* We should already hold a lock on the database connection */
37290   assert( sqlite3_mutex_held(p->db->mutex) );
37291
37292   /* Unless the database is sharable and unlocked, then BtShared.db
37293   ** should already be set correctly. */
37294   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
37295
37296   if( !p->sharable ) return;
37297   p->wantToLock++;
37298   if( p->locked ) return;
37299
37300   /* In most cases, we should be able to acquire the lock we
37301   ** want without having to go throught the ascending lock
37302   ** procedure that follows.  Just be sure not to block.
37303   */
37304   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
37305     p->pBt->db = p->db;
37306     p->locked = 1;
37307     return;
37308   }
37309
37310   /* To avoid deadlock, first release all locks with a larger
37311   ** BtShared address.  Then acquire our lock.  Then reacquire
37312   ** the other BtShared locks that we used to hold in ascending
37313   ** order.
37314   */
37315   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
37316     assert( pLater->sharable );
37317     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
37318     assert( !pLater->locked || pLater->wantToLock>0 );
37319     if( pLater->locked ){
37320       unlockBtreeMutex(pLater);
37321     }
37322   }
37323   lockBtreeMutex(p);
37324   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
37325     if( pLater->wantToLock ){
37326       lockBtreeMutex(pLater);
37327     }
37328   }
37329 }
37330
37331 /*
37332 ** Exit the recursive mutex on a Btree.
37333 */
37334 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
37335   if( p->sharable ){
37336     assert( p->wantToLock>0 );
37337     p->wantToLock--;
37338     if( p->wantToLock==0 ){
37339       unlockBtreeMutex(p);
37340     }
37341   }
37342 }
37343
37344 #ifndef NDEBUG
37345 /*
37346 ** Return true if the BtShared mutex is held on the btree, or if the
37347 ** B-Tree is not marked as sharable.
37348 **
37349 ** This routine is used only from within assert() statements.
37350 */
37351 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
37352   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
37353   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
37354   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
37355   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
37356
37357   return (p->sharable==0 || p->locked);
37358 }
37359 #endif
37360
37361
37362 #ifndef SQLITE_OMIT_INCRBLOB
37363 /*
37364 ** Enter and leave a mutex on a Btree given a cursor owned by that
37365 ** Btree.  These entry points are used by incremental I/O and can be
37366 ** omitted if that module is not used.
37367 */
37368 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
37369   sqlite3BtreeEnter(pCur->pBtree);
37370 }
37371 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
37372   sqlite3BtreeLeave(pCur->pBtree);
37373 }
37374 #endif /* SQLITE_OMIT_INCRBLOB */
37375
37376
37377 /*
37378 ** Enter the mutex on every Btree associated with a database
37379 ** connection.  This is needed (for example) prior to parsing
37380 ** a statement since we will be comparing table and column names
37381 ** against all schemas and we do not want those schemas being
37382 ** reset out from under us.
37383 **
37384 ** There is a corresponding leave-all procedures.
37385 **
37386 ** Enter the mutexes in accending order by BtShared pointer address
37387 ** to avoid the possibility of deadlock when two threads with
37388 ** two or more btrees in common both try to lock all their btrees
37389 ** at the same instant.
37390 */
37391 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
37392   int i;
37393   Btree *p, *pLater;
37394   assert( sqlite3_mutex_held(db->mutex) );
37395   for(i=0; i<db->nDb; i++){
37396     p = db->aDb[i].pBt;
37397     assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
37398     if( p && p->sharable ){
37399       p->wantToLock++;
37400       if( !p->locked ){
37401         assert( p->wantToLock==1 );
37402         while( p->pPrev ) p = p->pPrev;
37403         /* Reason for ALWAYS:  There must be at least on unlocked Btree in
37404         ** the chain.  Otherwise the !p->locked test above would have failed */
37405         while( p->locked && ALWAYS(p->pNext) ) p = p->pNext;
37406         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
37407           if( pLater->locked ){
37408             unlockBtreeMutex(pLater);
37409           }
37410         }
37411         while( p ){
37412           lockBtreeMutex(p);
37413           p = p->pNext;
37414         }
37415       }
37416     }
37417   }
37418 }
37419 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
37420   int i;
37421   Btree *p;
37422   assert( sqlite3_mutex_held(db->mutex) );
37423   for(i=0; i<db->nDb; i++){
37424     p = db->aDb[i].pBt;
37425     if( p && p->sharable ){
37426       assert( p->wantToLock>0 );
37427       p->wantToLock--;
37428       if( p->wantToLock==0 ){
37429         unlockBtreeMutex(p);
37430       }
37431     }
37432   }
37433 }
37434
37435 #ifndef NDEBUG
37436 /*
37437 ** Return true if the current thread holds the database connection
37438 ** mutex and all required BtShared mutexes.
37439 **
37440 ** This routine is used inside assert() statements only.
37441 */
37442 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
37443   int i;
37444   if( !sqlite3_mutex_held(db->mutex) ){
37445     return 0;
37446   }
37447   for(i=0; i<db->nDb; i++){
37448     Btree *p;
37449     p = db->aDb[i].pBt;
37450     if( p && p->sharable &&
37451          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
37452       return 0;
37453     }
37454   }
37455   return 1;
37456 }
37457 #endif /* NDEBUG */
37458
37459 /*
37460 ** Add a new Btree pointer to a BtreeMutexArray. 
37461 ** if the pointer can possibly be shared with
37462 ** another database connection.
37463 **
37464 ** The pointers are kept in sorted order by pBtree->pBt.  That
37465 ** way when we go to enter all the mutexes, we can enter them
37466 ** in order without every having to backup and retry and without
37467 ** worrying about deadlock.
37468 **
37469 ** The number of shared btrees will always be small (usually 0 or 1)
37470 ** so an insertion sort is an adequate algorithm here.
37471 */
37472 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
37473   int i, j;
37474   BtShared *pBt;
37475   if( pBtree==0 || pBtree->sharable==0 ) return;
37476 #ifndef NDEBUG
37477   {
37478     for(i=0; i<pArray->nMutex; i++){
37479       assert( pArray->aBtree[i]!=pBtree );
37480     }
37481   }
37482 #endif
37483   assert( pArray->nMutex>=0 );
37484   assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
37485   pBt = pBtree->pBt;
37486   for(i=0; i<pArray->nMutex; i++){
37487     assert( pArray->aBtree[i]!=pBtree );
37488     if( pArray->aBtree[i]->pBt>pBt ){
37489       for(j=pArray->nMutex; j>i; j--){
37490         pArray->aBtree[j] = pArray->aBtree[j-1];
37491       }
37492       pArray->aBtree[i] = pBtree;
37493       pArray->nMutex++;
37494       return;
37495     }
37496   }
37497   pArray->aBtree[pArray->nMutex++] = pBtree;
37498 }
37499
37500 /*
37501 ** Enter the mutex of every btree in the array.  This routine is
37502 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
37503 ** exited at the end of the same function.
37504 */
37505 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
37506   int i;
37507   for(i=0; i<pArray->nMutex; i++){
37508     Btree *p = pArray->aBtree[i];
37509     /* Some basic sanity checking */
37510     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
37511     assert( !p->locked || p->wantToLock>0 );
37512
37513     /* We should already hold a lock on the database connection */
37514     assert( sqlite3_mutex_held(p->db->mutex) );
37515
37516     /* The Btree is sharable because only sharable Btrees are entered
37517     ** into the array in the first place. */
37518     assert( p->sharable );
37519
37520     p->wantToLock++;
37521     if( !p->locked ){
37522       lockBtreeMutex(p);
37523     }
37524   }
37525 }
37526
37527 /*
37528 ** Leave the mutex of every btree in the group.
37529 */
37530 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
37531   int i;
37532   for(i=0; i<pArray->nMutex; i++){
37533     Btree *p = pArray->aBtree[i];
37534     /* Some basic sanity checking */
37535     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
37536     assert( p->locked );
37537     assert( p->wantToLock>0 );
37538
37539     /* We should already hold a lock on the database connection */
37540     assert( sqlite3_mutex_held(p->db->mutex) );
37541
37542     p->wantToLock--;
37543     if( p->wantToLock==0 ){
37544       unlockBtreeMutex(p);
37545     }
37546   }
37547 }
37548
37549 #else
37550 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
37551   p->pBt->db = p->db;
37552 }
37553 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
37554   int i;
37555   for(i=0; i<db->nDb; i++){
37556     Btree *p = db->aDb[i].pBt;
37557     if( p ){
37558       p->pBt->db = p->db;
37559     }
37560   }
37561 }
37562 #endif /* if SQLITE_THREADSAFE */
37563 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
37564
37565 /************** End of btmutex.c *********************************************/
37566 /************** Begin file btree.c *******************************************/
37567 /*
37568 ** 2004 April 6
37569 **
37570 ** The author disclaims copyright to this source code.  In place of
37571 ** a legal notice, here is a blessing:
37572 **
37573 **    May you do good and not evil.
37574 **    May you find forgiveness for yourself and forgive others.
37575 **    May you share freely, never taking more than you give.
37576 **
37577 *************************************************************************
37578 ** This file implements a external (disk-based) database using BTrees.
37579 ** See the header comment on "btreeInt.h" for additional information.
37580 ** Including a description of file format and an overview of operation.
37581 */
37582
37583 /*
37584 ** The header string that appears at the beginning of every
37585 ** SQLite database.
37586 */
37587 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
37588
37589 /*
37590 ** Set this global variable to 1 to enable tracing using the TRACE
37591 ** macro.
37592 */
37593 #if 0
37594 int sqlite3BtreeTrace=1;  /* True to enable tracing */
37595 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
37596 #else
37597 # define TRACE(X)
37598 #endif
37599
37600
37601
37602 #ifndef SQLITE_OMIT_SHARED_CACHE
37603 /*
37604 ** A list of BtShared objects that are eligible for participation
37605 ** in shared cache.  This variable has file scope during normal builds,
37606 ** but the test harness needs to access it so we make it global for 
37607 ** test builds.
37608 **
37609 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
37610 */
37611 #ifdef SQLITE_TEST
37612 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
37613 #else
37614 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
37615 #endif
37616 #endif /* SQLITE_OMIT_SHARED_CACHE */
37617
37618 #ifndef SQLITE_OMIT_SHARED_CACHE
37619 /*
37620 ** Enable or disable the shared pager and schema features.
37621 **
37622 ** This routine has no effect on existing database connections.
37623 ** The shared cache setting effects only future calls to
37624 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
37625 */
37626 SQLITE_API int sqlite3_enable_shared_cache(int enable){
37627   sqlite3GlobalConfig.sharedCacheEnabled = enable;
37628   return SQLITE_OK;
37629 }
37630 #endif
37631
37632
37633
37634 #ifdef SQLITE_OMIT_SHARED_CACHE
37635   /*
37636   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
37637   ** and clearAllSharedCacheTableLocks()
37638   ** manipulate entries in the BtShared.pLock linked list used to store
37639   ** shared-cache table level locks. If the library is compiled with the
37640   ** shared-cache feature disabled, then there is only ever one user
37641   ** of each BtShared structure and so this locking is not necessary. 
37642   ** So define the lock related functions as no-ops.
37643   */
37644   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
37645   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
37646   #define clearAllSharedCacheTableLocks(a)
37647   #define downgradeAllSharedCacheTableLocks(a)
37648   #define hasSharedCacheTableLock(a,b,c,d) 1
37649   #define hasReadConflicts(a, b) 0
37650 #endif
37651
37652 #ifndef SQLITE_OMIT_SHARED_CACHE
37653
37654 #ifdef SQLITE_DEBUG
37655 /*
37656 **** This function is only used as part of an assert() statement. ***
37657 **
37658 ** Check to see if pBtree holds the required locks to read or write to the 
37659 ** table with root page iRoot.   Return 1 if it does and 0 if not.
37660 **
37661 ** For example, when writing to a table with root-page iRoot via 
37662 ** Btree connection pBtree:
37663 **
37664 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
37665 **
37666 ** When writing to an index that resides in a sharable database, the 
37667 ** caller should have first obtained a lock specifying the root page of
37668 ** the corresponding table. This makes things a bit more complicated,
37669 ** as this module treats each table as a separate structure. To determine
37670 ** the table corresponding to the index being written, this
37671 ** function has to search through the database schema.
37672 **
37673 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
37674 ** hold a write-lock on the schema table (root page 1). This is also
37675 ** acceptable.
37676 */
37677 static int hasSharedCacheTableLock(
37678   Btree *pBtree,         /* Handle that must hold lock */
37679   Pgno iRoot,            /* Root page of b-tree */
37680   int isIndex,           /* True if iRoot is the root of an index b-tree */
37681   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
37682 ){
37683   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
37684   Pgno iTab = 0;
37685   BtLock *pLock;
37686
37687   /* If this database is not shareable, or if the client is reading
37688   ** and has the read-uncommitted flag set, then no lock is required. 
37689   ** Return true immediately.
37690   */
37691   if( (pBtree->sharable==0)
37692    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
37693   ){
37694     return 1;
37695   }
37696
37697   /* If the client is reading  or writing an index and the schema is
37698   ** not loaded, then it is too difficult to actually check to see if
37699   ** the correct locks are held.  So do not bother - just return true.
37700   ** This case does not come up very often anyhow.
37701   */
37702   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
37703     return 1;
37704   }
37705
37706   /* Figure out the root-page that the lock should be held on. For table
37707   ** b-trees, this is just the root page of the b-tree being read or
37708   ** written. For index b-trees, it is the root page of the associated
37709   ** table.  */
37710   if( isIndex ){
37711     HashElem *p;
37712     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
37713       Index *pIdx = (Index *)sqliteHashData(p);
37714       if( pIdx->tnum==(int)iRoot ){
37715         iTab = pIdx->pTable->tnum;
37716       }
37717     }
37718   }else{
37719     iTab = iRoot;
37720   }
37721
37722   /* Search for the required lock. Either a write-lock on root-page iTab, a 
37723   ** write-lock on the schema table, or (if the client is reading) a
37724   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
37725   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
37726     if( pLock->pBtree==pBtree 
37727      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
37728      && pLock->eLock>=eLockType 
37729     ){
37730       return 1;
37731     }
37732   }
37733
37734   /* Failed to find the required lock. */
37735   return 0;
37736 }
37737 #endif /* SQLITE_DEBUG */
37738
37739 #ifdef SQLITE_DEBUG
37740 /*
37741 **** This function may be used as part of assert() statements only. ****
37742 **
37743 ** Return true if it would be illegal for pBtree to write into the
37744 ** table or index rooted at iRoot because other shared connections are
37745 ** simultaneously reading that same table or index.
37746 **
37747 ** It is illegal for pBtree to write if some other Btree object that
37748 ** shares the same BtShared object is currently reading or writing
37749 ** the iRoot table.  Except, if the other Btree object has the
37750 ** read-uncommitted flag set, then it is OK for the other object to
37751 ** have a read cursor.
37752 **
37753 ** For example, before writing to any part of the table or index
37754 ** rooted at page iRoot, one should call:
37755 **
37756 **    assert( !hasReadConflicts(pBtree, iRoot) );
37757 */
37758 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
37759   BtCursor *p;
37760   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
37761     if( p->pgnoRoot==iRoot 
37762      && p->pBtree!=pBtree
37763      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
37764     ){
37765       return 1;
37766     }
37767   }
37768   return 0;
37769 }
37770 #endif    /* #ifdef SQLITE_DEBUG */
37771
37772 /*
37773 ** Query to see if Btree handle p may obtain a lock of type eLock 
37774 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
37775 ** SQLITE_OK if the lock may be obtained (by calling
37776 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
37777 */
37778 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
37779   BtShared *pBt = p->pBt;
37780   BtLock *pIter;
37781
37782   assert( sqlite3BtreeHoldsMutex(p) );
37783   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
37784   assert( p->db!=0 );
37785   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
37786   
37787   /* If requesting a write-lock, then the Btree must have an open write
37788   ** transaction on this file. And, obviously, for this to be so there 
37789   ** must be an open write transaction on the file itself.
37790   */
37791   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
37792   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
37793   
37794   /* This routine is a no-op if the shared-cache is not enabled */
37795   if( !p->sharable ){
37796     return SQLITE_OK;
37797   }
37798
37799   /* If some other connection is holding an exclusive lock, the
37800   ** requested lock may not be obtained.
37801   */
37802   if( pBt->pWriter!=p && pBt->isExclusive ){
37803     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
37804     return SQLITE_LOCKED_SHAREDCACHE;
37805   }
37806
37807   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
37808     /* The condition (pIter->eLock!=eLock) in the following if(...) 
37809     ** statement is a simplification of:
37810     **
37811     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
37812     **
37813     ** since we know that if eLock==WRITE_LOCK, then no other connection
37814     ** may hold a WRITE_LOCK on any table in this file (since there can
37815     ** only be a single writer).
37816     */
37817     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
37818     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
37819     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
37820       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
37821       if( eLock==WRITE_LOCK ){
37822         assert( p==pBt->pWriter );
37823         pBt->isPending = 1;
37824       }
37825       return SQLITE_LOCKED_SHAREDCACHE;
37826     }
37827   }
37828   return SQLITE_OK;
37829 }
37830 #endif /* !SQLITE_OMIT_SHARED_CACHE */
37831
37832 #ifndef SQLITE_OMIT_SHARED_CACHE
37833 /*
37834 ** Add a lock on the table with root-page iTable to the shared-btree used
37835 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
37836 ** WRITE_LOCK.
37837 **
37838 ** This function assumes the following:
37839 **
37840 **   (a) The specified Btree object p is connected to a sharable
37841 **       database (one with the BtShared.sharable flag set), and
37842 **
37843 **   (b) No other Btree objects hold a lock that conflicts
37844 **       with the requested lock (i.e. querySharedCacheTableLock() has
37845 **       already been called and returned SQLITE_OK).
37846 **
37847 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
37848 ** is returned if a malloc attempt fails.
37849 */
37850 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
37851   BtShared *pBt = p->pBt;
37852   BtLock *pLock = 0;
37853   BtLock *pIter;
37854
37855   assert( sqlite3BtreeHoldsMutex(p) );
37856   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
37857   assert( p->db!=0 );
37858
37859   /* A connection with the read-uncommitted flag set will never try to
37860   ** obtain a read-lock using this function. The only read-lock obtained
37861   ** by a connection in read-uncommitted mode is on the sqlite_master 
37862   ** table, and that lock is obtained in BtreeBeginTrans().  */
37863   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
37864
37865   /* This function should only be called on a sharable b-tree after it 
37866   ** has been determined that no other b-tree holds a conflicting lock.  */
37867   assert( p->sharable );
37868   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
37869
37870   /* First search the list for an existing lock on this table. */
37871   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
37872     if( pIter->iTable==iTable && pIter->pBtree==p ){
37873       pLock = pIter;
37874       break;
37875     }
37876   }
37877
37878   /* If the above search did not find a BtLock struct associating Btree p
37879   ** with table iTable, allocate one and link it into the list.
37880   */
37881   if( !pLock ){
37882     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
37883     if( !pLock ){
37884       return SQLITE_NOMEM;
37885     }
37886     pLock->iTable = iTable;
37887     pLock->pBtree = p;
37888     pLock->pNext = pBt->pLock;
37889     pBt->pLock = pLock;
37890   }
37891
37892   /* Set the BtLock.eLock variable to the maximum of the current lock
37893   ** and the requested lock. This means if a write-lock was already held
37894   ** and a read-lock requested, we don't incorrectly downgrade the lock.
37895   */
37896   assert( WRITE_LOCK>READ_LOCK );
37897   if( eLock>pLock->eLock ){
37898     pLock->eLock = eLock;
37899   }
37900
37901   return SQLITE_OK;
37902 }
37903 #endif /* !SQLITE_OMIT_SHARED_CACHE */
37904
37905 #ifndef SQLITE_OMIT_SHARED_CACHE
37906 /*
37907 ** Release all the table locks (locks obtained via calls to
37908 ** the setSharedCacheTableLock() procedure) held by Btree object p.
37909 **
37910 ** This function assumes that Btree p has an open read or write 
37911 ** transaction. If it does not, then the BtShared.isPending variable
37912 ** may be incorrectly cleared.
37913 */
37914 static void clearAllSharedCacheTableLocks(Btree *p){
37915   BtShared *pBt = p->pBt;
37916   BtLock **ppIter = &pBt->pLock;
37917
37918   assert( sqlite3BtreeHoldsMutex(p) );
37919   assert( p->sharable || 0==*ppIter );
37920   assert( p->inTrans>0 );
37921
37922   while( *ppIter ){
37923     BtLock *pLock = *ppIter;
37924     assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
37925     assert( pLock->pBtree->inTrans>=pLock->eLock );
37926     if( pLock->pBtree==p ){
37927       *ppIter = pLock->pNext;
37928       assert( pLock->iTable!=1 || pLock==&p->lock );
37929       if( pLock->iTable!=1 ){
37930         sqlite3_free(pLock);
37931       }
37932     }else{
37933       ppIter = &pLock->pNext;
37934     }
37935   }
37936
37937   assert( pBt->isPending==0 || pBt->pWriter );
37938   if( pBt->pWriter==p ){
37939     pBt->pWriter = 0;
37940     pBt->isExclusive = 0;
37941     pBt->isPending = 0;
37942   }else if( pBt->nTransaction==2 ){
37943     /* This function is called when Btree p is concluding its 
37944     ** transaction. If there currently exists a writer, and p is not
37945     ** that writer, then the number of locks held by connections other
37946     ** than the writer must be about to drop to zero. In this case
37947     ** set the isPending flag to 0.
37948     **
37949     ** If there is not currently a writer, then BtShared.isPending must
37950     ** be zero already. So this next line is harmless in that case.
37951     */
37952     pBt->isPending = 0;
37953   }
37954 }
37955
37956 /*
37957 ** This function changes all write-locks held by Btree p into read-locks.
37958 */
37959 static void downgradeAllSharedCacheTableLocks(Btree *p){
37960   BtShared *pBt = p->pBt;
37961   if( pBt->pWriter==p ){
37962     BtLock *pLock;
37963     pBt->pWriter = 0;
37964     pBt->isExclusive = 0;
37965     pBt->isPending = 0;
37966     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
37967       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
37968       pLock->eLock = READ_LOCK;
37969     }
37970   }
37971 }
37972
37973 #endif /* SQLITE_OMIT_SHARED_CACHE */
37974
37975 static void releasePage(MemPage *pPage);  /* Forward reference */
37976
37977 /*
37978 ***** This routine is used inside of assert() only ****
37979 **
37980 ** Verify that the cursor holds the mutex on its BtShared
37981 */
37982 #ifdef SQLITE_DEBUG
37983 static int cursorHoldsMutex(BtCursor *p){
37984   return sqlite3_mutex_held(p->pBt->mutex);
37985 }
37986 #endif
37987
37988
37989 #ifndef SQLITE_OMIT_INCRBLOB
37990 /*
37991 ** Invalidate the overflow page-list cache for cursor pCur, if any.
37992 */
37993 static void invalidateOverflowCache(BtCursor *pCur){
37994   assert( cursorHoldsMutex(pCur) );
37995   sqlite3_free(pCur->aOverflow);
37996   pCur->aOverflow = 0;
37997 }
37998
37999 /*
38000 ** Invalidate the overflow page-list cache for all cursors opened
38001 ** on the shared btree structure pBt.
38002 */
38003 static void invalidateAllOverflowCache(BtShared *pBt){
38004   BtCursor *p;
38005   assert( sqlite3_mutex_held(pBt->mutex) );
38006   for(p=pBt->pCursor; p; p=p->pNext){
38007     invalidateOverflowCache(p);
38008   }
38009 }
38010
38011 /*
38012 ** This function is called before modifying the contents of a table
38013 ** to invalidate any incrblob cursors that are open on the
38014 ** row or one of the rows being modified.
38015 **
38016 ** If argument isClearTable is true, then the entire contents of the
38017 ** table is about to be deleted. In this case invalidate all incrblob
38018 ** cursors open on any row within the table with root-page pgnoRoot.
38019 **
38020 ** Otherwise, if argument isClearTable is false, then the row with
38021 ** rowid iRow is being replaced or deleted. In this case invalidate
38022 ** only those incrblob cursors open on that specific row.
38023 */
38024 static void invalidateIncrblobCursors(
38025   Btree *pBtree,          /* The database file to check */
38026   i64 iRow,               /* The rowid that might be changing */
38027   int isClearTable        /* True if all rows are being deleted */
38028 ){
38029   BtCursor *p;
38030   BtShared *pBt = pBtree->pBt;
38031   assert( sqlite3BtreeHoldsMutex(pBtree) );
38032   for(p=pBt->pCursor; p; p=p->pNext){
38033     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
38034       p->eState = CURSOR_INVALID;
38035     }
38036   }
38037 }
38038
38039 #else
38040   /* Stub functions when INCRBLOB is omitted */
38041   #define invalidateOverflowCache(x)
38042   #define invalidateAllOverflowCache(x)
38043   #define invalidateIncrblobCursors(x,y,z)
38044 #endif /* SQLITE_OMIT_INCRBLOB */
38045
38046 /*
38047 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
38048 ** when a page that previously contained data becomes a free-list leaf 
38049 ** page.
38050 **
38051 ** The BtShared.pHasContent bitvec exists to work around an obscure
38052 ** bug caused by the interaction of two useful IO optimizations surrounding
38053 ** free-list leaf pages:
38054 **
38055 **   1) When all data is deleted from a page and the page becomes
38056 **      a free-list leaf page, the page is not written to the database
38057 **      (as free-list leaf pages contain no meaningful data). Sometimes
38058 **      such a page is not even journalled (as it will not be modified,
38059 **      why bother journalling it?).
38060 **
38061 **   2) When a free-list leaf page is reused, its content is not read
38062 **      from the database or written to the journal file (why should it
38063 **      be, if it is not at all meaningful?).
38064 **
38065 ** By themselves, these optimizations work fine and provide a handy
38066 ** performance boost to bulk delete or insert operations. However, if
38067 ** a page is moved to the free-list and then reused within the same
38068 ** transaction, a problem comes up. If the page is not journalled when
38069 ** it is moved to the free-list and it is also not journalled when it
38070 ** is extracted from the free-list and reused, then the original data
38071 ** may be lost. In the event of a rollback, it may not be possible
38072 ** to restore the database to its original configuration.
38073 **
38074 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
38075 ** moved to become a free-list leaf page, the corresponding bit is
38076 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
38077 ** optimization 2 above is omitted if the corresponding bit is already
38078 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
38079 ** at the end of every transaction.
38080 */
38081 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
38082   int rc = SQLITE_OK;
38083   if( !pBt->pHasContent ){
38084     int nPage = 100;
38085     sqlite3PagerPagecount(pBt->pPager, &nPage);
38086     /* If sqlite3PagerPagecount() fails there is no harm because the
38087     ** nPage variable is unchanged from its default value of 100 */
38088     pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
38089     if( !pBt->pHasContent ){
38090       rc = SQLITE_NOMEM;
38091     }
38092   }
38093   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
38094     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
38095   }
38096   return rc;
38097 }
38098
38099 /*
38100 ** Query the BtShared.pHasContent vector.
38101 **
38102 ** This function is called when a free-list leaf page is removed from the
38103 ** free-list for reuse. It returns false if it is safe to retrieve the
38104 ** page from the pager layer with the 'no-content' flag set. True otherwise.
38105 */
38106 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
38107   Bitvec *p = pBt->pHasContent;
38108   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
38109 }
38110
38111 /*
38112 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
38113 ** invoked at the conclusion of each write-transaction.
38114 */
38115 static void btreeClearHasContent(BtShared *pBt){
38116   sqlite3BitvecDestroy(pBt->pHasContent);
38117   pBt->pHasContent = 0;
38118 }
38119
38120 /*
38121 ** Save the current cursor position in the variables BtCursor.nKey 
38122 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
38123 **
38124 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
38125 ** prior to calling this routine.  
38126 */
38127 static int saveCursorPosition(BtCursor *pCur){
38128   int rc;
38129
38130   assert( CURSOR_VALID==pCur->eState );
38131   assert( 0==pCur->pKey );
38132   assert( cursorHoldsMutex(pCur) );
38133
38134   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
38135   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
38136
38137   /* If this is an intKey table, then the above call to BtreeKeySize()
38138   ** stores the integer key in pCur->nKey. In this case this value is
38139   ** all that is required. Otherwise, if pCur is not open on an intKey
38140   ** table, then malloc space for and store the pCur->nKey bytes of key 
38141   ** data.
38142   */
38143   if( 0==pCur->apPage[0]->intKey ){
38144     void *pKey = sqlite3Malloc( (int)pCur->nKey );
38145     if( pKey ){
38146       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
38147       if( rc==SQLITE_OK ){
38148         pCur->pKey = pKey;
38149       }else{
38150         sqlite3_free(pKey);
38151       }
38152     }else{
38153       rc = SQLITE_NOMEM;
38154     }
38155   }
38156   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
38157
38158   if( rc==SQLITE_OK ){
38159     int i;
38160     for(i=0; i<=pCur->iPage; i++){
38161       releasePage(pCur->apPage[i]);
38162       pCur->apPage[i] = 0;
38163     }
38164     pCur->iPage = -1;
38165     pCur->eState = CURSOR_REQUIRESEEK;
38166   }
38167
38168   invalidateOverflowCache(pCur);
38169   return rc;
38170 }
38171
38172 /*
38173 ** Save the positions of all cursors (except pExcept) that are open on
38174 ** the table  with root-page iRoot. Usually, this is called just before cursor
38175 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
38176 */
38177 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
38178   BtCursor *p;
38179   assert( sqlite3_mutex_held(pBt->mutex) );
38180   assert( pExcept==0 || pExcept->pBt==pBt );
38181   for(p=pBt->pCursor; p; p=p->pNext){
38182     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
38183         p->eState==CURSOR_VALID ){
38184       int rc = saveCursorPosition(p);
38185       if( SQLITE_OK!=rc ){
38186         return rc;
38187       }
38188     }
38189   }
38190   return SQLITE_OK;
38191 }
38192
38193 /*
38194 ** Clear the current cursor position.
38195 */
38196 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
38197   assert( cursorHoldsMutex(pCur) );
38198   sqlite3_free(pCur->pKey);
38199   pCur->pKey = 0;
38200   pCur->eState = CURSOR_INVALID;
38201 }
38202
38203 /*
38204 ** In this version of BtreeMoveto, pKey is a packed index record
38205 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
38206 ** record and then call BtreeMovetoUnpacked() to do the work.
38207 */
38208 static int btreeMoveto(
38209   BtCursor *pCur,     /* Cursor open on the btree to be searched */
38210   const void *pKey,   /* Packed key if the btree is an index */
38211   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
38212   int bias,           /* Bias search to the high end */
38213   int *pRes           /* Write search results here */
38214 ){
38215   int rc;                    /* Status code */
38216   UnpackedRecord *pIdxKey;   /* Unpacked index key */
38217   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
38218
38219   if( pKey ){
38220     assert( nKey==(i64)(int)nKey );
38221     pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
38222                                       aSpace, sizeof(aSpace));
38223     if( pIdxKey==0 ) return SQLITE_NOMEM;
38224   }else{
38225     pIdxKey = 0;
38226   }
38227   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
38228   if( pKey ){
38229     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
38230   }
38231   return rc;
38232 }
38233
38234 /*
38235 ** Restore the cursor to the position it was in (or as close to as possible)
38236 ** when saveCursorPosition() was called. Note that this call deletes the 
38237 ** saved position info stored by saveCursorPosition(), so there can be
38238 ** at most one effective restoreCursorPosition() call after each 
38239 ** saveCursorPosition().
38240 */
38241 static int btreeRestoreCursorPosition(BtCursor *pCur){
38242   int rc;
38243   assert( cursorHoldsMutex(pCur) );
38244   assert( pCur->eState>=CURSOR_REQUIRESEEK );
38245   if( pCur->eState==CURSOR_FAULT ){
38246     return pCur->skipNext;
38247   }
38248   pCur->eState = CURSOR_INVALID;
38249   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
38250   if( rc==SQLITE_OK ){
38251     sqlite3_free(pCur->pKey);
38252     pCur->pKey = 0;
38253     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
38254   }
38255   return rc;
38256 }
38257
38258 #define restoreCursorPosition(p) \
38259   (p->eState>=CURSOR_REQUIRESEEK ? \
38260          btreeRestoreCursorPosition(p) : \
38261          SQLITE_OK)
38262
38263 /*
38264 ** Determine whether or not a cursor has moved from the position it
38265 ** was last placed at.  Cursors can move when the row they are pointing
38266 ** at is deleted out from under them.
38267 **
38268 ** This routine returns an error code if something goes wrong.  The
38269 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
38270 */
38271 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
38272   int rc;
38273
38274   rc = restoreCursorPosition(pCur);
38275   if( rc ){
38276     *pHasMoved = 1;
38277     return rc;
38278   }
38279   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
38280     *pHasMoved = 1;
38281   }else{
38282     *pHasMoved = 0;
38283   }
38284   return SQLITE_OK;
38285 }
38286
38287 #ifndef SQLITE_OMIT_AUTOVACUUM
38288 /*
38289 ** Given a page number of a regular database page, return the page
38290 ** number for the pointer-map page that contains the entry for the
38291 ** input page number.
38292 */
38293 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
38294   int nPagesPerMapPage;
38295   Pgno iPtrMap, ret;
38296   assert( sqlite3_mutex_held(pBt->mutex) );
38297   nPagesPerMapPage = (pBt->usableSize/5)+1;
38298   iPtrMap = (pgno-2)/nPagesPerMapPage;
38299   ret = (iPtrMap*nPagesPerMapPage) + 2; 
38300   if( ret==PENDING_BYTE_PAGE(pBt) ){
38301     ret++;
38302   }
38303   return ret;
38304 }
38305
38306 /*
38307 ** Write an entry into the pointer map.
38308 **
38309 ** This routine updates the pointer map entry for page number 'key'
38310 ** so that it maps to type 'eType' and parent page number 'pgno'.
38311 **
38312 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
38313 ** a no-op.  If an error occurs, the appropriate error code is written
38314 ** into *pRC.
38315 */
38316 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
38317   DbPage *pDbPage;  /* The pointer map page */
38318   u8 *pPtrmap;      /* The pointer map data */
38319   Pgno iPtrmap;     /* The pointer map page number */
38320   int offset;       /* Offset in pointer map page */
38321   int rc;           /* Return code from subfunctions */
38322
38323   if( *pRC ) return;
38324
38325   assert( sqlite3_mutex_held(pBt->mutex) );
38326   /* The master-journal page number must never be used as a pointer map page */
38327   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
38328
38329   assert( pBt->autoVacuum );
38330   if( key==0 ){
38331     *pRC = SQLITE_CORRUPT_BKPT;
38332     return;
38333   }
38334   iPtrmap = PTRMAP_PAGENO(pBt, key);
38335   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
38336   if( rc!=SQLITE_OK ){
38337     *pRC = rc;
38338     return;
38339   }
38340   offset = PTRMAP_PTROFFSET(iPtrmap, key);
38341   if( offset<0 ){
38342     *pRC = SQLITE_CORRUPT_BKPT;
38343     goto ptrmap_exit;
38344   }
38345   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
38346
38347   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
38348     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
38349     *pRC= rc = sqlite3PagerWrite(pDbPage);
38350     if( rc==SQLITE_OK ){
38351       pPtrmap[offset] = eType;
38352       put4byte(&pPtrmap[offset+1], parent);
38353     }
38354   }
38355
38356 ptrmap_exit:
38357   sqlite3PagerUnref(pDbPage);
38358 }
38359
38360 /*
38361 ** Read an entry from the pointer map.
38362 **
38363 ** This routine retrieves the pointer map entry for page 'key', writing
38364 ** the type and parent page number to *pEType and *pPgno respectively.
38365 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
38366 */
38367 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
38368   DbPage *pDbPage;   /* The pointer map page */
38369   int iPtrmap;       /* Pointer map page index */
38370   u8 *pPtrmap;       /* Pointer map page data */
38371   int offset;        /* Offset of entry in pointer map */
38372   int rc;
38373
38374   assert( sqlite3_mutex_held(pBt->mutex) );
38375
38376   iPtrmap = PTRMAP_PAGENO(pBt, key);
38377   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
38378   if( rc!=0 ){
38379     return rc;
38380   }
38381   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
38382
38383   offset = PTRMAP_PTROFFSET(iPtrmap, key);
38384   assert( pEType!=0 );
38385   *pEType = pPtrmap[offset];
38386   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
38387
38388   sqlite3PagerUnref(pDbPage);
38389   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
38390   return SQLITE_OK;
38391 }
38392
38393 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
38394   #define ptrmapPut(w,x,y,z,rc)
38395   #define ptrmapGet(w,x,y,z) SQLITE_OK
38396   #define ptrmapPutOvflPtr(x, y, rc)
38397 #endif
38398
38399 /*
38400 ** Given a btree page and a cell index (0 means the first cell on
38401 ** the page, 1 means the second cell, and so forth) return a pointer
38402 ** to the cell content.
38403 **
38404 ** This routine works only for pages that do not contain overflow cells.
38405 */
38406 #define findCell(P,I) \
38407   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
38408
38409 /*
38410 ** This a more complex version of findCell() that works for
38411 ** pages that do contain overflow cells.
38412 */
38413 static u8 *findOverflowCell(MemPage *pPage, int iCell){
38414   int i;
38415   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38416   for(i=pPage->nOverflow-1; i>=0; i--){
38417     int k;
38418     struct _OvflCell *pOvfl;
38419     pOvfl = &pPage->aOvfl[i];
38420     k = pOvfl->idx;
38421     if( k<=iCell ){
38422       if( k==iCell ){
38423         return pOvfl->pCell;
38424       }
38425       iCell--;
38426     }
38427   }
38428   return findCell(pPage, iCell);
38429 }
38430
38431 /*
38432 ** Parse a cell content block and fill in the CellInfo structure.  There
38433 ** are two versions of this function.  btreeParseCell() takes a 
38434 ** cell index as the second argument and btreeParseCellPtr() 
38435 ** takes a pointer to the body of the cell as its second argument.
38436 **
38437 ** Within this file, the parseCell() macro can be called instead of
38438 ** btreeParseCellPtr(). Using some compilers, this will be faster.
38439 */
38440 static void btreeParseCellPtr(
38441   MemPage *pPage,         /* Page containing the cell */
38442   u8 *pCell,              /* Pointer to the cell text. */
38443   CellInfo *pInfo         /* Fill in this structure */
38444 ){
38445   u16 n;                  /* Number bytes in cell content header */
38446   u32 nPayload;           /* Number of bytes of cell payload */
38447
38448   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38449
38450   pInfo->pCell = pCell;
38451   assert( pPage->leaf==0 || pPage->leaf==1 );
38452   n = pPage->childPtrSize;
38453   assert( n==4-4*pPage->leaf );
38454   if( pPage->intKey ){
38455     if( pPage->hasData ){
38456       n += getVarint32(&pCell[n], nPayload);
38457     }else{
38458       nPayload = 0;
38459     }
38460     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
38461     pInfo->nData = nPayload;
38462   }else{
38463     pInfo->nData = 0;
38464     n += getVarint32(&pCell[n], nPayload);
38465     pInfo->nKey = nPayload;
38466   }
38467   pInfo->nPayload = nPayload;
38468   pInfo->nHeader = n;
38469   testcase( nPayload==pPage->maxLocal );
38470   testcase( nPayload==pPage->maxLocal+1 );
38471   if( likely(nPayload<=pPage->maxLocal) ){
38472     /* This is the (easy) common case where the entire payload fits
38473     ** on the local page.  No overflow is required.
38474     */
38475     int nSize;          /* Total size of cell content in bytes */
38476     nSize = nPayload + n;
38477     pInfo->nLocal = (u16)nPayload;
38478     pInfo->iOverflow = 0;
38479     if( (nSize & ~3)==0 ){
38480       nSize = 4;        /* Minimum cell size is 4 */
38481     }
38482     pInfo->nSize = (u16)nSize;
38483   }else{
38484     /* If the payload will not fit completely on the local page, we have
38485     ** to decide how much to store locally and how much to spill onto
38486     ** overflow pages.  The strategy is to minimize the amount of unused
38487     ** space on overflow pages while keeping the amount of local storage
38488     ** in between minLocal and maxLocal.
38489     **
38490     ** Warning:  changing the way overflow payload is distributed in any
38491     ** way will result in an incompatible file format.
38492     */
38493     int minLocal;  /* Minimum amount of payload held locally */
38494     int maxLocal;  /* Maximum amount of payload held locally */
38495     int surplus;   /* Overflow payload available for local storage */
38496
38497     minLocal = pPage->minLocal;
38498     maxLocal = pPage->maxLocal;
38499     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
38500     testcase( surplus==maxLocal );
38501     testcase( surplus==maxLocal+1 );
38502     if( surplus <= maxLocal ){
38503       pInfo->nLocal = (u16)surplus;
38504     }else{
38505       pInfo->nLocal = (u16)minLocal;
38506     }
38507     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
38508     pInfo->nSize = pInfo->iOverflow + 4;
38509   }
38510 }
38511 #define parseCell(pPage, iCell, pInfo) \
38512   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
38513 static void btreeParseCell(
38514   MemPage *pPage,         /* Page containing the cell */
38515   int iCell,              /* The cell index.  First cell is 0 */
38516   CellInfo *pInfo         /* Fill in this structure */
38517 ){
38518   parseCell(pPage, iCell, pInfo);
38519 }
38520
38521 /*
38522 ** Compute the total number of bytes that a Cell needs in the cell
38523 ** data area of the btree-page.  The return number includes the cell
38524 ** data header and the local payload, but not any overflow page or
38525 ** the space used by the cell pointer.
38526 */
38527 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
38528   u8 *pIter = &pCell[pPage->childPtrSize];
38529   u32 nSize;
38530
38531 #ifdef SQLITE_DEBUG
38532   /* The value returned by this function should always be the same as
38533   ** the (CellInfo.nSize) value found by doing a full parse of the
38534   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
38535   ** this function verifies that this invariant is not violated. */
38536   CellInfo debuginfo;
38537   btreeParseCellPtr(pPage, pCell, &debuginfo);
38538 #endif
38539
38540   if( pPage->intKey ){
38541     u8 *pEnd;
38542     if( pPage->hasData ){
38543       pIter += getVarint32(pIter, nSize);
38544     }else{
38545       nSize = 0;
38546     }
38547
38548     /* pIter now points at the 64-bit integer key value, a variable length 
38549     ** integer. The following block moves pIter to point at the first byte
38550     ** past the end of the key value. */
38551     pEnd = &pIter[9];
38552     while( (*pIter++)&0x80 && pIter<pEnd );
38553   }else{
38554     pIter += getVarint32(pIter, nSize);
38555   }
38556
38557   testcase( nSize==pPage->maxLocal );
38558   testcase( nSize==pPage->maxLocal+1 );
38559   if( nSize>pPage->maxLocal ){
38560     int minLocal = pPage->minLocal;
38561     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
38562     testcase( nSize==pPage->maxLocal );
38563     testcase( nSize==pPage->maxLocal+1 );
38564     if( nSize>pPage->maxLocal ){
38565       nSize = minLocal;
38566     }
38567     nSize += 4;
38568   }
38569   nSize += (u32)(pIter - pCell);
38570
38571   /* The minimum size of any cell is 4 bytes. */
38572   if( nSize<4 ){
38573     nSize = 4;
38574   }
38575
38576   assert( nSize==debuginfo.nSize );
38577   return (u16)nSize;
38578 }
38579
38580 #ifdef SQLITE_DEBUG
38581 /* This variation on cellSizePtr() is used inside of assert() statements
38582 ** only. */
38583 static u16 cellSize(MemPage *pPage, int iCell){
38584   return cellSizePtr(pPage, findCell(pPage, iCell));
38585 }
38586 #endif
38587
38588 #ifndef SQLITE_OMIT_AUTOVACUUM
38589 /*
38590 ** If the cell pCell, part of page pPage contains a pointer
38591 ** to an overflow page, insert an entry into the pointer-map
38592 ** for the overflow page.
38593 */
38594 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
38595   CellInfo info;
38596   if( *pRC ) return;
38597   assert( pCell!=0 );
38598   btreeParseCellPtr(pPage, pCell, &info);
38599   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
38600   if( info.iOverflow ){
38601     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
38602     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
38603   }
38604 }
38605 #endif
38606
38607
38608 /*
38609 ** Defragment the page given.  All Cells are moved to the
38610 ** end of the page and all free space is collected into one
38611 ** big FreeBlk that occurs in between the header and cell
38612 ** pointer array and the cell content area.
38613 */
38614 static int defragmentPage(MemPage *pPage){
38615   int i;                     /* Loop counter */
38616   int pc;                    /* Address of a i-th cell */
38617   int hdr;                   /* Offset to the page header */
38618   int size;                  /* Size of a cell */
38619   int usableSize;            /* Number of usable bytes on a page */
38620   int cellOffset;            /* Offset to the cell pointer array */
38621   int cbrk;                  /* Offset to the cell content area */
38622   int nCell;                 /* Number of cells on the page */
38623   unsigned char *data;       /* The page data */
38624   unsigned char *temp;       /* Temp area for cell content */
38625   int iCellFirst;            /* First allowable cell index */
38626   int iCellLast;             /* Last possible cell index */
38627
38628
38629   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38630   assert( pPage->pBt!=0 );
38631   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
38632   assert( pPage->nOverflow==0 );
38633   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38634   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
38635   data = pPage->aData;
38636   hdr = pPage->hdrOffset;
38637   cellOffset = pPage->cellOffset;
38638   nCell = pPage->nCell;
38639   assert( nCell==get2byte(&data[hdr+3]) );
38640   usableSize = pPage->pBt->usableSize;
38641   cbrk = get2byte(&data[hdr+5]);
38642   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
38643   cbrk = usableSize;
38644   iCellFirst = cellOffset + 2*nCell;
38645   iCellLast = usableSize - 4;
38646   for(i=0; i<nCell; i++){
38647     u8 *pAddr;     /* The i-th cell pointer */
38648     pAddr = &data[cellOffset + i*2];
38649     pc = get2byte(pAddr);
38650     testcase( pc==iCellFirst );
38651     testcase( pc==iCellLast );
38652 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
38653     /* These conditions have already been verified in btreeInitPage()
38654     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
38655     */
38656     if( pc<iCellFirst || pc>iCellLast ){
38657       return SQLITE_CORRUPT_BKPT;
38658     }
38659 #endif
38660     assert( pc>=iCellFirst && pc<=iCellLast );
38661     size = cellSizePtr(pPage, &temp[pc]);
38662     cbrk -= size;
38663 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
38664     if( cbrk<iCellFirst ){
38665       return SQLITE_CORRUPT_BKPT;
38666     }
38667 #else
38668     if( cbrk<iCellFirst || pc+size>usableSize ){
38669       return SQLITE_CORRUPT_BKPT;
38670     }
38671 #endif
38672     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
38673     testcase( cbrk+size==usableSize );
38674     testcase( pc+size==usableSize );
38675     memcpy(&data[cbrk], &temp[pc], size);
38676     put2byte(pAddr, cbrk);
38677   }
38678   assert( cbrk>=iCellFirst );
38679   put2byte(&data[hdr+5], cbrk);
38680   data[hdr+1] = 0;
38681   data[hdr+2] = 0;
38682   data[hdr+7] = 0;
38683   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
38684   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38685   if( cbrk-iCellFirst!=pPage->nFree ){
38686     return SQLITE_CORRUPT_BKPT;
38687   }
38688   return SQLITE_OK;
38689 }
38690
38691 /*
38692 ** Allocate nByte bytes of space from within the B-Tree page passed
38693 ** as the first argument. Write into *pIdx the index into pPage->aData[]
38694 ** of the first byte of allocated space. Return either SQLITE_OK or
38695 ** an error code (usually SQLITE_CORRUPT).
38696 **
38697 ** The caller guarantees that there is sufficient space to make the
38698 ** allocation.  This routine might need to defragment in order to bring
38699 ** all the space together, however.  This routine will avoid using
38700 ** the first two bytes past the cell pointer area since presumably this
38701 ** allocation is being made in order to insert a new cell, so we will
38702 ** also end up needing a new cell pointer.
38703 */
38704 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
38705   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
38706   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
38707   int nFrag;                           /* Number of fragmented bytes on pPage */
38708   int top;                             /* First byte of cell content area */
38709   int gap;        /* First byte of gap between cell pointers and cell content */
38710   int rc;         /* Integer return code */
38711   int usableSize; /* Usable size of the page */
38712   
38713   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38714   assert( pPage->pBt );
38715   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38716   assert( nByte>=0 );  /* Minimum cell size is 4 */
38717   assert( pPage->nFree>=nByte );
38718   assert( pPage->nOverflow==0 );
38719   usableSize = pPage->pBt->usableSize;
38720   assert( nByte < usableSize-8 );
38721
38722   nFrag = data[hdr+7];
38723   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
38724   gap = pPage->cellOffset + 2*pPage->nCell;
38725   top = get2byte(&data[hdr+5]);
38726   if( gap>top ) return SQLITE_CORRUPT_BKPT;
38727   testcase( gap+2==top );
38728   testcase( gap+1==top );
38729   testcase( gap==top );
38730
38731   if( nFrag>=60 ){
38732     /* Always defragment highly fragmented pages */
38733     rc = defragmentPage(pPage);
38734     if( rc ) return rc;
38735     top = get2byte(&data[hdr+5]);
38736   }else if( gap+2<=top ){
38737     /* Search the freelist looking for a free slot big enough to satisfy 
38738     ** the request. The allocation is made from the first free slot in 
38739     ** the list that is large enough to accomadate it.
38740     */
38741     int pc, addr;
38742     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
38743       int size;            /* Size of the free slot */
38744       if( pc>usableSize-4 || pc<addr+4 ){
38745         return SQLITE_CORRUPT_BKPT;
38746       }
38747       size = get2byte(&data[pc+2]);
38748       if( size>=nByte ){
38749         int x = size - nByte;
38750         testcase( x==4 );
38751         testcase( x==3 );
38752         if( x<4 ){
38753           /* Remove the slot from the free-list. Update the number of
38754           ** fragmented bytes within the page. */
38755           memcpy(&data[addr], &data[pc], 2);
38756           data[hdr+7] = (u8)(nFrag + x);
38757         }else if( size+pc > usableSize ){
38758           return SQLITE_CORRUPT_BKPT;
38759         }else{
38760           /* The slot remains on the free-list. Reduce its size to account
38761           ** for the portion used by the new allocation. */
38762           put2byte(&data[pc+2], x);
38763         }
38764         *pIdx = pc + x;
38765         return SQLITE_OK;
38766       }
38767     }
38768   }
38769
38770   /* Check to make sure there is enough space in the gap to satisfy
38771   ** the allocation.  If not, defragment.
38772   */
38773   testcase( gap+2+nByte==top );
38774   if( gap+2+nByte>top ){
38775     rc = defragmentPage(pPage);
38776     if( rc ) return rc;
38777     top = get2byte(&data[hdr+5]);
38778     assert( gap+nByte<=top );
38779   }
38780
38781
38782   /* Allocate memory from the gap in between the cell pointer array
38783   ** and the cell content area.  The btreeInitPage() call has already
38784   ** validated the freelist.  Given that the freelist is valid, there
38785   ** is no way that the allocation can extend off the end of the page.
38786   ** The assert() below verifies the previous sentence.
38787   */
38788   top -= nByte;
38789   put2byte(&data[hdr+5], top);
38790   assert( top+nByte <= pPage->pBt->usableSize );
38791   *pIdx = top;
38792   return SQLITE_OK;
38793 }
38794
38795 /*
38796 ** Return a section of the pPage->aData to the freelist.
38797 ** The first byte of the new free block is pPage->aDisk[start]
38798 ** and the size of the block is "size" bytes.
38799 **
38800 ** Most of the effort here is involved in coalesing adjacent
38801 ** free blocks into a single big free block.
38802 */
38803 static int freeSpace(MemPage *pPage, int start, int size){
38804   int addr, pbegin, hdr;
38805   int iLast;                        /* Largest possible freeblock offset */
38806   unsigned char *data = pPage->aData;
38807
38808   assert( pPage->pBt!=0 );
38809   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38810   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
38811   assert( (start + size)<=pPage->pBt->usableSize );
38812   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38813   assert( size>=0 );   /* Minimum cell size is 4 */
38814
38815 #ifdef SQLITE_SECURE_DELETE
38816   /* Overwrite deleted information with zeros when the SECURE_DELETE 
38817   ** option is enabled at compile-time */
38818   memset(&data[start], 0, size);
38819 #endif
38820
38821   /* Add the space back into the linked list of freeblocks.  Note that
38822   ** even though the freeblock list was checked by btreeInitPage(),
38823   ** btreeInitPage() did not detect overlapping cells or
38824   ** freeblocks that overlapped cells.   Nor does it detect when the
38825   ** cell content area exceeds the value in the page header.  If these
38826   ** situations arise, then subsequent insert operations might corrupt
38827   ** the freelist.  So we do need to check for corruption while scanning
38828   ** the freelist.
38829   */
38830   hdr = pPage->hdrOffset;
38831   addr = hdr + 1;
38832   iLast = pPage->pBt->usableSize - 4;
38833   assert( start<=iLast );
38834   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
38835     if( pbegin<addr+4 ){
38836       return SQLITE_CORRUPT_BKPT;
38837     }
38838     addr = pbegin;
38839   }
38840   if( pbegin>iLast ){
38841     return SQLITE_CORRUPT_BKPT;
38842   }
38843   assert( pbegin>addr || pbegin==0 );
38844   put2byte(&data[addr], start);
38845   put2byte(&data[start], pbegin);
38846   put2byte(&data[start+2], size);
38847   pPage->nFree = pPage->nFree + (u16)size;
38848
38849   /* Coalesce adjacent free blocks */
38850   addr = hdr + 1;
38851   while( (pbegin = get2byte(&data[addr]))>0 ){
38852     int pnext, psize, x;
38853     assert( pbegin>addr );
38854     assert( pbegin<=pPage->pBt->usableSize-4 );
38855     pnext = get2byte(&data[pbegin]);
38856     psize = get2byte(&data[pbegin+2]);
38857     if( pbegin + psize + 3 >= pnext && pnext>0 ){
38858       int frag = pnext - (pbegin+psize);
38859       if( (frag<0) || (frag>(int)data[hdr+7]) ){
38860         return SQLITE_CORRUPT_BKPT;
38861       }
38862       data[hdr+7] -= (u8)frag;
38863       x = get2byte(&data[pnext]);
38864       put2byte(&data[pbegin], x);
38865       x = pnext + get2byte(&data[pnext+2]) - pbegin;
38866       put2byte(&data[pbegin+2], x);
38867     }else{
38868       addr = pbegin;
38869     }
38870   }
38871
38872   /* If the cell content area begins with a freeblock, remove it. */
38873   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
38874     int top;
38875     pbegin = get2byte(&data[hdr+1]);
38876     memcpy(&data[hdr+1], &data[pbegin], 2);
38877     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
38878     put2byte(&data[hdr+5], top);
38879   }
38880   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38881   return SQLITE_OK;
38882 }
38883
38884 /*
38885 ** Decode the flags byte (the first byte of the header) for a page
38886 ** and initialize fields of the MemPage structure accordingly.
38887 **
38888 ** Only the following combinations are supported.  Anything different
38889 ** indicates a corrupt database files:
38890 **
38891 **         PTF_ZERODATA
38892 **         PTF_ZERODATA | PTF_LEAF
38893 **         PTF_LEAFDATA | PTF_INTKEY
38894 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
38895 */
38896 static int decodeFlags(MemPage *pPage, int flagByte){
38897   BtShared *pBt;     /* A copy of pPage->pBt */
38898
38899   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
38900   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38901   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
38902   flagByte &= ~PTF_LEAF;
38903   pPage->childPtrSize = 4-4*pPage->leaf;
38904   pBt = pPage->pBt;
38905   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
38906     pPage->intKey = 1;
38907     pPage->hasData = pPage->leaf;
38908     pPage->maxLocal = pBt->maxLeaf;
38909     pPage->minLocal = pBt->minLeaf;
38910   }else if( flagByte==PTF_ZERODATA ){
38911     pPage->intKey = 0;
38912     pPage->hasData = 0;
38913     pPage->maxLocal = pBt->maxLocal;
38914     pPage->minLocal = pBt->minLocal;
38915   }else{
38916     return SQLITE_CORRUPT_BKPT;
38917   }
38918   return SQLITE_OK;
38919 }
38920
38921 /*
38922 ** Initialize the auxiliary information for a disk block.
38923 **
38924 ** Return SQLITE_OK on success.  If we see that the page does
38925 ** not contain a well-formed database page, then return 
38926 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
38927 ** guarantee that the page is well-formed.  It only shows that
38928 ** we failed to detect any corruption.
38929 */
38930 static int btreeInitPage(MemPage *pPage){
38931
38932   assert( pPage->pBt!=0 );
38933   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38934   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
38935   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
38936   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
38937
38938   if( !pPage->isInit ){
38939     u16 pc;            /* Address of a freeblock within pPage->aData[] */
38940     u8 hdr;            /* Offset to beginning of page header */
38941     u8 *data;          /* Equal to pPage->aData */
38942     BtShared *pBt;        /* The main btree structure */
38943     u16 usableSize;    /* Amount of usable space on each page */
38944     u16 cellOffset;    /* Offset from start of page to first cell pointer */
38945     u16 nFree;         /* Number of unused bytes on the page */
38946     u16 top;           /* First byte of the cell content area */
38947     int iCellFirst;    /* First allowable cell or freeblock offset */
38948     int iCellLast;     /* Last possible cell or freeblock offset */
38949
38950     pBt = pPage->pBt;
38951
38952     hdr = pPage->hdrOffset;
38953     data = pPage->aData;
38954     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
38955     assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
38956     pPage->maskPage = pBt->pageSize - 1;
38957     pPage->nOverflow = 0;
38958     usableSize = pBt->usableSize;
38959     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
38960     top = get2byte(&data[hdr+5]);
38961     pPage->nCell = get2byte(&data[hdr+3]);
38962     if( pPage->nCell>MX_CELL(pBt) ){
38963       /* To many cells for a single page.  The page must be corrupt */
38964       return SQLITE_CORRUPT_BKPT;
38965     }
38966     testcase( pPage->nCell==MX_CELL(pBt) );
38967
38968     /* A malformed database page might cause us to read past the end
38969     ** of page when parsing a cell.  
38970     **
38971     ** The following block of code checks early to see if a cell extends
38972     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
38973     ** returned if it does.
38974     */
38975     iCellFirst = cellOffset + 2*pPage->nCell;
38976     iCellLast = usableSize - 4;
38977 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
38978     {
38979       int i;            /* Index into the cell pointer array */
38980       int sz;           /* Size of a cell */
38981
38982       if( !pPage->leaf ) iCellLast--;
38983       for(i=0; i<pPage->nCell; i++){
38984         pc = get2byte(&data[cellOffset+i*2]);
38985         testcase( pc==iCellFirst );
38986         testcase( pc==iCellLast );
38987         if( pc<iCellFirst || pc>iCellLast ){
38988           return SQLITE_CORRUPT_BKPT;
38989         }
38990         sz = cellSizePtr(pPage, &data[pc]);
38991         testcase( pc+sz==usableSize );
38992         if( pc+sz>usableSize ){
38993           return SQLITE_CORRUPT_BKPT;
38994         }
38995       }
38996       if( !pPage->leaf ) iCellLast++;
38997     }  
38998 #endif
38999
39000     /* Compute the total free space on the page */
39001     pc = get2byte(&data[hdr+1]);
39002     nFree = data[hdr+7] + top;
39003     while( pc>0 ){
39004       u16 next, size;
39005       if( pc<iCellFirst || pc>iCellLast ){
39006         /* Start of free block is off the page */
39007         return SQLITE_CORRUPT_BKPT; 
39008       }
39009       next = get2byte(&data[pc]);
39010       size = get2byte(&data[pc+2]);
39011       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
39012         /* Free blocks must be in ascending order. And the last byte of
39013         ** the free-block must lie on the database page.  */
39014         return SQLITE_CORRUPT_BKPT; 
39015       }
39016       nFree = nFree + size;
39017       pc = next;
39018     }
39019
39020     /* At this point, nFree contains the sum of the offset to the start
39021     ** of the cell-content area plus the number of free bytes within
39022     ** the cell-content area. If this is greater than the usable-size
39023     ** of the page, then the page must be corrupted. This check also
39024     ** serves to verify that the offset to the start of the cell-content
39025     ** area, according to the page header, lies within the page.
39026     */
39027     if( nFree>usableSize ){
39028       return SQLITE_CORRUPT_BKPT; 
39029     }
39030     pPage->nFree = (u16)(nFree - iCellFirst);
39031     pPage->isInit = 1;
39032   }
39033   return SQLITE_OK;
39034 }
39035
39036 /*
39037 ** Set up a raw page so that it looks like a database page holding
39038 ** no entries.
39039 */
39040 static void zeroPage(MemPage *pPage, int flags){
39041   unsigned char *data = pPage->aData;
39042   BtShared *pBt = pPage->pBt;
39043   u8 hdr = pPage->hdrOffset;
39044   u16 first;
39045
39046   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
39047   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
39048   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
39049   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
39050   assert( sqlite3_mutex_held(pBt->mutex) );
39051 #ifdef SQLITE_SECURE_DELETE
39052   memset(&data[hdr], 0, pBt->usableSize - hdr);
39053 #endif
39054   data[hdr] = (char)flags;
39055   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
39056   memset(&data[hdr+1], 0, 4);
39057   data[hdr+7] = 0;
39058   put2byte(&data[hdr+5], pBt->usableSize);
39059   pPage->nFree = pBt->usableSize - first;
39060   decodeFlags(pPage, flags);
39061   pPage->hdrOffset = hdr;
39062   pPage->cellOffset = first;
39063   pPage->nOverflow = 0;
39064   assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
39065   pPage->maskPage = pBt->pageSize - 1;
39066   pPage->nCell = 0;
39067   pPage->isInit = 1;
39068 }
39069
39070
39071 /*
39072 ** Convert a DbPage obtained from the pager into a MemPage used by
39073 ** the btree layer.
39074 */
39075 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
39076   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
39077   pPage->aData = sqlite3PagerGetData(pDbPage);
39078   pPage->pDbPage = pDbPage;
39079   pPage->pBt = pBt;
39080   pPage->pgno = pgno;
39081   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
39082   return pPage; 
39083 }
39084
39085 /*
39086 ** Get a page from the pager.  Initialize the MemPage.pBt and
39087 ** MemPage.aData elements if needed.
39088 **
39089 ** If the noContent flag is set, it means that we do not care about
39090 ** the content of the page at this time.  So do not go to the disk
39091 ** to fetch the content.  Just fill in the content with zeros for now.
39092 ** If in the future we call sqlite3PagerWrite() on this page, that
39093 ** means we have started to be concerned about content and the disk
39094 ** read should occur at that point.
39095 */
39096 static int btreeGetPage(
39097   BtShared *pBt,       /* The btree */
39098   Pgno pgno,           /* Number of the page to fetch */
39099   MemPage **ppPage,    /* Return the page in this parameter */
39100   int noContent        /* Do not load page content if true */
39101 ){
39102   int rc;
39103   DbPage *pDbPage;
39104
39105   assert( sqlite3_mutex_held(pBt->mutex) );
39106   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
39107   if( rc ) return rc;
39108   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
39109   return SQLITE_OK;
39110 }
39111
39112 /*
39113 ** Retrieve a page from the pager cache. If the requested page is not
39114 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
39115 ** MemPage.aData elements if needed.
39116 */
39117 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
39118   DbPage *pDbPage;
39119   assert( sqlite3_mutex_held(pBt->mutex) );
39120   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
39121   if( pDbPage ){
39122     return btreePageFromDbPage(pDbPage, pgno, pBt);
39123   }
39124   return 0;
39125 }
39126
39127 /*
39128 ** Return the size of the database file in pages. If there is any kind of
39129 ** error, return ((unsigned int)-1).
39130 */
39131 static Pgno pagerPagecount(BtShared *pBt){
39132   int nPage = -1;
39133   int rc;
39134   assert( pBt->pPage1 );
39135   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
39136   assert( rc==SQLITE_OK || nPage==-1 );
39137   return (Pgno)nPage;
39138 }
39139
39140 /*
39141 ** Get a page from the pager and initialize it.  This routine is just a
39142 ** convenience wrapper around separate calls to btreeGetPage() and 
39143 ** btreeInitPage().
39144 **
39145 ** If an error occurs, then the value *ppPage is set to is undefined. It
39146 ** may remain unchanged, or it may be set to an invalid value.
39147 */
39148 static int getAndInitPage(
39149   BtShared *pBt,          /* The database file */
39150   Pgno pgno,           /* Number of the page to get */
39151   MemPage **ppPage     /* Write the page pointer here */
39152 ){
39153   int rc;
39154   TESTONLY( Pgno iLastPg = pagerPagecount(pBt); )
39155   assert( sqlite3_mutex_held(pBt->mutex) );
39156
39157   rc = btreeGetPage(pBt, pgno, ppPage, 0);
39158   if( rc==SQLITE_OK ){
39159     rc = btreeInitPage(*ppPage);
39160     if( rc!=SQLITE_OK ){
39161       releasePage(*ppPage);
39162     }
39163   }
39164
39165   /* If the requested page number was either 0 or greater than the page
39166   ** number of the last page in the database, this function should return
39167   ** SQLITE_CORRUPT or some other error (i.e. SQLITE_FULL). Check that this
39168   ** is the case.  */
39169   assert( (pgno>0 && pgno<=iLastPg) || rc!=SQLITE_OK );
39170   testcase( pgno==0 );
39171   testcase( pgno==iLastPg );
39172
39173   return rc;
39174 }
39175
39176 /*
39177 ** Release a MemPage.  This should be called once for each prior
39178 ** call to btreeGetPage.
39179 */
39180 static void releasePage(MemPage *pPage){
39181   if( pPage ){
39182     assert( pPage->aData );
39183     assert( pPage->pBt );
39184     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
39185     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
39186     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39187     sqlite3PagerUnref(pPage->pDbPage);
39188   }
39189 }
39190
39191 /*
39192 ** During a rollback, when the pager reloads information into the cache
39193 ** so that the cache is restored to its original state at the start of
39194 ** the transaction, for each page restored this routine is called.
39195 **
39196 ** This routine needs to reset the extra data section at the end of the
39197 ** page to agree with the restored data.
39198 */
39199 static void pageReinit(DbPage *pData){
39200   MemPage *pPage;
39201   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
39202   assert( sqlite3PagerPageRefcount(pData)>0 );
39203   if( pPage->isInit ){
39204     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39205     pPage->isInit = 0;
39206     if( sqlite3PagerPageRefcount(pData)>1 ){
39207       /* pPage might not be a btree page;  it might be an overflow page
39208       ** or ptrmap page or a free page.  In those cases, the following
39209       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
39210       ** But no harm is done by this.  And it is very important that
39211       ** btreeInitPage() be called on every btree page so we make
39212       ** the call for every page that comes in for re-initing. */
39213       btreeInitPage(pPage);
39214     }
39215   }
39216 }
39217
39218 /*
39219 ** Invoke the busy handler for a btree.
39220 */
39221 static int btreeInvokeBusyHandler(void *pArg){
39222   BtShared *pBt = (BtShared*)pArg;
39223   assert( pBt->db );
39224   assert( sqlite3_mutex_held(pBt->db->mutex) );
39225   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
39226 }
39227
39228 /*
39229 ** Open a database file.
39230 ** 
39231 ** zFilename is the name of the database file.  If zFilename is NULL
39232 ** a new database with a random name is created.  This randomly named
39233 ** database file will be deleted when sqlite3BtreeClose() is called.
39234 ** If zFilename is ":memory:" then an in-memory database is created
39235 ** that is automatically destroyed when it is closed.
39236 **
39237 ** If the database is already opened in the same database connection
39238 ** and we are in shared cache mode, then the open will fail with an
39239 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
39240 ** objects in the same database connection since doing so will lead
39241 ** to problems with locking.
39242 */
39243 SQLITE_PRIVATE int sqlite3BtreeOpen(
39244   const char *zFilename,  /* Name of the file containing the BTree database */
39245   sqlite3 *db,            /* Associated database handle */
39246   Btree **ppBtree,        /* Pointer to new Btree object written here */
39247   int flags,              /* Options */
39248   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
39249 ){
39250   sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
39251   BtShared *pBt = 0;             /* Shared part of btree structure */
39252   Btree *p;                      /* Handle to return */
39253   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
39254   int rc = SQLITE_OK;            /* Result code from this function */
39255   u8 nReserve;                   /* Byte of unused space on each page */
39256   unsigned char zDbHeader[100];  /* Database header content */
39257
39258   /* Set the variable isMemdb to true for an in-memory database, or 
39259   ** false for a file-based database. This symbol is only required if
39260   ** either of the shared-data or autovacuum features are compiled 
39261   ** into the library.
39262   */
39263 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
39264   #ifdef SQLITE_OMIT_MEMORYDB
39265     const int isMemdb = 0;
39266   #else
39267     const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
39268   #endif
39269 #endif
39270
39271   assert( db!=0 );
39272   assert( sqlite3_mutex_held(db->mutex) );
39273
39274   pVfs = db->pVfs;
39275   p = sqlite3MallocZero(sizeof(Btree));
39276   if( !p ){
39277     return SQLITE_NOMEM;
39278   }
39279   p->inTrans = TRANS_NONE;
39280   p->db = db;
39281 #ifndef SQLITE_OMIT_SHARED_CACHE
39282   p->lock.pBtree = p;
39283   p->lock.iTable = 1;
39284 #endif
39285
39286 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
39287   /*
39288   ** If this Btree is a candidate for shared cache, try to find an
39289   ** existing BtShared object that we can share with
39290   */
39291   if( isMemdb==0 && zFilename && zFilename[0] ){
39292     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
39293       int nFullPathname = pVfs->mxPathname+1;
39294       char *zFullPathname = sqlite3Malloc(nFullPathname);
39295       sqlite3_mutex *mutexShared;
39296       p->sharable = 1;
39297       if( !zFullPathname ){
39298         sqlite3_free(p);
39299         return SQLITE_NOMEM;
39300       }
39301       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
39302       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
39303       sqlite3_mutex_enter(mutexOpen);
39304       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
39305       sqlite3_mutex_enter(mutexShared);
39306       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
39307         assert( pBt->nRef>0 );
39308         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
39309                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
39310           int iDb;
39311           for(iDb=db->nDb-1; iDb>=0; iDb--){
39312             Btree *pExisting = db->aDb[iDb].pBt;
39313             if( pExisting && pExisting->pBt==pBt ){
39314               sqlite3_mutex_leave(mutexShared);
39315               sqlite3_mutex_leave(mutexOpen);
39316               sqlite3_free(zFullPathname);
39317               sqlite3_free(p);
39318               return SQLITE_CONSTRAINT;
39319             }
39320           }
39321           p->pBt = pBt;
39322           pBt->nRef++;
39323           break;
39324         }
39325       }
39326       sqlite3_mutex_leave(mutexShared);
39327       sqlite3_free(zFullPathname);
39328     }
39329 #ifdef SQLITE_DEBUG
39330     else{
39331       /* In debug mode, we mark all persistent databases as sharable
39332       ** even when they are not.  This exercises the locking code and
39333       ** gives more opportunity for asserts(sqlite3_mutex_held())
39334       ** statements to find locking problems.
39335       */
39336       p->sharable = 1;
39337     }
39338 #endif
39339   }
39340 #endif
39341   if( pBt==0 ){
39342     /*
39343     ** The following asserts make sure that structures used by the btree are
39344     ** the right size.  This is to guard against size changes that result
39345     ** when compiling on a different architecture.
39346     */
39347     assert( sizeof(i64)==8 || sizeof(i64)==4 );
39348     assert( sizeof(u64)==8 || sizeof(u64)==4 );
39349     assert( sizeof(u32)==4 );
39350     assert( sizeof(u16)==2 );
39351     assert( sizeof(Pgno)==4 );
39352   
39353     pBt = sqlite3MallocZero( sizeof(*pBt) );
39354     if( pBt==0 ){
39355       rc = SQLITE_NOMEM;
39356       goto btree_open_out;
39357     }
39358     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
39359                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
39360     if( rc==SQLITE_OK ){
39361       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
39362     }
39363     if( rc!=SQLITE_OK ){
39364       goto btree_open_out;
39365     }
39366     pBt->db = db;
39367     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
39368     p->pBt = pBt;
39369   
39370     pBt->pCursor = 0;
39371     pBt->pPage1 = 0;
39372     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
39373     pBt->pageSize = get2byte(&zDbHeader[16]);
39374     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
39375          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
39376       pBt->pageSize = 0;
39377 #ifndef SQLITE_OMIT_AUTOVACUUM
39378       /* If the magic name ":memory:" will create an in-memory database, then
39379       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
39380       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
39381       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
39382       ** regular file-name. In this case the auto-vacuum applies as per normal.
39383       */
39384       if( zFilename && !isMemdb ){
39385         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
39386         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
39387       }
39388 #endif
39389       nReserve = 0;
39390     }else{
39391       nReserve = zDbHeader[20];
39392       pBt->pageSizeFixed = 1;
39393 #ifndef SQLITE_OMIT_AUTOVACUUM
39394       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
39395       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
39396 #endif
39397     }
39398     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
39399     if( rc ) goto btree_open_out;
39400     pBt->usableSize = pBt->pageSize - nReserve;
39401     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
39402    
39403 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
39404     /* Add the new BtShared object to the linked list sharable BtShareds.
39405     */
39406     if( p->sharable ){
39407       sqlite3_mutex *mutexShared;
39408       pBt->nRef = 1;
39409       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
39410       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
39411         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
39412         if( pBt->mutex==0 ){
39413           rc = SQLITE_NOMEM;
39414           db->mallocFailed = 0;
39415           goto btree_open_out;
39416         }
39417       }
39418       sqlite3_mutex_enter(mutexShared);
39419       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
39420       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
39421       sqlite3_mutex_leave(mutexShared);
39422     }
39423 #endif
39424   }
39425
39426 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
39427   /* If the new Btree uses a sharable pBtShared, then link the new
39428   ** Btree into the list of all sharable Btrees for the same connection.
39429   ** The list is kept in ascending order by pBt address.
39430   */
39431   if( p->sharable ){
39432     int i;
39433     Btree *pSib;
39434     for(i=0; i<db->nDb; i++){
39435       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
39436         while( pSib->pPrev ){ pSib = pSib->pPrev; }
39437         if( p->pBt<pSib->pBt ){
39438           p->pNext = pSib;
39439           p->pPrev = 0;
39440           pSib->pPrev = p;
39441         }else{
39442           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
39443             pSib = pSib->pNext;
39444           }
39445           p->pNext = pSib->pNext;
39446           p->pPrev = pSib;
39447           if( p->pNext ){
39448             p->pNext->pPrev = p;
39449           }
39450           pSib->pNext = p;
39451         }
39452         break;
39453       }
39454     }
39455   }
39456 #endif
39457   *ppBtree = p;
39458
39459 btree_open_out:
39460   if( rc!=SQLITE_OK ){
39461     if( pBt && pBt->pPager ){
39462       sqlite3PagerClose(pBt->pPager);
39463     }
39464     sqlite3_free(pBt);
39465     sqlite3_free(p);
39466     *ppBtree = 0;
39467   }
39468   if( mutexOpen ){
39469     assert( sqlite3_mutex_held(mutexOpen) );
39470     sqlite3_mutex_leave(mutexOpen);
39471   }
39472   return rc;
39473 }
39474
39475 /*
39476 ** Decrement the BtShared.nRef counter.  When it reaches zero,
39477 ** remove the BtShared structure from the sharing list.  Return
39478 ** true if the BtShared.nRef counter reaches zero and return
39479 ** false if it is still positive.
39480 */
39481 static int removeFromSharingList(BtShared *pBt){
39482 #ifndef SQLITE_OMIT_SHARED_CACHE
39483   sqlite3_mutex *pMaster;
39484   BtShared *pList;
39485   int removed = 0;
39486
39487   assert( sqlite3_mutex_notheld(pBt->mutex) );
39488   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
39489   sqlite3_mutex_enter(pMaster);
39490   pBt->nRef--;
39491   if( pBt->nRef<=0 ){
39492     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
39493       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
39494     }else{
39495       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
39496       while( ALWAYS(pList) && pList->pNext!=pBt ){
39497         pList=pList->pNext;
39498       }
39499       if( ALWAYS(pList) ){
39500         pList->pNext = pBt->pNext;
39501       }
39502     }
39503     if( SQLITE_THREADSAFE ){
39504       sqlite3_mutex_free(pBt->mutex);
39505     }
39506     removed = 1;
39507   }
39508   sqlite3_mutex_leave(pMaster);
39509   return removed;
39510 #else
39511   return 1;
39512 #endif
39513 }
39514
39515 /*
39516 ** Make sure pBt->pTmpSpace points to an allocation of 
39517 ** MX_CELL_SIZE(pBt) bytes.
39518 */
39519 static void allocateTempSpace(BtShared *pBt){
39520   if( !pBt->pTmpSpace ){
39521     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
39522   }
39523 }
39524
39525 /*
39526 ** Free the pBt->pTmpSpace allocation
39527 */
39528 static void freeTempSpace(BtShared *pBt){
39529   sqlite3PageFree( pBt->pTmpSpace);
39530   pBt->pTmpSpace = 0;
39531 }
39532
39533 /*
39534 ** Close an open database and invalidate all cursors.
39535 */
39536 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
39537   BtShared *pBt = p->pBt;
39538   BtCursor *pCur;
39539
39540   /* Close all cursors opened via this handle.  */
39541   assert( sqlite3_mutex_held(p->db->mutex) );
39542   sqlite3BtreeEnter(p);
39543   pCur = pBt->pCursor;
39544   while( pCur ){
39545     BtCursor *pTmp = pCur;
39546     pCur = pCur->pNext;
39547     if( pTmp->pBtree==p ){
39548       sqlite3BtreeCloseCursor(pTmp);
39549     }
39550   }
39551
39552   /* Rollback any active transaction and free the handle structure.
39553   ** The call to sqlite3BtreeRollback() drops any table-locks held by
39554   ** this handle.
39555   */
39556   sqlite3BtreeRollback(p);
39557   sqlite3BtreeLeave(p);
39558
39559   /* If there are still other outstanding references to the shared-btree
39560   ** structure, return now. The remainder of this procedure cleans 
39561   ** up the shared-btree.
39562   */
39563   assert( p->wantToLock==0 && p->locked==0 );
39564   if( !p->sharable || removeFromSharingList(pBt) ){
39565     /* The pBt is no longer on the sharing list, so we can access
39566     ** it without having to hold the mutex.
39567     **
39568     ** Clean out and delete the BtShared object.
39569     */
39570     assert( !pBt->pCursor );
39571     sqlite3PagerClose(pBt->pPager);
39572     if( pBt->xFreeSchema && pBt->pSchema ){
39573       pBt->xFreeSchema(pBt->pSchema);
39574     }
39575     sqlite3_free(pBt->pSchema);
39576     freeTempSpace(pBt);
39577     sqlite3_free(pBt);
39578   }
39579
39580 #ifndef SQLITE_OMIT_SHARED_CACHE
39581   assert( p->wantToLock==0 );
39582   assert( p->locked==0 );
39583   if( p->pPrev ) p->pPrev->pNext = p->pNext;
39584   if( p->pNext ) p->pNext->pPrev = p->pPrev;
39585 #endif
39586
39587   sqlite3_free(p);
39588   return SQLITE_OK;
39589 }
39590
39591 /*
39592 ** Change the limit on the number of pages allowed in the cache.
39593 **
39594 ** The maximum number of cache pages is set to the absolute
39595 ** value of mxPage.  If mxPage is negative, the pager will
39596 ** operate asynchronously - it will not stop to do fsync()s
39597 ** to insure data is written to the disk surface before
39598 ** continuing.  Transactions still work if synchronous is off,
39599 ** and the database cannot be corrupted if this program
39600 ** crashes.  But if the operating system crashes or there is
39601 ** an abrupt power failure when synchronous is off, the database
39602 ** could be left in an inconsistent and unrecoverable state.
39603 ** Synchronous is on by default so database corruption is not
39604 ** normally a worry.
39605 */
39606 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
39607   BtShared *pBt = p->pBt;
39608   assert( sqlite3_mutex_held(p->db->mutex) );
39609   sqlite3BtreeEnter(p);
39610   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
39611   sqlite3BtreeLeave(p);
39612   return SQLITE_OK;
39613 }
39614
39615 /*
39616 ** Change the way data is synced to disk in order to increase or decrease
39617 ** how well the database resists damage due to OS crashes and power
39618 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
39619 ** there is a high probability of damage)  Level 2 is the default.  There
39620 ** is a very low but non-zero probability of damage.  Level 3 reduces the
39621 ** probability of damage to near zero but with a write performance reduction.
39622 */
39623 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
39624 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
39625   BtShared *pBt = p->pBt;
39626   assert( sqlite3_mutex_held(p->db->mutex) );
39627   sqlite3BtreeEnter(p);
39628   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
39629   sqlite3BtreeLeave(p);
39630   return SQLITE_OK;
39631 }
39632 #endif
39633
39634 /*
39635 ** Return TRUE if the given btree is set to safety level 1.  In other
39636 ** words, return TRUE if no sync() occurs on the disk files.
39637 */
39638 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
39639   BtShared *pBt = p->pBt;
39640   int rc;
39641   assert( sqlite3_mutex_held(p->db->mutex) );  
39642   sqlite3BtreeEnter(p);
39643   assert( pBt && pBt->pPager );
39644   rc = sqlite3PagerNosync(pBt->pPager);
39645   sqlite3BtreeLeave(p);
39646   return rc;
39647 }
39648
39649 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
39650 /*
39651 ** Change the default pages size and the number of reserved bytes per page.
39652 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
39653 ** without changing anything.
39654 **
39655 ** The page size must be a power of 2 between 512 and 65536.  If the page
39656 ** size supplied does not meet this constraint then the page size is not
39657 ** changed.
39658 **
39659 ** Page sizes are constrained to be a power of two so that the region
39660 ** of the database file used for locking (beginning at PENDING_BYTE,
39661 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
39662 ** at the beginning of a page.
39663 **
39664 ** If parameter nReserve is less than zero, then the number of reserved
39665 ** bytes per page is left unchanged.
39666 **
39667 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
39668 ** and autovacuum mode can no longer be changed.
39669 */
39670 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
39671   int rc = SQLITE_OK;
39672   BtShared *pBt = p->pBt;
39673   assert( nReserve>=-1 && nReserve<=255 );
39674   sqlite3BtreeEnter(p);
39675   if( pBt->pageSizeFixed ){
39676     sqlite3BtreeLeave(p);
39677     return SQLITE_READONLY;
39678   }
39679   if( nReserve<0 ){
39680     nReserve = pBt->pageSize - pBt->usableSize;
39681   }
39682   assert( nReserve>=0 && nReserve<=255 );
39683   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
39684         ((pageSize-1)&pageSize)==0 ){
39685     assert( (pageSize & 7)==0 );
39686     assert( !pBt->pPage1 && !pBt->pCursor );
39687     pBt->pageSize = (u16)pageSize;
39688     freeTempSpace(pBt);
39689   }
39690   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
39691   pBt->usableSize = pBt->pageSize - (u16)nReserve;
39692   if( iFix ) pBt->pageSizeFixed = 1;
39693   sqlite3BtreeLeave(p);
39694   return rc;
39695 }
39696
39697 /*
39698 ** Return the currently defined page size
39699 */
39700 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
39701   return p->pBt->pageSize;
39702 }
39703
39704 /*
39705 ** Return the number of bytes of space at the end of every page that
39706 ** are intentually left unused.  This is the "reserved" space that is
39707 ** sometimes used by extensions.
39708 */
39709 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
39710   int n;
39711   sqlite3BtreeEnter(p);
39712   n = p->pBt->pageSize - p->pBt->usableSize;
39713   sqlite3BtreeLeave(p);
39714   return n;
39715 }
39716
39717 /*
39718 ** Set the maximum page count for a database if mxPage is positive.
39719 ** No changes are made if mxPage is 0 or negative.
39720 ** Regardless of the value of mxPage, return the maximum page count.
39721 */
39722 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
39723   int n;
39724   sqlite3BtreeEnter(p);
39725   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
39726   sqlite3BtreeLeave(p);
39727   return n;
39728 }
39729 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
39730
39731 /*
39732 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
39733 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
39734 ** is disabled. The default value for the auto-vacuum property is 
39735 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
39736 */
39737 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
39738 #ifdef SQLITE_OMIT_AUTOVACUUM
39739   return SQLITE_READONLY;
39740 #else
39741   BtShared *pBt = p->pBt;
39742   int rc = SQLITE_OK;
39743   u8 av = (u8)autoVacuum;
39744
39745   sqlite3BtreeEnter(p);
39746   if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
39747     rc = SQLITE_READONLY;
39748   }else{
39749     pBt->autoVacuum = av ?1:0;
39750     pBt->incrVacuum = av==2 ?1:0;
39751   }
39752   sqlite3BtreeLeave(p);
39753   return rc;
39754 #endif
39755 }
39756
39757 /*
39758 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
39759 ** enabled 1 is returned. Otherwise 0.
39760 */
39761 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
39762 #ifdef SQLITE_OMIT_AUTOVACUUM
39763   return BTREE_AUTOVACUUM_NONE;
39764 #else
39765   int rc;
39766   sqlite3BtreeEnter(p);
39767   rc = (
39768     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
39769     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
39770     BTREE_AUTOVACUUM_INCR
39771   );
39772   sqlite3BtreeLeave(p);
39773   return rc;
39774 #endif
39775 }
39776
39777
39778 /*
39779 ** Get a reference to pPage1 of the database file.  This will
39780 ** also acquire a readlock on that file.
39781 **
39782 ** SQLITE_OK is returned on success.  If the file is not a
39783 ** well-formed database file, then SQLITE_CORRUPT is returned.
39784 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
39785 ** is returned if we run out of memory. 
39786 */
39787 static int lockBtree(BtShared *pBt){
39788   int rc;
39789   MemPage *pPage1;
39790   int nPage;
39791
39792   assert( sqlite3_mutex_held(pBt->mutex) );
39793   assert( pBt->pPage1==0 );
39794   rc = sqlite3PagerSharedLock(pBt->pPager);
39795   if( rc!=SQLITE_OK ) return rc;
39796   rc = btreeGetPage(pBt, 1, &pPage1, 0);
39797   if( rc!=SQLITE_OK ) return rc;
39798
39799   /* Do some checking to help insure the file we opened really is
39800   ** a valid database file. 
39801   */
39802   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
39803   if( rc!=SQLITE_OK ){
39804     goto page1_init_failed;
39805   }else if( nPage>0 ){
39806     int pageSize;
39807     int usableSize;
39808     u8 *page1 = pPage1->aData;
39809     rc = SQLITE_NOTADB;
39810     if( memcmp(page1, zMagicHeader, 16)!=0 ){
39811       goto page1_init_failed;
39812     }
39813     if( page1[18]>1 ){
39814       pBt->readOnly = 1;
39815     }
39816     if( page1[19]>1 ){
39817       goto page1_init_failed;
39818     }
39819
39820     /* The maximum embedded fraction must be exactly 25%.  And the minimum
39821     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
39822     ** The original design allowed these amounts to vary, but as of
39823     ** version 3.6.0, we require them to be fixed.
39824     */
39825     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
39826       goto page1_init_failed;
39827     }
39828     pageSize = get2byte(&page1[16]);
39829     if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
39830         (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
39831     ){
39832       goto page1_init_failed;
39833     }
39834     assert( (pageSize & 7)==0 );
39835     usableSize = pageSize - page1[20];
39836     if( pageSize!=pBt->pageSize ){
39837       /* After reading the first page of the database assuming a page size
39838       ** of BtShared.pageSize, we have discovered that the page-size is
39839       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
39840       ** zero and return SQLITE_OK. The caller will call this function
39841       ** again with the correct page-size.
39842       */
39843       releasePage(pPage1);
39844       pBt->usableSize = (u16)usableSize;
39845       pBt->pageSize = (u16)pageSize;
39846       freeTempSpace(pBt);
39847       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
39848                                    pageSize-usableSize);
39849       return rc;
39850     }
39851     if( usableSize<480 ){
39852       goto page1_init_failed;
39853     }
39854     pBt->pageSize = (u16)pageSize;
39855     pBt->usableSize = (u16)usableSize;
39856 #ifndef SQLITE_OMIT_AUTOVACUUM
39857     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
39858     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
39859 #endif
39860   }
39861
39862   /* maxLocal is the maximum amount of payload to store locally for
39863   ** a cell.  Make sure it is small enough so that at least minFanout
39864   ** cells can will fit on one page.  We assume a 10-byte page header.
39865   ** Besides the payload, the cell must store:
39866   **     2-byte pointer to the cell
39867   **     4-byte child pointer
39868   **     9-byte nKey value
39869   **     4-byte nData value
39870   **     4-byte overflow page pointer
39871   ** So a cell consists of a 2-byte poiner, a header which is as much as
39872   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
39873   ** page pointer.
39874   */
39875   pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
39876   pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
39877   pBt->maxLeaf = pBt->usableSize - 35;
39878   pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
39879   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
39880   pBt->pPage1 = pPage1;
39881   return SQLITE_OK;
39882
39883 page1_init_failed:
39884   releasePage(pPage1);
39885   pBt->pPage1 = 0;
39886   return rc;
39887 }
39888
39889 /*
39890 ** If there are no outstanding cursors and we are not in the middle
39891 ** of a transaction but there is a read lock on the database, then
39892 ** this routine unrefs the first page of the database file which 
39893 ** has the effect of releasing the read lock.
39894 **
39895 ** If there is a transaction in progress, this routine is a no-op.
39896 */
39897 static void unlockBtreeIfUnused(BtShared *pBt){
39898   assert( sqlite3_mutex_held(pBt->mutex) );
39899   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
39900   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
39901     assert( pBt->pPage1->aData );
39902     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
39903     assert( pBt->pPage1->aData );
39904     releasePage(pBt->pPage1);
39905     pBt->pPage1 = 0;
39906   }
39907 }
39908
39909 /*
39910 ** If pBt points to an empty file then convert that empty file
39911 ** into a new empty database by initializing the first page of
39912 ** the database.
39913 */
39914 static int newDatabase(BtShared *pBt){
39915   MemPage *pP1;
39916   unsigned char *data;
39917   int rc;
39918   int nPage;
39919
39920   assert( sqlite3_mutex_held(pBt->mutex) );
39921   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
39922   if( rc!=SQLITE_OK || nPage>0 ){
39923     return rc;
39924   }
39925   pP1 = pBt->pPage1;
39926   assert( pP1!=0 );
39927   data = pP1->aData;
39928   rc = sqlite3PagerWrite(pP1->pDbPage);
39929   if( rc ) return rc;
39930   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
39931   assert( sizeof(zMagicHeader)==16 );
39932   put2byte(&data[16], pBt->pageSize);
39933   data[18] = 1;
39934   data[19] = 1;
39935   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
39936   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
39937   data[21] = 64;
39938   data[22] = 32;
39939   data[23] = 32;
39940   memset(&data[24], 0, 100-24);
39941   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
39942   pBt->pageSizeFixed = 1;
39943 #ifndef SQLITE_OMIT_AUTOVACUUM
39944   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
39945   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
39946   put4byte(&data[36 + 4*4], pBt->autoVacuum);
39947   put4byte(&data[36 + 7*4], pBt->incrVacuum);
39948 #endif
39949   return SQLITE_OK;
39950 }
39951
39952 /*
39953 ** Attempt to start a new transaction. A write-transaction
39954 ** is started if the second argument is nonzero, otherwise a read-
39955 ** transaction.  If the second argument is 2 or more and exclusive
39956 ** transaction is started, meaning that no other process is allowed
39957 ** to access the database.  A preexisting transaction may not be
39958 ** upgraded to exclusive by calling this routine a second time - the
39959 ** exclusivity flag only works for a new transaction.
39960 **
39961 ** A write-transaction must be started before attempting any 
39962 ** changes to the database.  None of the following routines 
39963 ** will work unless a transaction is started first:
39964 **
39965 **      sqlite3BtreeCreateTable()
39966 **      sqlite3BtreeCreateIndex()
39967 **      sqlite3BtreeClearTable()
39968 **      sqlite3BtreeDropTable()
39969 **      sqlite3BtreeInsert()
39970 **      sqlite3BtreeDelete()
39971 **      sqlite3BtreeUpdateMeta()
39972 **
39973 ** If an initial attempt to acquire the lock fails because of lock contention
39974 ** and the database was previously unlocked, then invoke the busy handler
39975 ** if there is one.  But if there was previously a read-lock, do not
39976 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
39977 ** returned when there is already a read-lock in order to avoid a deadlock.
39978 **
39979 ** Suppose there are two processes A and B.  A has a read lock and B has
39980 ** a reserved lock.  B tries to promote to exclusive but is blocked because
39981 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
39982 ** One or the other of the two processes must give way or there can be
39983 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
39984 ** when A already has a read lock, we encourage A to give up and let B
39985 ** proceed.
39986 */
39987 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
39988   sqlite3 *pBlock = 0;
39989   BtShared *pBt = p->pBt;
39990   int rc = SQLITE_OK;
39991
39992   sqlite3BtreeEnter(p);
39993   btreeIntegrity(p);
39994
39995   /* If the btree is already in a write-transaction, or it
39996   ** is already in a read-transaction and a read-transaction
39997   ** is requested, this is a no-op.
39998   */
39999   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
40000     goto trans_begun;
40001   }
40002
40003   /* Write transactions are not possible on a read-only database */
40004   if( pBt->readOnly && wrflag ){
40005     rc = SQLITE_READONLY;
40006     goto trans_begun;
40007   }
40008
40009 #ifndef SQLITE_OMIT_SHARED_CACHE
40010   /* If another database handle has already opened a write transaction 
40011   ** on this shared-btree structure and a second write transaction is
40012   ** requested, return SQLITE_LOCKED.
40013   */
40014   if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
40015     pBlock = pBt->pWriter->db;
40016   }else if( wrflag>1 ){
40017     BtLock *pIter;
40018     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
40019       if( pIter->pBtree!=p ){
40020         pBlock = pIter->pBtree->db;
40021         break;
40022       }
40023     }
40024   }
40025   if( pBlock ){
40026     sqlite3ConnectionBlocked(p->db, pBlock);
40027     rc = SQLITE_LOCKED_SHAREDCACHE;
40028     goto trans_begun;
40029   }
40030 #endif
40031
40032   /* Any read-only or read-write transaction implies a read-lock on 
40033   ** page 1. So if some other shared-cache client already has a write-lock 
40034   ** on page 1, the transaction cannot be opened. */
40035   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
40036   if( SQLITE_OK!=rc ) goto trans_begun;
40037
40038   do {
40039     /* Call lockBtree() until either pBt->pPage1 is populated or
40040     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
40041     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
40042     ** reading page 1 it discovers that the page-size of the database 
40043     ** file is not pBt->pageSize. In this case lockBtree() will update
40044     ** pBt->pageSize to the page-size of the file on disk.
40045     */
40046     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
40047
40048     if( rc==SQLITE_OK && wrflag ){
40049       if( pBt->readOnly ){
40050         rc = SQLITE_READONLY;
40051       }else{
40052         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
40053         if( rc==SQLITE_OK ){
40054           rc = newDatabase(pBt);
40055         }
40056       }
40057     }
40058   
40059     if( rc!=SQLITE_OK ){
40060       unlockBtreeIfUnused(pBt);
40061     }
40062   }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
40063           btreeInvokeBusyHandler(pBt) );
40064
40065   if( rc==SQLITE_OK ){
40066     if( p->inTrans==TRANS_NONE ){
40067       pBt->nTransaction++;
40068 #ifndef SQLITE_OMIT_SHARED_CACHE
40069       if( p->sharable ){
40070         assert( p->lock.pBtree==p && p->lock.iTable==1 );
40071         p->lock.eLock = READ_LOCK;
40072         p->lock.pNext = pBt->pLock;
40073         pBt->pLock = &p->lock;
40074       }
40075 #endif
40076     }
40077     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
40078     if( p->inTrans>pBt->inTransaction ){
40079       pBt->inTransaction = p->inTrans;
40080     }
40081 #ifndef SQLITE_OMIT_SHARED_CACHE
40082     if( wrflag ){
40083       assert( !pBt->pWriter );
40084       pBt->pWriter = p;
40085       pBt->isExclusive = (u8)(wrflag>1);
40086     }
40087 #endif
40088   }
40089
40090
40091 trans_begun:
40092   if( rc==SQLITE_OK && wrflag ){
40093     /* This call makes sure that the pager has the correct number of
40094     ** open savepoints. If the second parameter is greater than 0 and
40095     ** the sub-journal is not already open, then it will be opened here.
40096     */
40097     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
40098   }
40099
40100   btreeIntegrity(p);
40101   sqlite3BtreeLeave(p);
40102   return rc;
40103 }
40104
40105 #ifndef SQLITE_OMIT_AUTOVACUUM
40106
40107 /*
40108 ** Set the pointer-map entries for all children of page pPage. Also, if
40109 ** pPage contains cells that point to overflow pages, set the pointer
40110 ** map entries for the overflow pages as well.
40111 */
40112 static int setChildPtrmaps(MemPage *pPage){
40113   int i;                             /* Counter variable */
40114   int nCell;                         /* Number of cells in page pPage */
40115   int rc;                            /* Return code */
40116   BtShared *pBt = pPage->pBt;
40117   u8 isInitOrig = pPage->isInit;
40118   Pgno pgno = pPage->pgno;
40119
40120   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
40121   rc = btreeInitPage(pPage);
40122   if( rc!=SQLITE_OK ){
40123     goto set_child_ptrmaps_out;
40124   }
40125   nCell = pPage->nCell;
40126
40127   for(i=0; i<nCell; i++){
40128     u8 *pCell = findCell(pPage, i);
40129
40130     ptrmapPutOvflPtr(pPage, pCell, &rc);
40131
40132     if( !pPage->leaf ){
40133       Pgno childPgno = get4byte(pCell);
40134       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
40135     }
40136   }
40137
40138   if( !pPage->leaf ){
40139     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
40140     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
40141   }
40142
40143 set_child_ptrmaps_out:
40144   pPage->isInit = isInitOrig;
40145   return rc;
40146 }
40147
40148 /*
40149 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
40150 ** that it points to iTo. Parameter eType describes the type of pointer to
40151 ** be modified, as  follows:
40152 **
40153 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
40154 **                   page of pPage.
40155 **
40156 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
40157 **                   page pointed to by one of the cells on pPage.
40158 **
40159 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
40160 **                   overflow page in the list.
40161 */
40162 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
40163   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
40164   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
40165   if( eType==PTRMAP_OVERFLOW2 ){
40166     /* The pointer is always the first 4 bytes of the page in this case.  */
40167     if( get4byte(pPage->aData)!=iFrom ){
40168       return SQLITE_CORRUPT_BKPT;
40169     }
40170     put4byte(pPage->aData, iTo);
40171   }else{
40172     u8 isInitOrig = pPage->isInit;
40173     int i;
40174     int nCell;
40175
40176     btreeInitPage(pPage);
40177     nCell = pPage->nCell;
40178
40179     for(i=0; i<nCell; i++){
40180       u8 *pCell = findCell(pPage, i);
40181       if( eType==PTRMAP_OVERFLOW1 ){
40182         CellInfo info;
40183         btreeParseCellPtr(pPage, pCell, &info);
40184         if( info.iOverflow ){
40185           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
40186             put4byte(&pCell[info.iOverflow], iTo);
40187             break;
40188           }
40189         }
40190       }else{
40191         if( get4byte(pCell)==iFrom ){
40192           put4byte(pCell, iTo);
40193           break;
40194         }
40195       }
40196     }
40197   
40198     if( i==nCell ){
40199       if( eType!=PTRMAP_BTREE || 
40200           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
40201         return SQLITE_CORRUPT_BKPT;
40202       }
40203       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
40204     }
40205
40206     pPage->isInit = isInitOrig;
40207   }
40208   return SQLITE_OK;
40209 }
40210
40211
40212 /*
40213 ** Move the open database page pDbPage to location iFreePage in the 
40214 ** database. The pDbPage reference remains valid.
40215 **
40216 ** The isCommit flag indicates that there is no need to remember that
40217 ** the journal needs to be sync()ed before database page pDbPage->pgno 
40218 ** can be written to. The caller has already promised not to write to that
40219 ** page.
40220 */
40221 static int relocatePage(
40222   BtShared *pBt,           /* Btree */
40223   MemPage *pDbPage,        /* Open page to move */
40224   u8 eType,                /* Pointer map 'type' entry for pDbPage */
40225   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
40226   Pgno iFreePage,          /* The location to move pDbPage to */
40227   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
40228 ){
40229   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
40230   Pgno iDbPage = pDbPage->pgno;
40231   Pager *pPager = pBt->pPager;
40232   int rc;
40233
40234   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
40235       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
40236   assert( sqlite3_mutex_held(pBt->mutex) );
40237   assert( pDbPage->pBt==pBt );
40238
40239   /* Move page iDbPage from its current location to page number iFreePage */
40240   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
40241       iDbPage, iFreePage, iPtrPage, eType));
40242   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
40243   if( rc!=SQLITE_OK ){
40244     return rc;
40245   }
40246   pDbPage->pgno = iFreePage;
40247
40248   /* If pDbPage was a btree-page, then it may have child pages and/or cells
40249   ** that point to overflow pages. The pointer map entries for all these
40250   ** pages need to be changed.
40251   **
40252   ** If pDbPage is an overflow page, then the first 4 bytes may store a
40253   ** pointer to a subsequent overflow page. If this is the case, then
40254   ** the pointer map needs to be updated for the subsequent overflow page.
40255   */
40256   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
40257     rc = setChildPtrmaps(pDbPage);
40258     if( rc!=SQLITE_OK ){
40259       return rc;
40260     }
40261   }else{
40262     Pgno nextOvfl = get4byte(pDbPage->aData);
40263     if( nextOvfl!=0 ){
40264       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
40265       if( rc!=SQLITE_OK ){
40266         return rc;
40267       }
40268     }
40269   }
40270
40271   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
40272   ** that it points at iFreePage. Also fix the pointer map entry for
40273   ** iPtrPage.
40274   */
40275   if( eType!=PTRMAP_ROOTPAGE ){
40276     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
40277     if( rc!=SQLITE_OK ){
40278       return rc;
40279     }
40280     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
40281     if( rc!=SQLITE_OK ){
40282       releasePage(pPtrPage);
40283       return rc;
40284     }
40285     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
40286     releasePage(pPtrPage);
40287     if( rc==SQLITE_OK ){
40288       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
40289     }
40290   }
40291   return rc;
40292 }
40293
40294 /* Forward declaration required by incrVacuumStep(). */
40295 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
40296
40297 /*
40298 ** Perform a single step of an incremental-vacuum. If successful,
40299 ** return SQLITE_OK. If there is no work to do (and therefore no
40300 ** point in calling this function again), return SQLITE_DONE.
40301 **
40302 ** More specificly, this function attempts to re-organize the 
40303 ** database so that the last page of the file currently in use
40304 ** is no longer in use.
40305 **
40306 ** If the nFin parameter is non-zero, this function assumes
40307 ** that the caller will keep calling incrVacuumStep() until
40308 ** it returns SQLITE_DONE or an error, and that nFin is the
40309 ** number of pages the database file will contain after this 
40310 ** process is complete.  If nFin is zero, it is assumed that
40311 ** incrVacuumStep() will be called a finite amount of times
40312 ** which may or may not empty the freelist.  A full autovacuum
40313 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
40314 */
40315 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
40316   Pgno nFreeList;           /* Number of pages still on the free-list */
40317
40318   assert( sqlite3_mutex_held(pBt->mutex) );
40319   assert( iLastPg>nFin );
40320
40321   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
40322     int rc;
40323     u8 eType;
40324     Pgno iPtrPage;
40325
40326     nFreeList = get4byte(&pBt->pPage1->aData[36]);
40327     if( nFreeList==0 ){
40328       return SQLITE_DONE;
40329     }
40330
40331     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
40332     if( rc!=SQLITE_OK ){
40333       return rc;
40334     }
40335     if( eType==PTRMAP_ROOTPAGE ){
40336       return SQLITE_CORRUPT_BKPT;
40337     }
40338
40339     if( eType==PTRMAP_FREEPAGE ){
40340       if( nFin==0 ){
40341         /* Remove the page from the files free-list. This is not required
40342         ** if nFin is non-zero. In that case, the free-list will be
40343         ** truncated to zero after this function returns, so it doesn't 
40344         ** matter if it still contains some garbage entries.
40345         */
40346         Pgno iFreePg;
40347         MemPage *pFreePg;
40348         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
40349         if( rc!=SQLITE_OK ){
40350           return rc;
40351         }
40352         assert( iFreePg==iLastPg );
40353         releasePage(pFreePg);
40354       }
40355     } else {
40356       Pgno iFreePg;             /* Index of free page to move pLastPg to */
40357       MemPage *pLastPg;
40358
40359       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
40360       if( rc!=SQLITE_OK ){
40361         return rc;
40362       }
40363
40364       /* If nFin is zero, this loop runs exactly once and page pLastPg
40365       ** is swapped with the first free page pulled off the free list.
40366       **
40367       ** On the other hand, if nFin is greater than zero, then keep
40368       ** looping until a free-page located within the first nFin pages
40369       ** of the file is found.
40370       */
40371       do {
40372         MemPage *pFreePg;
40373         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
40374         if( rc!=SQLITE_OK ){
40375           releasePage(pLastPg);
40376           return rc;
40377         }
40378         releasePage(pFreePg);
40379       }while( nFin!=0 && iFreePg>nFin );
40380       assert( iFreePg<iLastPg );
40381       
40382       rc = sqlite3PagerWrite(pLastPg->pDbPage);
40383       if( rc==SQLITE_OK ){
40384         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
40385       }
40386       releasePage(pLastPg);
40387       if( rc!=SQLITE_OK ){
40388         return rc;
40389       }
40390     }
40391   }
40392
40393   if( nFin==0 ){
40394     iLastPg--;
40395     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
40396       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
40397         MemPage *pPg;
40398         int rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
40399         if( rc!=SQLITE_OK ){
40400           return rc;
40401         }
40402         rc = sqlite3PagerWrite(pPg->pDbPage);
40403         releasePage(pPg);
40404         if( rc!=SQLITE_OK ){
40405           return rc;
40406         }
40407       }
40408       iLastPg--;
40409     }
40410     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
40411   }
40412   return SQLITE_OK;
40413 }
40414
40415 /*
40416 ** A write-transaction must be opened before calling this function.
40417 ** It performs a single unit of work towards an incremental vacuum.
40418 **
40419 ** If the incremental vacuum is finished after this function has run,
40420 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
40421 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
40422 */
40423 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
40424   int rc;
40425   BtShared *pBt = p->pBt;
40426
40427   sqlite3BtreeEnter(p);
40428   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
40429   if( !pBt->autoVacuum ){
40430     rc = SQLITE_DONE;
40431   }else{
40432     invalidateAllOverflowCache(pBt);
40433     rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
40434   }
40435   sqlite3BtreeLeave(p);
40436   return rc;
40437 }
40438
40439 /*
40440 ** This routine is called prior to sqlite3PagerCommit when a transaction
40441 ** is commited for an auto-vacuum database.
40442 **
40443 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
40444 ** the database file should be truncated to during the commit process. 
40445 ** i.e. the database has been reorganized so that only the first *pnTrunc
40446 ** pages are in use.
40447 */
40448 static int autoVacuumCommit(BtShared *pBt){
40449   int rc = SQLITE_OK;
40450   Pager *pPager = pBt->pPager;
40451   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
40452
40453   assert( sqlite3_mutex_held(pBt->mutex) );
40454   invalidateAllOverflowCache(pBt);
40455   assert(pBt->autoVacuum);
40456   if( !pBt->incrVacuum ){
40457     Pgno nFin;         /* Number of pages in database after autovacuuming */
40458     Pgno nFree;        /* Number of pages on the freelist initially */
40459     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
40460     Pgno iFree;        /* The next page to be freed */
40461     int nEntry;        /* Number of entries on one ptrmap page */
40462     Pgno nOrig;        /* Database size before freeing */
40463
40464     nOrig = pagerPagecount(pBt);
40465     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
40466       /* It is not possible to create a database for which the final page
40467       ** is either a pointer-map page or the pending-byte page. If one
40468       ** is encountered, this indicates corruption.
40469       */
40470       return SQLITE_CORRUPT_BKPT;
40471     }
40472
40473     nFree = get4byte(&pBt->pPage1->aData[36]);
40474     nEntry = pBt->usableSize/5;
40475     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
40476     nFin = nOrig - nFree - nPtrmap;
40477     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
40478       nFin--;
40479     }
40480     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
40481       nFin--;
40482     }
40483     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
40484
40485     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
40486       rc = incrVacuumStep(pBt, nFin, iFree);
40487     }
40488     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
40489       rc = SQLITE_OK;
40490       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
40491       put4byte(&pBt->pPage1->aData[32], 0);
40492       put4byte(&pBt->pPage1->aData[36], 0);
40493       sqlite3PagerTruncateImage(pBt->pPager, nFin);
40494     }
40495     if( rc!=SQLITE_OK ){
40496       sqlite3PagerRollback(pPager);
40497     }
40498   }
40499
40500   assert( nRef==sqlite3PagerRefcount(pPager) );
40501   return rc;
40502 }
40503
40504 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
40505 # define setChildPtrmaps(x) SQLITE_OK
40506 #endif
40507
40508 /*
40509 ** This routine does the first phase of a two-phase commit.  This routine
40510 ** causes a rollback journal to be created (if it does not already exist)
40511 ** and populated with enough information so that if a power loss occurs
40512 ** the database can be restored to its original state by playing back
40513 ** the journal.  Then the contents of the journal are flushed out to
40514 ** the disk.  After the journal is safely on oxide, the changes to the
40515 ** database are written into the database file and flushed to oxide.
40516 ** At the end of this call, the rollback journal still exists on the
40517 ** disk and we are still holding all locks, so the transaction has not
40518 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
40519 ** commit process.
40520 **
40521 ** This call is a no-op if no write-transaction is currently active on pBt.
40522 **
40523 ** Otherwise, sync the database file for the btree pBt. zMaster points to
40524 ** the name of a master journal file that should be written into the
40525 ** individual journal file, or is NULL, indicating no master journal file 
40526 ** (single database transaction).
40527 **
40528 ** When this is called, the master journal should already have been
40529 ** created, populated with this journal pointer and synced to disk.
40530 **
40531 ** Once this is routine has returned, the only thing required to commit
40532 ** the write-transaction for this database file is to delete the journal.
40533 */
40534 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
40535   int rc = SQLITE_OK;
40536   if( p->inTrans==TRANS_WRITE ){
40537     BtShared *pBt = p->pBt;
40538     sqlite3BtreeEnter(p);
40539 #ifndef SQLITE_OMIT_AUTOVACUUM
40540     if( pBt->autoVacuum ){
40541       rc = autoVacuumCommit(pBt);
40542       if( rc!=SQLITE_OK ){
40543         sqlite3BtreeLeave(p);
40544         return rc;
40545       }
40546     }
40547 #endif
40548     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
40549     sqlite3BtreeLeave(p);
40550   }
40551   return rc;
40552 }
40553
40554 /*
40555 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
40556 ** at the conclusion of a transaction.
40557 */
40558 static void btreeEndTransaction(Btree *p){
40559   BtShared *pBt = p->pBt;
40560   assert( sqlite3BtreeHoldsMutex(p) );
40561
40562   btreeClearHasContent(pBt);
40563   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
40564     /* If there are other active statements that belong to this database
40565     ** handle, downgrade to a read-only transaction. The other statements
40566     ** may still be reading from the database.  */
40567     downgradeAllSharedCacheTableLocks(p);
40568     p->inTrans = TRANS_READ;
40569   }else{
40570     /* If the handle had any kind of transaction open, decrement the 
40571     ** transaction count of the shared btree. If the transaction count 
40572     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
40573     ** call below will unlock the pager.  */
40574     if( p->inTrans!=TRANS_NONE ){
40575       clearAllSharedCacheTableLocks(p);
40576       pBt->nTransaction--;
40577       if( 0==pBt->nTransaction ){
40578         pBt->inTransaction = TRANS_NONE;
40579       }
40580     }
40581
40582     /* Set the current transaction state to TRANS_NONE and unlock the 
40583     ** pager if this call closed the only read or write transaction.  */
40584     p->inTrans = TRANS_NONE;
40585     unlockBtreeIfUnused(pBt);
40586   }
40587
40588   btreeIntegrity(p);
40589 }
40590
40591 /*
40592 ** Commit the transaction currently in progress.
40593 **
40594 ** This routine implements the second phase of a 2-phase commit.  The
40595 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
40596 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
40597 ** routine did all the work of writing information out to disk and flushing the
40598 ** contents so that they are written onto the disk platter.  All this
40599 ** routine has to do is delete or truncate or zero the header in the
40600 ** the rollback journal (which causes the transaction to commit) and
40601 ** drop locks.
40602 **
40603 ** This will release the write lock on the database file.  If there
40604 ** are no active cursors, it also releases the read lock.
40605 */
40606 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
40607   BtShared *pBt = p->pBt;
40608
40609   sqlite3BtreeEnter(p);
40610   btreeIntegrity(p);
40611
40612   /* If the handle has a write-transaction open, commit the shared-btrees 
40613   ** transaction and set the shared state to TRANS_READ.
40614   */
40615   if( p->inTrans==TRANS_WRITE ){
40616     int rc;
40617     assert( pBt->inTransaction==TRANS_WRITE );
40618     assert( pBt->nTransaction>0 );
40619     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
40620     if( rc!=SQLITE_OK ){
40621       sqlite3BtreeLeave(p);
40622       return rc;
40623     }
40624     pBt->inTransaction = TRANS_READ;
40625   }
40626
40627   btreeEndTransaction(p);
40628   sqlite3BtreeLeave(p);
40629   return SQLITE_OK;
40630 }
40631
40632 /*
40633 ** Do both phases of a commit.
40634 */
40635 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
40636   int rc;
40637   sqlite3BtreeEnter(p);
40638   rc = sqlite3BtreeCommitPhaseOne(p, 0);
40639   if( rc==SQLITE_OK ){
40640     rc = sqlite3BtreeCommitPhaseTwo(p);
40641   }
40642   sqlite3BtreeLeave(p);
40643   return rc;
40644 }
40645
40646 #ifndef NDEBUG
40647 /*
40648 ** Return the number of write-cursors open on this handle. This is for use
40649 ** in assert() expressions, so it is only compiled if NDEBUG is not
40650 ** defined.
40651 **
40652 ** For the purposes of this routine, a write-cursor is any cursor that
40653 ** is capable of writing to the databse.  That means the cursor was
40654 ** originally opened for writing and the cursor has not be disabled
40655 ** by having its state changed to CURSOR_FAULT.
40656 */
40657 static int countWriteCursors(BtShared *pBt){
40658   BtCursor *pCur;
40659   int r = 0;
40660   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
40661     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
40662   }
40663   return r;
40664 }
40665 #endif
40666
40667 /*
40668 ** This routine sets the state to CURSOR_FAULT and the error
40669 ** code to errCode for every cursor on BtShared that pBtree
40670 ** references.
40671 **
40672 ** Every cursor is tripped, including cursors that belong
40673 ** to other database connections that happen to be sharing
40674 ** the cache with pBtree.
40675 **
40676 ** This routine gets called when a rollback occurs.
40677 ** All cursors using the same cache must be tripped
40678 ** to prevent them from trying to use the btree after
40679 ** the rollback.  The rollback may have deleted tables
40680 ** or moved root pages, so it is not sufficient to
40681 ** save the state of the cursor.  The cursor must be
40682 ** invalidated.
40683 */
40684 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
40685   BtCursor *p;
40686   sqlite3BtreeEnter(pBtree);
40687   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
40688     int i;
40689     sqlite3BtreeClearCursor(p);
40690     p->eState = CURSOR_FAULT;
40691     p->skipNext = errCode;
40692     for(i=0; i<=p->iPage; i++){
40693       releasePage(p->apPage[i]);
40694       p->apPage[i] = 0;
40695     }
40696   }
40697   sqlite3BtreeLeave(pBtree);
40698 }
40699
40700 /*
40701 ** Rollback the transaction in progress.  All cursors will be
40702 ** invalided by this operation.  Any attempt to use a cursor
40703 ** that was open at the beginning of this operation will result
40704 ** in an error.
40705 **
40706 ** This will release the write lock on the database file.  If there
40707 ** are no active cursors, it also releases the read lock.
40708 */
40709 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
40710   int rc;
40711   BtShared *pBt = p->pBt;
40712   MemPage *pPage1;
40713
40714   sqlite3BtreeEnter(p);
40715   rc = saveAllCursors(pBt, 0, 0);
40716 #ifndef SQLITE_OMIT_SHARED_CACHE
40717   if( rc!=SQLITE_OK ){
40718     /* This is a horrible situation. An IO or malloc() error occurred whilst
40719     ** trying to save cursor positions. If this is an automatic rollback (as
40720     ** the result of a constraint, malloc() failure or IO error) then 
40721     ** the cache may be internally inconsistent (not contain valid trees) so
40722     ** we cannot simply return the error to the caller. Instead, abort 
40723     ** all queries that may be using any of the cursors that failed to save.
40724     */
40725     sqlite3BtreeTripAllCursors(p, rc);
40726   }
40727 #endif
40728   btreeIntegrity(p);
40729
40730   if( p->inTrans==TRANS_WRITE ){
40731     int rc2;
40732
40733     assert( TRANS_WRITE==pBt->inTransaction );
40734     rc2 = sqlite3PagerRollback(pBt->pPager);
40735     if( rc2!=SQLITE_OK ){
40736       rc = rc2;
40737     }
40738
40739     /* The rollback may have destroyed the pPage1->aData value.  So
40740     ** call btreeGetPage() on page 1 again to make
40741     ** sure pPage1->aData is set correctly. */
40742     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
40743       releasePage(pPage1);
40744     }
40745     assert( countWriteCursors(pBt)==0 );
40746     pBt->inTransaction = TRANS_READ;
40747   }
40748
40749   btreeEndTransaction(p);
40750   sqlite3BtreeLeave(p);
40751   return rc;
40752 }
40753
40754 /*
40755 ** Start a statement subtransaction. The subtransaction can can be rolled
40756 ** back independently of the main transaction. You must start a transaction 
40757 ** before starting a subtransaction. The subtransaction is ended automatically 
40758 ** if the main transaction commits or rolls back.
40759 **
40760 ** Statement subtransactions are used around individual SQL statements
40761 ** that are contained within a BEGIN...COMMIT block.  If a constraint
40762 ** error occurs within the statement, the effect of that one statement
40763 ** can be rolled back without having to rollback the entire transaction.
40764 **
40765 ** A statement sub-transaction is implemented as an anonymous savepoint. The
40766 ** value passed as the second parameter is the total number of savepoints,
40767 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
40768 ** are no active savepoints and no other statement-transactions open,
40769 ** iStatement is 1. This anonymous savepoint can be released or rolled back
40770 ** using the sqlite3BtreeSavepoint() function.
40771 */
40772 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
40773   int rc;
40774   BtShared *pBt = p->pBt;
40775   sqlite3BtreeEnter(p);
40776   assert( p->inTrans==TRANS_WRITE );
40777   assert( pBt->readOnly==0 );
40778   assert( iStatement>0 );
40779   assert( iStatement>p->db->nSavepoint );
40780   if( NEVER(p->inTrans!=TRANS_WRITE || pBt->readOnly) ){
40781     rc = SQLITE_INTERNAL;
40782   }else{
40783     assert( pBt->inTransaction==TRANS_WRITE );
40784     /* At the pager level, a statement transaction is a savepoint with
40785     ** an index greater than all savepoints created explicitly using
40786     ** SQL statements. It is illegal to open, release or rollback any
40787     ** such savepoints while the statement transaction savepoint is active.
40788     */
40789     rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
40790   }
40791   sqlite3BtreeLeave(p);
40792   return rc;
40793 }
40794
40795 /*
40796 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
40797 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
40798 ** savepoint identified by parameter iSavepoint, depending on the value 
40799 ** of op.
40800 **
40801 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
40802 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
40803 ** contents of the entire transaction are rolled back. This is different
40804 ** from a normal transaction rollback, as no locks are released and the
40805 ** transaction remains open.
40806 */
40807 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
40808   int rc = SQLITE_OK;
40809   if( p && p->inTrans==TRANS_WRITE ){
40810     BtShared *pBt = p->pBt;
40811     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
40812     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
40813     sqlite3BtreeEnter(p);
40814     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
40815     if( rc==SQLITE_OK ){
40816       rc = newDatabase(pBt);
40817     }
40818     sqlite3BtreeLeave(p);
40819   }
40820   return rc;
40821 }
40822
40823 /*
40824 ** Create a new cursor for the BTree whose root is on the page
40825 ** iTable. If a read-only cursor is requested, it is assumed that
40826 ** the caller already has at least a read-only transaction open
40827 ** on the database already. If a write-cursor is requested, then
40828 ** the caller is assumed to have an open write transaction.
40829 **
40830 ** If wrFlag==0, then the cursor can only be used for reading.
40831 ** If wrFlag==1, then the cursor can be used for reading or for
40832 ** writing if other conditions for writing are also met.  These
40833 ** are the conditions that must be met in order for writing to
40834 ** be allowed:
40835 **
40836 ** 1:  The cursor must have been opened with wrFlag==1
40837 **
40838 ** 2:  Other database connections that share the same pager cache
40839 **     but which are not in the READ_UNCOMMITTED state may not have
40840 **     cursors open with wrFlag==0 on the same table.  Otherwise
40841 **     the changes made by this write cursor would be visible to
40842 **     the read cursors in the other database connection.
40843 **
40844 ** 3:  The database must be writable (not on read-only media)
40845 **
40846 ** 4:  There must be an active transaction.
40847 **
40848 ** No checking is done to make sure that page iTable really is the
40849 ** root page of a b-tree.  If it is not, then the cursor acquired
40850 ** will not work correctly.
40851 **
40852 ** It is assumed that the sqlite3BtreeCursorZero() has been called
40853 ** on pCur to initialize the memory space prior to invoking this routine.
40854 */
40855 static int btreeCursor(
40856   Btree *p,                              /* The btree */
40857   int iTable,                            /* Root page of table to open */
40858   int wrFlag,                            /* 1 to write. 0 read-only */
40859   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
40860   BtCursor *pCur                         /* Space for new cursor */
40861 ){
40862   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
40863
40864   assert( sqlite3BtreeHoldsMutex(p) );
40865   assert( wrFlag==0 || wrFlag==1 );
40866
40867   /* The following assert statements verify that if this is a sharable 
40868   ** b-tree database, the connection is holding the required table locks, 
40869   ** and that no other connection has any open cursor that conflicts with 
40870   ** this lock.  */
40871   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
40872   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
40873
40874   /* Assert that the caller has opened the required transaction. */
40875   assert( p->inTrans>TRANS_NONE );
40876   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
40877   assert( pBt->pPage1 && pBt->pPage1->aData );
40878
40879   if( NEVER(wrFlag && pBt->readOnly) ){
40880     return SQLITE_READONLY;
40881   }
40882   if( iTable==1 && pagerPagecount(pBt)==0 ){
40883     return SQLITE_EMPTY;
40884   }
40885
40886   /* Now that no other errors can occur, finish filling in the BtCursor
40887   ** variables and link the cursor into the BtShared list.  */
40888   pCur->pgnoRoot = (Pgno)iTable;
40889   pCur->iPage = -1;
40890   pCur->pKeyInfo = pKeyInfo;
40891   pCur->pBtree = p;
40892   pCur->pBt = pBt;
40893   pCur->wrFlag = (u8)wrFlag;
40894   pCur->pNext = pBt->pCursor;
40895   if( pCur->pNext ){
40896     pCur->pNext->pPrev = pCur;
40897   }
40898   pBt->pCursor = pCur;
40899   pCur->eState = CURSOR_INVALID;
40900   pCur->cachedRowid = 0;
40901   return SQLITE_OK;
40902 }
40903 SQLITE_PRIVATE int sqlite3BtreeCursor(
40904   Btree *p,                                   /* The btree */
40905   int iTable,                                 /* Root page of table to open */
40906   int wrFlag,                                 /* 1 to write. 0 read-only */
40907   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
40908   BtCursor *pCur                              /* Write new cursor here */
40909 ){
40910   int rc;
40911   sqlite3BtreeEnter(p);
40912   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
40913   sqlite3BtreeLeave(p);
40914   return rc;
40915 }
40916
40917 /*
40918 ** Return the size of a BtCursor object in bytes.
40919 **
40920 ** This interfaces is needed so that users of cursors can preallocate
40921 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
40922 ** to users so they cannot do the sizeof() themselves - they must call
40923 ** this routine.
40924 */
40925 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
40926   return ROUND8(sizeof(BtCursor));
40927 }
40928
40929 /*
40930 ** Initialize memory that will be converted into a BtCursor object.
40931 **
40932 ** The simple approach here would be to memset() the entire object
40933 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
40934 ** do not need to be zeroed and they are large, so we can save a lot
40935 ** of run-time by skipping the initialization of those elements.
40936 */
40937 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
40938   memset(p, 0, offsetof(BtCursor, iPage));
40939 }
40940
40941 /*
40942 ** Set the cached rowid value of every cursor in the same database file
40943 ** as pCur and having the same root page number as pCur.  The value is
40944 ** set to iRowid.
40945 **
40946 ** Only positive rowid values are considered valid for this cache.
40947 ** The cache is initialized to zero, indicating an invalid cache.
40948 ** A btree will work fine with zero or negative rowids.  We just cannot
40949 ** cache zero or negative rowids, which means tables that use zero or
40950 ** negative rowids might run a little slower.  But in practice, zero
40951 ** or negative rowids are very uncommon so this should not be a problem.
40952 */
40953 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
40954   BtCursor *p;
40955   for(p=pCur->pBt->pCursor; p; p=p->pNext){
40956     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
40957   }
40958   assert( pCur->cachedRowid==iRowid );
40959 }
40960
40961 /*
40962 ** Return the cached rowid for the given cursor.  A negative or zero
40963 ** return value indicates that the rowid cache is invalid and should be
40964 ** ignored.  If the rowid cache has never before been set, then a
40965 ** zero is returned.
40966 */
40967 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
40968   return pCur->cachedRowid;
40969 }
40970
40971 /*
40972 ** Close a cursor.  The read lock on the database file is released
40973 ** when the last cursor is closed.
40974 */
40975 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
40976   Btree *pBtree = pCur->pBtree;
40977   if( pBtree ){
40978     int i;
40979     BtShared *pBt = pCur->pBt;
40980     sqlite3BtreeEnter(pBtree);
40981     sqlite3BtreeClearCursor(pCur);
40982     if( pCur->pPrev ){
40983       pCur->pPrev->pNext = pCur->pNext;
40984     }else{
40985       pBt->pCursor = pCur->pNext;
40986     }
40987     if( pCur->pNext ){
40988       pCur->pNext->pPrev = pCur->pPrev;
40989     }
40990     for(i=0; i<=pCur->iPage; i++){
40991       releasePage(pCur->apPage[i]);
40992     }
40993     unlockBtreeIfUnused(pBt);
40994     invalidateOverflowCache(pCur);
40995     /* sqlite3_free(pCur); */
40996     sqlite3BtreeLeave(pBtree);
40997   }
40998   return SQLITE_OK;
40999 }
41000
41001 /*
41002 ** Make sure the BtCursor* given in the argument has a valid
41003 ** BtCursor.info structure.  If it is not already valid, call
41004 ** btreeParseCell() to fill it in.
41005 **
41006 ** BtCursor.info is a cache of the information in the current cell.
41007 ** Using this cache reduces the number of calls to btreeParseCell().
41008 **
41009 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
41010 ** compiler to crash when getCellInfo() is implemented as a macro.
41011 ** But there is a measureable speed advantage to using the macro on gcc
41012 ** (when less compiler optimizations like -Os or -O0 are used and the
41013 ** compiler is not doing agressive inlining.)  So we use a real function
41014 ** for MSVC and a macro for everything else.  Ticket #2457.
41015 */
41016 #ifndef NDEBUG
41017   static void assertCellInfo(BtCursor *pCur){
41018     CellInfo info;
41019     int iPage = pCur->iPage;
41020     memset(&info, 0, sizeof(info));
41021     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
41022     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
41023   }
41024 #else
41025   #define assertCellInfo(x)
41026 #endif
41027 #ifdef _MSC_VER
41028   /* Use a real function in MSVC to work around bugs in that compiler. */
41029   static void getCellInfo(BtCursor *pCur){
41030     if( pCur->info.nSize==0 ){
41031       int iPage = pCur->iPage;
41032       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
41033       pCur->validNKey = 1;
41034     }else{
41035       assertCellInfo(pCur);
41036     }
41037   }
41038 #else /* if not _MSC_VER */
41039   /* Use a macro in all other compilers so that the function is inlined */
41040 #define getCellInfo(pCur)                                                      \
41041   if( pCur->info.nSize==0 ){                                                   \
41042     int iPage = pCur->iPage;                                                   \
41043     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
41044     pCur->validNKey = 1;                                                       \
41045   }else{                                                                       \
41046     assertCellInfo(pCur);                                                      \
41047   }
41048 #endif /* _MSC_VER */
41049
41050 #ifndef NDEBUG  /* The next routine used only within assert() statements */
41051 /*
41052 ** Return true if the given BtCursor is valid.  A valid cursor is one
41053 ** that is currently pointing to a row in a (non-empty) table.
41054 ** This is a verification routine is used only within assert() statements.
41055 */
41056 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
41057   return pCur && pCur->eState==CURSOR_VALID;
41058 }
41059 #endif /* NDEBUG */
41060
41061 /*
41062 ** Set *pSize to the size of the buffer needed to hold the value of
41063 ** the key for the current entry.  If the cursor is not pointing
41064 ** to a valid entry, *pSize is set to 0. 
41065 **
41066 ** For a table with the INTKEY flag set, this routine returns the key
41067 ** itself, not the number of bytes in the key.
41068 **
41069 ** The caller must position the cursor prior to invoking this routine.
41070 ** 
41071 ** This routine cannot fail.  It always returns SQLITE_OK.  
41072 */
41073 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
41074   assert( cursorHoldsMutex(pCur) );
41075   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
41076   if( pCur->eState!=CURSOR_VALID ){
41077     *pSize = 0;
41078   }else{
41079     getCellInfo(pCur);
41080     *pSize = pCur->info.nKey;
41081   }
41082   return SQLITE_OK;
41083 }
41084
41085 /*
41086 ** Set *pSize to the number of bytes of data in the entry the
41087 ** cursor currently points to.
41088 **
41089 ** The caller must guarantee that the cursor is pointing to a non-NULL
41090 ** valid entry.  In other words, the calling procedure must guarantee
41091 ** that the cursor has Cursor.eState==CURSOR_VALID.
41092 **
41093 ** Failure is not possible.  This function always returns SQLITE_OK.
41094 ** It might just as well be a procedure (returning void) but we continue
41095 ** to return an integer result code for historical reasons.
41096 */
41097 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
41098   assert( cursorHoldsMutex(pCur) );
41099   assert( pCur->eState==CURSOR_VALID );
41100   getCellInfo(pCur);
41101   *pSize = pCur->info.nData;
41102   return SQLITE_OK;
41103 }
41104
41105 /*
41106 ** Given the page number of an overflow page in the database (parameter
41107 ** ovfl), this function finds the page number of the next page in the 
41108 ** linked list of overflow pages. If possible, it uses the auto-vacuum
41109 ** pointer-map data instead of reading the content of page ovfl to do so. 
41110 **
41111 ** If an error occurs an SQLite error code is returned. Otherwise:
41112 **
41113 ** The page number of the next overflow page in the linked list is 
41114 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
41115 ** list, *pPgnoNext is set to zero. 
41116 **
41117 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
41118 ** to page number pOvfl was obtained, then *ppPage is set to point to that
41119 ** reference. It is the responsibility of the caller to call releasePage()
41120 ** on *ppPage to free the reference. In no reference was obtained (because
41121 ** the pointer-map was used to obtain the value for *pPgnoNext), then
41122 ** *ppPage is set to zero.
41123 */
41124 static int getOverflowPage(
41125   BtShared *pBt,               /* The database file */
41126   Pgno ovfl,                   /* Current overflow page number */
41127   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
41128   Pgno *pPgnoNext              /* OUT: Next overflow page number */
41129 ){
41130   Pgno next = 0;
41131   MemPage *pPage = 0;
41132   int rc = SQLITE_OK;
41133
41134   assert( sqlite3_mutex_held(pBt->mutex) );
41135   assert(pPgnoNext);
41136
41137 #ifndef SQLITE_OMIT_AUTOVACUUM
41138   /* Try to find the next page in the overflow list using the
41139   ** autovacuum pointer-map pages. Guess that the next page in 
41140   ** the overflow list is page number (ovfl+1). If that guess turns 
41141   ** out to be wrong, fall back to loading the data of page 
41142   ** number ovfl to determine the next page number.
41143   */
41144   if( pBt->autoVacuum ){
41145     Pgno pgno;
41146     Pgno iGuess = ovfl+1;
41147     u8 eType;
41148
41149     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
41150       iGuess++;
41151     }
41152
41153     if( iGuess<=pagerPagecount(pBt) ){
41154       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
41155       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
41156         next = iGuess;
41157         rc = SQLITE_DONE;
41158       }
41159     }
41160   }
41161 #endif
41162
41163   assert( next==0 || rc==SQLITE_DONE );
41164   if( rc==SQLITE_OK ){
41165     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
41166     assert( rc==SQLITE_OK || pPage==0 );
41167     if( rc==SQLITE_OK ){
41168       next = get4byte(pPage->aData);
41169     }
41170   }
41171
41172   *pPgnoNext = next;
41173   if( ppPage ){
41174     *ppPage = pPage;
41175   }else{
41176     releasePage(pPage);
41177   }
41178   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
41179 }
41180
41181 /*
41182 ** Copy data from a buffer to a page, or from a page to a buffer.
41183 **
41184 ** pPayload is a pointer to data stored on database page pDbPage.
41185 ** If argument eOp is false, then nByte bytes of data are copied
41186 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
41187 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
41188 ** of data are copied from the buffer pBuf to pPayload.
41189 **
41190 ** SQLITE_OK is returned on success, otherwise an error code.
41191 */
41192 static int copyPayload(
41193   void *pPayload,           /* Pointer to page data */
41194   void *pBuf,               /* Pointer to buffer */
41195   int nByte,                /* Number of bytes to copy */
41196   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
41197   DbPage *pDbPage           /* Page containing pPayload */
41198 ){
41199   if( eOp ){
41200     /* Copy data from buffer to page (a write operation) */
41201     int rc = sqlite3PagerWrite(pDbPage);
41202     if( rc!=SQLITE_OK ){
41203       return rc;
41204     }
41205     memcpy(pPayload, pBuf, nByte);
41206   }else{
41207     /* Copy data from page to buffer (a read operation) */
41208     memcpy(pBuf, pPayload, nByte);
41209   }
41210   return SQLITE_OK;
41211 }
41212
41213 /*
41214 ** This function is used to read or overwrite payload information
41215 ** for the entry that the pCur cursor is pointing to. If the eOp
41216 ** parameter is 0, this is a read operation (data copied into
41217 ** buffer pBuf). If it is non-zero, a write (data copied from
41218 ** buffer pBuf).
41219 **
41220 ** A total of "amt" bytes are read or written beginning at "offset".
41221 ** Data is read to or from the buffer pBuf.
41222 **
41223 ** The content being read or written might appear on the main page
41224 ** or be scattered out on multiple overflow pages.
41225 **
41226 ** If the BtCursor.isIncrblobHandle flag is set, and the current
41227 ** cursor entry uses one or more overflow pages, this function
41228 ** allocates space for and lazily popluates the overflow page-list 
41229 ** cache array (BtCursor.aOverflow). Subsequent calls use this
41230 ** cache to make seeking to the supplied offset more efficient.
41231 **
41232 ** Once an overflow page-list cache has been allocated, it may be
41233 ** invalidated if some other cursor writes to the same table, or if
41234 ** the cursor is moved to a different row. Additionally, in auto-vacuum
41235 ** mode, the following events may invalidate an overflow page-list cache.
41236 **
41237 **   * An incremental vacuum,
41238 **   * A commit in auto_vacuum="full" mode,
41239 **   * Creating a table (may require moving an overflow page).
41240 */
41241 static int accessPayload(
41242   BtCursor *pCur,      /* Cursor pointing to entry to read from */
41243   u32 offset,          /* Begin reading this far into payload */
41244   u32 amt,             /* Read this many bytes */
41245   unsigned char *pBuf, /* Write the bytes into this buffer */ 
41246   int eOp              /* zero to read. non-zero to write. */
41247 ){
41248   unsigned char *aPayload;
41249   int rc = SQLITE_OK;
41250   u32 nKey;
41251   int iIdx = 0;
41252   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
41253   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
41254
41255   assert( pPage );
41256   assert( pCur->eState==CURSOR_VALID );
41257   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
41258   assert( cursorHoldsMutex(pCur) );
41259
41260   getCellInfo(pCur);
41261   aPayload = pCur->info.pCell + pCur->info.nHeader;
41262   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
41263
41264   if( NEVER(offset+amt > nKey+pCur->info.nData) 
41265    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
41266   ){
41267     /* Trying to read or write past the end of the data is an error */
41268     return SQLITE_CORRUPT_BKPT;
41269   }
41270
41271   /* Check if data must be read/written to/from the btree page itself. */
41272   if( offset<pCur->info.nLocal ){
41273     int a = amt;
41274     if( a+offset>pCur->info.nLocal ){
41275       a = pCur->info.nLocal - offset;
41276     }
41277     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
41278     offset = 0;
41279     pBuf += a;
41280     amt -= a;
41281   }else{
41282     offset -= pCur->info.nLocal;
41283   }
41284
41285   if( rc==SQLITE_OK && amt>0 ){
41286     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
41287     Pgno nextPage;
41288
41289     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
41290
41291 #ifndef SQLITE_OMIT_INCRBLOB
41292     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
41293     ** has not been allocated, allocate it now. The array is sized at
41294     ** one entry for each overflow page in the overflow chain. The
41295     ** page number of the first overflow page is stored in aOverflow[0],
41296     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
41297     ** (the cache is lazily populated).
41298     */
41299     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
41300       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
41301       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
41302       /* nOvfl is always positive.  If it were zero, fetchPayload would have
41303       ** been used instead of this routine. */
41304       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
41305         rc = SQLITE_NOMEM;
41306       }
41307     }
41308
41309     /* If the overflow page-list cache has been allocated and the
41310     ** entry for the first required overflow page is valid, skip
41311     ** directly to it.
41312     */
41313     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
41314       iIdx = (offset/ovflSize);
41315       nextPage = pCur->aOverflow[iIdx];
41316       offset = (offset%ovflSize);
41317     }
41318 #endif
41319
41320     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
41321
41322 #ifndef SQLITE_OMIT_INCRBLOB
41323       /* If required, populate the overflow page-list cache. */
41324       if( pCur->aOverflow ){
41325         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
41326         pCur->aOverflow[iIdx] = nextPage;
41327       }
41328 #endif
41329
41330       if( offset>=ovflSize ){
41331         /* The only reason to read this page is to obtain the page
41332         ** number for the next page in the overflow chain. The page
41333         ** data is not required. So first try to lookup the overflow
41334         ** page-list cache, if any, then fall back to the getOverflowPage()
41335         ** function.
41336         */
41337 #ifndef SQLITE_OMIT_INCRBLOB
41338         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
41339           nextPage = pCur->aOverflow[iIdx+1];
41340         } else 
41341 #endif
41342           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
41343         offset -= ovflSize;
41344       }else{
41345         /* Need to read this page properly. It contains some of the
41346         ** range of data that is being read (eOp==0) or written (eOp!=0).
41347         */
41348         DbPage *pDbPage;
41349         int a = amt;
41350         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
41351         if( rc==SQLITE_OK ){
41352           aPayload = sqlite3PagerGetData(pDbPage);
41353           nextPage = get4byte(aPayload);
41354           if( a + offset > ovflSize ){
41355             a = ovflSize - offset;
41356           }
41357           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
41358           sqlite3PagerUnref(pDbPage);
41359           offset = 0;
41360           amt -= a;
41361           pBuf += a;
41362         }
41363       }
41364     }
41365   }
41366
41367   if( rc==SQLITE_OK && amt>0 ){
41368     return SQLITE_CORRUPT_BKPT;
41369   }
41370   return rc;
41371 }
41372
41373 /*
41374 ** Read part of the key associated with cursor pCur.  Exactly
41375 ** "amt" bytes will be transfered into pBuf[].  The transfer
41376 ** begins at "offset".
41377 **
41378 ** The caller must ensure that pCur is pointing to a valid row
41379 ** in the table.
41380 **
41381 ** Return SQLITE_OK on success or an error code if anything goes
41382 ** wrong.  An error is returned if "offset+amt" is larger than
41383 ** the available payload.
41384 */
41385 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
41386   assert( cursorHoldsMutex(pCur) );
41387   assert( pCur->eState==CURSOR_VALID );
41388   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
41389   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
41390   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
41391 }
41392
41393 /*
41394 ** Read part of the data associated with cursor pCur.  Exactly
41395 ** "amt" bytes will be transfered into pBuf[].  The transfer
41396 ** begins at "offset".
41397 **
41398 ** Return SQLITE_OK on success or an error code if anything goes
41399 ** wrong.  An error is returned if "offset+amt" is larger than
41400 ** the available payload.
41401 */
41402 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
41403   int rc;
41404
41405 #ifndef SQLITE_OMIT_INCRBLOB
41406   if ( pCur->eState==CURSOR_INVALID ){
41407     return SQLITE_ABORT;
41408   }
41409 #endif
41410
41411   assert( cursorHoldsMutex(pCur) );
41412   rc = restoreCursorPosition(pCur);
41413   if( rc==SQLITE_OK ){
41414     assert( pCur->eState==CURSOR_VALID );
41415     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
41416     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
41417     rc = accessPayload(pCur, offset, amt, pBuf, 0);
41418   }
41419   return rc;
41420 }
41421
41422 /*
41423 ** Return a pointer to payload information from the entry that the 
41424 ** pCur cursor is pointing to.  The pointer is to the beginning of
41425 ** the key if skipKey==0 and it points to the beginning of data if
41426 ** skipKey==1.  The number of bytes of available key/data is written
41427 ** into *pAmt.  If *pAmt==0, then the value returned will not be
41428 ** a valid pointer.
41429 **
41430 ** This routine is an optimization.  It is common for the entire key
41431 ** and data to fit on the local page and for there to be no overflow
41432 ** pages.  When that is so, this routine can be used to access the
41433 ** key and data without making a copy.  If the key and/or data spills
41434 ** onto overflow pages, then accessPayload() must be used to reassemble
41435 ** the key/data and copy it into a preallocated buffer.
41436 **
41437 ** The pointer returned by this routine looks directly into the cached
41438 ** page of the database.  The data might change or move the next time
41439 ** any btree routine is called.
41440 */
41441 static const unsigned char *fetchPayload(
41442   BtCursor *pCur,      /* Cursor pointing to entry to read from */
41443   int *pAmt,           /* Write the number of available bytes here */
41444   int skipKey          /* read beginning at data if this is true */
41445 ){
41446   unsigned char *aPayload;
41447   MemPage *pPage;
41448   u32 nKey;
41449   u32 nLocal;
41450
41451   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
41452   assert( pCur->eState==CURSOR_VALID );
41453   assert( cursorHoldsMutex(pCur) );
41454   pPage = pCur->apPage[pCur->iPage];
41455   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
41456   if( NEVER(pCur->info.nSize==0) ){
41457     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
41458                    &pCur->info);
41459   }
41460   aPayload = pCur->info.pCell;
41461   aPayload += pCur->info.nHeader;
41462   if( pPage->intKey ){
41463     nKey = 0;
41464   }else{
41465     nKey = (int)pCur->info.nKey;
41466   }
41467   if( skipKey ){
41468     aPayload += nKey;
41469     nLocal = pCur->info.nLocal - nKey;
41470   }else{
41471     nLocal = pCur->info.nLocal;
41472     assert( nLocal<=nKey );
41473   }
41474   *pAmt = nLocal;
41475   return aPayload;
41476 }
41477
41478
41479 /*
41480 ** For the entry that cursor pCur is point to, return as
41481 ** many bytes of the key or data as are available on the local
41482 ** b-tree page.  Write the number of available bytes into *pAmt.
41483 **
41484 ** The pointer returned is ephemeral.  The key/data may move
41485 ** or be destroyed on the next call to any Btree routine,
41486 ** including calls from other threads against the same cache.
41487 ** Hence, a mutex on the BtShared should be held prior to calling
41488 ** this routine.
41489 **
41490 ** These routines is used to get quick access to key and data
41491 ** in the common case where no overflow pages are used.
41492 */
41493 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
41494   const void *p = 0;
41495   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41496   assert( cursorHoldsMutex(pCur) );
41497   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
41498     p = (const void*)fetchPayload(pCur, pAmt, 0);
41499   }
41500   return p;
41501 }
41502 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
41503   const void *p = 0;
41504   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41505   assert( cursorHoldsMutex(pCur) );
41506   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
41507     p = (const void*)fetchPayload(pCur, pAmt, 1);
41508   }
41509   return p;
41510 }
41511
41512
41513 /*
41514 ** Move the cursor down to a new child page.  The newPgno argument is the
41515 ** page number of the child page to move to.
41516 **
41517 ** This function returns SQLITE_CORRUPT if the page-header flags field of
41518 ** the new child page does not match the flags field of the parent (i.e.
41519 ** if an intkey page appears to be the parent of a non-intkey page, or
41520 ** vice-versa).
41521 */
41522 static int moveToChild(BtCursor *pCur, u32 newPgno){
41523   int rc;
41524   int i = pCur->iPage;
41525   MemPage *pNewPage;
41526   BtShared *pBt = pCur->pBt;
41527
41528   assert( cursorHoldsMutex(pCur) );
41529   assert( pCur->eState==CURSOR_VALID );
41530   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
41531   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
41532     return SQLITE_CORRUPT_BKPT;
41533   }
41534   rc = getAndInitPage(pBt, newPgno, &pNewPage);
41535   if( rc ) return rc;
41536   pCur->apPage[i+1] = pNewPage;
41537   pCur->aiIdx[i+1] = 0;
41538   pCur->iPage++;
41539
41540   pCur->info.nSize = 0;
41541   pCur->validNKey = 0;
41542   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
41543     return SQLITE_CORRUPT_BKPT;
41544   }
41545   return SQLITE_OK;
41546 }
41547
41548 #ifndef NDEBUG
41549 /*
41550 ** Page pParent is an internal (non-leaf) tree page. This function 
41551 ** asserts that page number iChild is the left-child if the iIdx'th
41552 ** cell in page pParent. Or, if iIdx is equal to the total number of
41553 ** cells in pParent, that page number iChild is the right-child of
41554 ** the page.
41555 */
41556 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
41557   assert( iIdx<=pParent->nCell );
41558   if( iIdx==pParent->nCell ){
41559     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
41560   }else{
41561     assert( get4byte(findCell(pParent, iIdx))==iChild );
41562   }
41563 }
41564 #else
41565 #  define assertParentIndex(x,y,z) 
41566 #endif
41567
41568 /*
41569 ** Move the cursor up to the parent page.
41570 **
41571 ** pCur->idx is set to the cell index that contains the pointer
41572 ** to the page we are coming from.  If we are coming from the
41573 ** right-most child page then pCur->idx is set to one more than
41574 ** the largest cell index.
41575 */
41576 static void moveToParent(BtCursor *pCur){
41577   assert( cursorHoldsMutex(pCur) );
41578   assert( pCur->eState==CURSOR_VALID );
41579   assert( pCur->iPage>0 );
41580   assert( pCur->apPage[pCur->iPage] );
41581   assertParentIndex(
41582     pCur->apPage[pCur->iPage-1], 
41583     pCur->aiIdx[pCur->iPage-1], 
41584     pCur->apPage[pCur->iPage]->pgno
41585   );
41586   releasePage(pCur->apPage[pCur->iPage]);
41587   pCur->iPage--;
41588   pCur->info.nSize = 0;
41589   pCur->validNKey = 0;
41590 }
41591
41592 /*
41593 ** Move the cursor to point to the root page of its b-tree structure.
41594 **
41595 ** If the table has a virtual root page, then the cursor is moved to point
41596 ** to the virtual root page instead of the actual root page. A table has a
41597 ** virtual root page when the actual root page contains no cells and a 
41598 ** single child page. This can only happen with the table rooted at page 1.
41599 **
41600 ** If the b-tree structure is empty, the cursor state is set to 
41601 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
41602 ** cell located on the root (or virtual root) page and the cursor state
41603 ** is set to CURSOR_VALID.
41604 **
41605 ** If this function returns successfully, it may be assumed that the
41606 ** page-header flags indicate that the [virtual] root-page is the expected 
41607 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
41608 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
41609 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
41610 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
41611 ** b-tree).
41612 */
41613 static int moveToRoot(BtCursor *pCur){
41614   MemPage *pRoot;
41615   int rc = SQLITE_OK;
41616   Btree *p = pCur->pBtree;
41617   BtShared *pBt = p->pBt;
41618
41619   assert( cursorHoldsMutex(pCur) );
41620   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
41621   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
41622   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
41623   if( pCur->eState>=CURSOR_REQUIRESEEK ){
41624     if( pCur->eState==CURSOR_FAULT ){
41625       assert( pCur->skipNext!=SQLITE_OK );
41626       return pCur->skipNext;
41627     }
41628     sqlite3BtreeClearCursor(pCur);
41629   }
41630
41631   if( pCur->iPage>=0 ){
41632     int i;
41633     for(i=1; i<=pCur->iPage; i++){
41634       releasePage(pCur->apPage[i]);
41635     }
41636     pCur->iPage = 0;
41637   }else{
41638     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
41639     if( rc!=SQLITE_OK ){
41640       pCur->eState = CURSOR_INVALID;
41641       return rc;
41642     }
41643     pCur->iPage = 0;
41644
41645     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
41646     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
41647     ** NULL, the caller expects a table b-tree. If this is not the case,
41648     ** return an SQLITE_CORRUPT error.  */
41649     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
41650     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
41651       return SQLITE_CORRUPT_BKPT;
41652     }
41653   }
41654
41655   /* Assert that the root page is of the correct type. This must be the
41656   ** case as the call to this function that loaded the root-page (either
41657   ** this call or a previous invocation) would have detected corruption 
41658   ** if the assumption were not true, and it is not possible for the flags 
41659   ** byte to have been modified while this cursor is holding a reference
41660   ** to the page.  */
41661   pRoot = pCur->apPage[0];
41662   assert( pRoot->pgno==pCur->pgnoRoot );
41663   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
41664
41665   pCur->aiIdx[0] = 0;
41666   pCur->info.nSize = 0;
41667   pCur->atLast = 0;
41668   pCur->validNKey = 0;
41669
41670   if( pRoot->nCell==0 && !pRoot->leaf ){
41671     Pgno subpage;
41672     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
41673     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
41674     pCur->eState = CURSOR_VALID;
41675     rc = moveToChild(pCur, subpage);
41676   }else{
41677     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
41678   }
41679   return rc;
41680 }
41681
41682 /*
41683 ** Move the cursor down to the left-most leaf entry beneath the
41684 ** entry to which it is currently pointing.
41685 **
41686 ** The left-most leaf is the one with the smallest key - the first
41687 ** in ascending order.
41688 */
41689 static int moveToLeftmost(BtCursor *pCur){
41690   Pgno pgno;
41691   int rc = SQLITE_OK;
41692   MemPage *pPage;
41693
41694   assert( cursorHoldsMutex(pCur) );
41695   assert( pCur->eState==CURSOR_VALID );
41696   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
41697     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
41698     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
41699     rc = moveToChild(pCur, pgno);
41700   }
41701   return rc;
41702 }
41703
41704 /*
41705 ** Move the cursor down to the right-most leaf entry beneath the
41706 ** page to which it is currently pointing.  Notice the difference
41707 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
41708 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
41709 ** finds the right-most entry beneath the *page*.
41710 **
41711 ** The right-most entry is the one with the largest key - the last
41712 ** key in ascending order.
41713 */
41714 static int moveToRightmost(BtCursor *pCur){
41715   Pgno pgno;
41716   int rc = SQLITE_OK;
41717   MemPage *pPage = 0;
41718
41719   assert( cursorHoldsMutex(pCur) );
41720   assert( pCur->eState==CURSOR_VALID );
41721   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
41722     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
41723     pCur->aiIdx[pCur->iPage] = pPage->nCell;
41724     rc = moveToChild(pCur, pgno);
41725   }
41726   if( rc==SQLITE_OK ){
41727     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
41728     pCur->info.nSize = 0;
41729     pCur->validNKey = 0;
41730   }
41731   return rc;
41732 }
41733
41734 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
41735 ** on success.  Set *pRes to 0 if the cursor actually points to something
41736 ** or set *pRes to 1 if the table is empty.
41737 */
41738 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
41739   int rc;
41740
41741   assert( cursorHoldsMutex(pCur) );
41742   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41743   rc = moveToRoot(pCur);
41744   if( rc==SQLITE_OK ){
41745     if( pCur->eState==CURSOR_INVALID ){
41746       assert( pCur->apPage[pCur->iPage]->nCell==0 );
41747       *pRes = 1;
41748       rc = SQLITE_OK;
41749     }else{
41750       assert( pCur->apPage[pCur->iPage]->nCell>0 );
41751       *pRes = 0;
41752       rc = moveToLeftmost(pCur);
41753     }
41754   }
41755   return rc;
41756 }
41757
41758 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
41759 ** on success.  Set *pRes to 0 if the cursor actually points to something
41760 ** or set *pRes to 1 if the table is empty.
41761 */
41762 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
41763   int rc;
41764  
41765   assert( cursorHoldsMutex(pCur) );
41766   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41767
41768   /* If the cursor already points to the last entry, this is a no-op. */
41769   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
41770 #ifdef SQLITE_DEBUG
41771     /* This block serves to assert() that the cursor really does point 
41772     ** to the last entry in the b-tree. */
41773     int ii;
41774     for(ii=0; ii<pCur->iPage; ii++){
41775       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
41776     }
41777     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
41778     assert( pCur->apPage[pCur->iPage]->leaf );
41779 #endif
41780     return SQLITE_OK;
41781   }
41782
41783   rc = moveToRoot(pCur);
41784   if( rc==SQLITE_OK ){
41785     if( CURSOR_INVALID==pCur->eState ){
41786       assert( pCur->apPage[pCur->iPage]->nCell==0 );
41787       *pRes = 1;
41788     }else{
41789       assert( pCur->eState==CURSOR_VALID );
41790       *pRes = 0;
41791       rc = moveToRightmost(pCur);
41792       pCur->atLast = rc==SQLITE_OK ?1:0;
41793     }
41794   }
41795   return rc;
41796 }
41797
41798 /* Move the cursor so that it points to an entry near the key 
41799 ** specified by pIdxKey or intKey.   Return a success code.
41800 **
41801 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
41802 ** must be NULL.  For index tables, pIdxKey is used and intKey
41803 ** is ignored.
41804 **
41805 ** If an exact match is not found, then the cursor is always
41806 ** left pointing at a leaf page which would hold the entry if it
41807 ** were present.  The cursor might point to an entry that comes
41808 ** before or after the key.
41809 **
41810 ** An integer is written into *pRes which is the result of
41811 ** comparing the key with the entry to which the cursor is 
41812 ** pointing.  The meaning of the integer written into
41813 ** *pRes is as follows:
41814 **
41815 **     *pRes<0      The cursor is left pointing at an entry that
41816 **                  is smaller than intKey/pIdxKey or if the table is empty
41817 **                  and the cursor is therefore left point to nothing.
41818 **
41819 **     *pRes==0     The cursor is left pointing at an entry that
41820 **                  exactly matches intKey/pIdxKey.
41821 **
41822 **     *pRes>0      The cursor is left pointing at an entry that
41823 **                  is larger than intKey/pIdxKey.
41824 **
41825 */
41826 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
41827   BtCursor *pCur,          /* The cursor to be moved */
41828   UnpackedRecord *pIdxKey, /* Unpacked index key */
41829   i64 intKey,              /* The table key */
41830   int biasRight,           /* If true, bias the search to the high end */
41831   int *pRes                /* Write search results here */
41832 ){
41833   int rc;
41834
41835   assert( cursorHoldsMutex(pCur) );
41836   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41837   assert( pRes );
41838   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
41839
41840   /* If the cursor is already positioned at the point we are trying
41841   ** to move to, then just return without doing any work */
41842   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
41843    && pCur->apPage[0]->intKey 
41844   ){
41845     if( pCur->info.nKey==intKey ){
41846       *pRes = 0;
41847       return SQLITE_OK;
41848     }
41849     if( pCur->atLast && pCur->info.nKey<intKey ){
41850       *pRes = -1;
41851       return SQLITE_OK;
41852     }
41853   }
41854
41855   rc = moveToRoot(pCur);
41856   if( rc ){
41857     return rc;
41858   }
41859   assert( pCur->apPage[pCur->iPage] );
41860   assert( pCur->apPage[pCur->iPage]->isInit );
41861   assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
41862   if( pCur->eState==CURSOR_INVALID ){
41863     *pRes = -1;
41864     assert( pCur->apPage[pCur->iPage]->nCell==0 );
41865     return SQLITE_OK;
41866   }
41867   assert( pCur->apPage[0]->intKey || pIdxKey );
41868   for(;;){
41869     int lwr, upr;
41870     Pgno chldPg;
41871     MemPage *pPage = pCur->apPage[pCur->iPage];
41872     int c;
41873
41874     /* pPage->nCell must be greater than zero. If this is the root-page
41875     ** the cursor would have been INVALID above and this for(;;) loop
41876     ** not run. If this is not the root-page, then the moveToChild() routine
41877     ** would have already detected db corruption. Similarly, pPage must
41878     ** be the right kind (index or table) of b-tree page. Otherwise
41879     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
41880     assert( pPage->nCell>0 );
41881     assert( pPage->intKey==(pIdxKey==0) );
41882     lwr = 0;
41883     upr = pPage->nCell-1;
41884     if( biasRight ){
41885       pCur->aiIdx[pCur->iPage] = (u16)upr;
41886     }else{
41887       pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
41888     }
41889     for(;;){
41890       int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
41891       u8 *pCell;                          /* Pointer to current cell in pPage */
41892
41893       pCur->info.nSize = 0;
41894       pCell = findCell(pPage, idx) + pPage->childPtrSize;
41895       if( pPage->intKey ){
41896         i64 nCellKey;
41897         if( pPage->hasData ){
41898           u32 dummy;
41899           pCell += getVarint32(pCell, dummy);
41900         }
41901         getVarint(pCell, (u64*)&nCellKey);
41902         if( nCellKey==intKey ){
41903           c = 0;
41904         }else if( nCellKey<intKey ){
41905           c = -1;
41906         }else{
41907           assert( nCellKey>intKey );
41908           c = +1;
41909         }
41910         pCur->validNKey = 1;
41911         pCur->info.nKey = nCellKey;
41912       }else{
41913         /* The maximum supported page-size is 32768 bytes. This means that
41914         ** the maximum number of record bytes stored on an index B-Tree
41915         ** page is at most 8198 bytes, which may be stored as a 2-byte
41916         ** varint. This information is used to attempt to avoid parsing 
41917         ** the entire cell by checking for the cases where the record is 
41918         ** stored entirely within the b-tree page by inspecting the first 
41919         ** 2 bytes of the cell.
41920         */
41921         int nCell = pCell[0];
41922         if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
41923           /* This branch runs if the record-size field of the cell is a
41924           ** single byte varint and the record fits entirely on the main
41925           ** b-tree page.  */
41926           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
41927         }else if( !(pCell[1] & 0x80) 
41928           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
41929         ){
41930           /* The record-size field is a 2 byte varint and the record 
41931           ** fits entirely on the main b-tree page.  */
41932           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
41933         }else{
41934           /* The record flows over onto one or more overflow pages. In
41935           ** this case the whole cell needs to be parsed, a buffer allocated
41936           ** and accessPayload() used to retrieve the record into the
41937           ** buffer before VdbeRecordCompare() can be called. */
41938           void *pCellKey;
41939           u8 * const pCellBody = pCell - pPage->childPtrSize;
41940           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
41941           nCell = (int)pCur->info.nKey;
41942           pCellKey = sqlite3Malloc( nCell );
41943           if( pCellKey==0 ){
41944             rc = SQLITE_NOMEM;
41945             goto moveto_finish;
41946           }
41947           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
41948           if( rc ){
41949             sqlite3_free(pCellKey);
41950             goto moveto_finish;
41951           }
41952           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
41953           sqlite3_free(pCellKey);
41954         }
41955       }
41956       if( c==0 ){
41957         if( pPage->intKey && !pPage->leaf ){
41958           lwr = idx;
41959           upr = lwr - 1;
41960           break;
41961         }else{
41962           *pRes = 0;
41963           rc = SQLITE_OK;
41964           goto moveto_finish;
41965         }
41966       }
41967       if( c<0 ){
41968         lwr = idx+1;
41969       }else{
41970         upr = idx-1;
41971       }
41972       if( lwr>upr ){
41973         break;
41974       }
41975       pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
41976     }
41977     assert( lwr==upr+1 );
41978     assert( pPage->isInit );
41979     if( pPage->leaf ){
41980       chldPg = 0;
41981     }else if( lwr>=pPage->nCell ){
41982       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
41983     }else{
41984       chldPg = get4byte(findCell(pPage, lwr));
41985     }
41986     if( chldPg==0 ){
41987       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
41988       *pRes = c;
41989       rc = SQLITE_OK;
41990       goto moveto_finish;
41991     }
41992     pCur->aiIdx[pCur->iPage] = (u16)lwr;
41993     pCur->info.nSize = 0;
41994     pCur->validNKey = 0;
41995     rc = moveToChild(pCur, chldPg);
41996     if( rc ) goto moveto_finish;
41997   }
41998 moveto_finish:
41999   return rc;
42000 }
42001
42002
42003 /*
42004 ** Return TRUE if the cursor is not pointing at an entry of the table.
42005 **
42006 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
42007 ** past the last entry in the table or sqlite3BtreePrev() moves past
42008 ** the first entry.  TRUE is also returned if the table is empty.
42009 */
42010 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
42011   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
42012   ** have been deleted? This API will need to change to return an error code
42013   ** as well as the boolean result value.
42014   */
42015   return (CURSOR_VALID!=pCur->eState);
42016 }
42017
42018 /*
42019 ** Advance the cursor to the next entry in the database.  If
42020 ** successful then set *pRes=0.  If the cursor
42021 ** was already pointing to the last entry in the database before
42022 ** this routine was called, then set *pRes=1.
42023 */
42024 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
42025   int rc;
42026   int idx;
42027   MemPage *pPage;
42028
42029   assert( cursorHoldsMutex(pCur) );
42030   rc = restoreCursorPosition(pCur);
42031   if( rc!=SQLITE_OK ){
42032     return rc;
42033   }
42034   assert( pRes!=0 );
42035   if( CURSOR_INVALID==pCur->eState ){
42036     *pRes = 1;
42037     return SQLITE_OK;
42038   }
42039   if( pCur->skipNext>0 ){
42040     pCur->skipNext = 0;
42041     *pRes = 0;
42042     return SQLITE_OK;
42043   }
42044   pCur->skipNext = 0;
42045
42046   pPage = pCur->apPage[pCur->iPage];
42047   idx = ++pCur->aiIdx[pCur->iPage];
42048   assert( pPage->isInit );
42049   assert( idx<=pPage->nCell );
42050
42051   pCur->info.nSize = 0;
42052   pCur->validNKey = 0;
42053   if( idx>=pPage->nCell ){
42054     if( !pPage->leaf ){
42055       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
42056       if( rc ) return rc;
42057       rc = moveToLeftmost(pCur);
42058       *pRes = 0;
42059       return rc;
42060     }
42061     do{
42062       if( pCur->iPage==0 ){
42063         *pRes = 1;
42064         pCur->eState = CURSOR_INVALID;
42065         return SQLITE_OK;
42066       }
42067       moveToParent(pCur);
42068       pPage = pCur->apPage[pCur->iPage];
42069     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
42070     *pRes = 0;
42071     if( pPage->intKey ){
42072       rc = sqlite3BtreeNext(pCur, pRes);
42073     }else{
42074       rc = SQLITE_OK;
42075     }
42076     return rc;
42077   }
42078   *pRes = 0;
42079   if( pPage->leaf ){
42080     return SQLITE_OK;
42081   }
42082   rc = moveToLeftmost(pCur);
42083   return rc;
42084 }
42085
42086
42087 /*
42088 ** Step the cursor to the back to the previous entry in the database.  If
42089 ** successful then set *pRes=0.  If the cursor
42090 ** was already pointing to the first entry in the database before
42091 ** this routine was called, then set *pRes=1.
42092 */
42093 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
42094   int rc;
42095   MemPage *pPage;
42096
42097   assert( cursorHoldsMutex(pCur) );
42098   rc = restoreCursorPosition(pCur);
42099   if( rc!=SQLITE_OK ){
42100     return rc;
42101   }
42102   pCur->atLast = 0;
42103   if( CURSOR_INVALID==pCur->eState ){
42104     *pRes = 1;
42105     return SQLITE_OK;
42106   }
42107   if( pCur->skipNext<0 ){
42108     pCur->skipNext = 0;
42109     *pRes = 0;
42110     return SQLITE_OK;
42111   }
42112   pCur->skipNext = 0;
42113
42114   pPage = pCur->apPage[pCur->iPage];
42115   assert( pPage->isInit );
42116   if( !pPage->leaf ){
42117     int idx = pCur->aiIdx[pCur->iPage];
42118     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
42119     if( rc ){
42120       return rc;
42121     }
42122     rc = moveToRightmost(pCur);
42123   }else{
42124     while( pCur->aiIdx[pCur->iPage]==0 ){
42125       if( pCur->iPage==0 ){
42126         pCur->eState = CURSOR_INVALID;
42127         *pRes = 1;
42128         return SQLITE_OK;
42129       }
42130       moveToParent(pCur);
42131     }
42132     pCur->info.nSize = 0;
42133     pCur->validNKey = 0;
42134
42135     pCur->aiIdx[pCur->iPage]--;
42136     pPage = pCur->apPage[pCur->iPage];
42137     if( pPage->intKey && !pPage->leaf ){
42138       rc = sqlite3BtreePrevious(pCur, pRes);
42139     }else{
42140       rc = SQLITE_OK;
42141     }
42142   }
42143   *pRes = 0;
42144   return rc;
42145 }
42146
42147 /*
42148 ** Allocate a new page from the database file.
42149 **
42150 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
42151 ** has already been called on the new page.)  The new page has also
42152 ** been referenced and the calling routine is responsible for calling
42153 ** sqlite3PagerUnref() on the new page when it is done.
42154 **
42155 ** SQLITE_OK is returned on success.  Any other return value indicates
42156 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
42157 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
42158 **
42159 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
42160 ** locate a page close to the page number "nearby".  This can be used in an
42161 ** attempt to keep related pages close to each other in the database file,
42162 ** which in turn can make database access faster.
42163 **
42164 ** If the "exact" parameter is not 0, and the page-number nearby exists 
42165 ** anywhere on the free-list, then it is guarenteed to be returned. This
42166 ** is only used by auto-vacuum databases when allocating a new table.
42167 */
42168 static int allocateBtreePage(
42169   BtShared *pBt, 
42170   MemPage **ppPage, 
42171   Pgno *pPgno, 
42172   Pgno nearby,
42173   u8 exact
42174 ){
42175   MemPage *pPage1;
42176   int rc;
42177   u32 n;     /* Number of pages on the freelist */
42178   u32 k;     /* Number of leaves on the trunk of the freelist */
42179   MemPage *pTrunk = 0;
42180   MemPage *pPrevTrunk = 0;
42181   Pgno mxPage;     /* Total size of the database file */
42182
42183   assert( sqlite3_mutex_held(pBt->mutex) );
42184   pPage1 = pBt->pPage1;
42185   mxPage = pagerPagecount(pBt);
42186   n = get4byte(&pPage1->aData[36]);
42187   testcase( n==mxPage-1 );
42188   if( n>=mxPage ){
42189     return SQLITE_CORRUPT_BKPT;
42190   }
42191   if( n>0 ){
42192     /* There are pages on the freelist.  Reuse one of those pages. */
42193     Pgno iTrunk;
42194     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
42195     
42196     /* If the 'exact' parameter was true and a query of the pointer-map
42197     ** shows that the page 'nearby' is somewhere on the free-list, then
42198     ** the entire-list will be searched for that page.
42199     */
42200 #ifndef SQLITE_OMIT_AUTOVACUUM
42201     if( exact && nearby<=mxPage ){
42202       u8 eType;
42203       assert( nearby>0 );
42204       assert( pBt->autoVacuum );
42205       rc = ptrmapGet(pBt, nearby, &eType, 0);
42206       if( rc ) return rc;
42207       if( eType==PTRMAP_FREEPAGE ){
42208         searchList = 1;
42209       }
42210       *pPgno = nearby;
42211     }
42212 #endif
42213
42214     /* Decrement the free-list count by 1. Set iTrunk to the index of the
42215     ** first free-list trunk page. iPrevTrunk is initially 1.
42216     */
42217     rc = sqlite3PagerWrite(pPage1->pDbPage);
42218     if( rc ) return rc;
42219     put4byte(&pPage1->aData[36], n-1);
42220
42221     /* The code within this loop is run only once if the 'searchList' variable
42222     ** is not true. Otherwise, it runs once for each trunk-page on the
42223     ** free-list until the page 'nearby' is located.
42224     */
42225     do {
42226       pPrevTrunk = pTrunk;
42227       if( pPrevTrunk ){
42228         iTrunk = get4byte(&pPrevTrunk->aData[0]);
42229       }else{
42230         iTrunk = get4byte(&pPage1->aData[32]);
42231       }
42232       testcase( iTrunk==mxPage );
42233       if( iTrunk>mxPage ){
42234         rc = SQLITE_CORRUPT_BKPT;
42235       }else{
42236         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
42237       }
42238       if( rc ){
42239         pTrunk = 0;
42240         goto end_allocate_page;
42241       }
42242
42243       k = get4byte(&pTrunk->aData[4]);
42244       if( k==0 && !searchList ){
42245         /* The trunk has no leaves and the list is not being searched. 
42246         ** So extract the trunk page itself and use it as the newly 
42247         ** allocated page */
42248         assert( pPrevTrunk==0 );
42249         rc = sqlite3PagerWrite(pTrunk->pDbPage);
42250         if( rc ){
42251           goto end_allocate_page;
42252         }
42253         *pPgno = iTrunk;
42254         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
42255         *ppPage = pTrunk;
42256         pTrunk = 0;
42257         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
42258       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
42259         /* Value of k is out of range.  Database corruption */
42260         rc = SQLITE_CORRUPT_BKPT;
42261         goto end_allocate_page;
42262 #ifndef SQLITE_OMIT_AUTOVACUUM
42263       }else if( searchList && nearby==iTrunk ){
42264         /* The list is being searched and this trunk page is the page
42265         ** to allocate, regardless of whether it has leaves.
42266         */
42267         assert( *pPgno==iTrunk );
42268         *ppPage = pTrunk;
42269         searchList = 0;
42270         rc = sqlite3PagerWrite(pTrunk->pDbPage);
42271         if( rc ){
42272           goto end_allocate_page;
42273         }
42274         if( k==0 ){
42275           if( !pPrevTrunk ){
42276             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
42277           }else{
42278             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
42279           }
42280         }else{
42281           /* The trunk page is required by the caller but it contains 
42282           ** pointers to free-list leaves. The first leaf becomes a trunk
42283           ** page in this case.
42284           */
42285           MemPage *pNewTrunk;
42286           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
42287           if( iNewTrunk>mxPage ){ 
42288             rc = SQLITE_CORRUPT_BKPT;
42289             goto end_allocate_page;
42290           }
42291           testcase( iNewTrunk==mxPage );
42292           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
42293           if( rc!=SQLITE_OK ){
42294             goto end_allocate_page;
42295           }
42296           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
42297           if( rc!=SQLITE_OK ){
42298             releasePage(pNewTrunk);
42299             goto end_allocate_page;
42300           }
42301           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
42302           put4byte(&pNewTrunk->aData[4], k-1);
42303           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
42304           releasePage(pNewTrunk);
42305           if( !pPrevTrunk ){
42306             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
42307             put4byte(&pPage1->aData[32], iNewTrunk);
42308           }else{
42309             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
42310             if( rc ){
42311               goto end_allocate_page;
42312             }
42313             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
42314           }
42315         }
42316         pTrunk = 0;
42317         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
42318 #endif
42319       }else if( k>0 ){
42320         /* Extract a leaf from the trunk */
42321         u32 closest;
42322         Pgno iPage;
42323         unsigned char *aData = pTrunk->aData;
42324         rc = sqlite3PagerWrite(pTrunk->pDbPage);
42325         if( rc ){
42326           goto end_allocate_page;
42327         }
42328         if( nearby>0 ){
42329           u32 i;
42330           int dist;
42331           closest = 0;
42332           dist = get4byte(&aData[8]) - nearby;
42333           if( dist<0 ) dist = -dist;
42334           for(i=1; i<k; i++){
42335             int d2 = get4byte(&aData[8+i*4]) - nearby;
42336             if( d2<0 ) d2 = -d2;
42337             if( d2<dist ){
42338               closest = i;
42339               dist = d2;
42340             }
42341           }
42342         }else{
42343           closest = 0;
42344         }
42345
42346         iPage = get4byte(&aData[8+closest*4]);
42347         testcase( iPage==mxPage );
42348         if( iPage>mxPage ){
42349           rc = SQLITE_CORRUPT_BKPT;
42350           goto end_allocate_page;
42351         }
42352         testcase( iPage==mxPage );
42353         if( !searchList || iPage==nearby ){
42354           int noContent;
42355           *pPgno = iPage;
42356           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
42357                  ": %d more free pages\n",
42358                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
42359           if( closest<k-1 ){
42360             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
42361           }
42362           put4byte(&aData[4], k-1);
42363           assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
42364           noContent = !btreeGetHasContent(pBt, *pPgno);
42365           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
42366           if( rc==SQLITE_OK ){
42367             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
42368             if( rc!=SQLITE_OK ){
42369               releasePage(*ppPage);
42370             }
42371           }
42372           searchList = 0;
42373         }
42374       }
42375       releasePage(pPrevTrunk);
42376       pPrevTrunk = 0;
42377     }while( searchList );
42378   }else{
42379     /* There are no pages on the freelist, so create a new page at the
42380     ** end of the file */
42381     int nPage = pagerPagecount(pBt);
42382     *pPgno = nPage + 1;
42383
42384     if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
42385       (*pPgno)++;
42386     }
42387
42388 #ifndef SQLITE_OMIT_AUTOVACUUM
42389     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
42390       /* If *pPgno refers to a pointer-map page, allocate two new pages
42391       ** at the end of the file instead of one. The first allocated page
42392       ** becomes a new pointer-map page, the second is used by the caller.
42393       */
42394       MemPage *pPg = 0;
42395       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
42396       assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
42397       rc = btreeGetPage(pBt, *pPgno, &pPg, 0);
42398       if( rc==SQLITE_OK ){
42399         rc = sqlite3PagerWrite(pPg->pDbPage);
42400         releasePage(pPg);
42401       }
42402       if( rc ) return rc;
42403       (*pPgno)++;
42404       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
42405     }
42406 #endif
42407
42408     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
42409     rc = btreeGetPage(pBt, *pPgno, ppPage, 0);
42410     if( rc ) return rc;
42411     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
42412     if( rc!=SQLITE_OK ){
42413       releasePage(*ppPage);
42414     }
42415     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
42416   }
42417
42418   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
42419
42420 end_allocate_page:
42421   releasePage(pTrunk);
42422   releasePage(pPrevTrunk);
42423   if( rc==SQLITE_OK ){
42424     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
42425       releasePage(*ppPage);
42426       return SQLITE_CORRUPT_BKPT;
42427     }
42428     (*ppPage)->isInit = 0;
42429   }else{
42430     *ppPage = 0;
42431   }
42432   return rc;
42433 }
42434
42435 /*
42436 ** This function is used to add page iPage to the database file free-list. 
42437 ** It is assumed that the page is not already a part of the free-list.
42438 **
42439 ** The value passed as the second argument to this function is optional.
42440 ** If the caller happens to have a pointer to the MemPage object 
42441 ** corresponding to page iPage handy, it may pass it as the second value. 
42442 ** Otherwise, it may pass NULL.
42443 **
42444 ** If a pointer to a MemPage object is passed as the second argument,
42445 ** its reference count is not altered by this function.
42446 */
42447 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
42448   MemPage *pTrunk = 0;                /* Free-list trunk page */
42449   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
42450   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
42451   MemPage *pPage;                     /* Page being freed. May be NULL. */
42452   int rc;                             /* Return Code */
42453   int nFree;                          /* Initial number of pages on free-list */
42454
42455   assert( sqlite3_mutex_held(pBt->mutex) );
42456   assert( iPage>1 );
42457   assert( !pMemPage || pMemPage->pgno==iPage );
42458
42459   if( pMemPage ){
42460     pPage = pMemPage;
42461     sqlite3PagerRef(pPage->pDbPage);
42462   }else{
42463     pPage = btreePageLookup(pBt, iPage);
42464   }
42465
42466   /* Increment the free page count on pPage1 */
42467   rc = sqlite3PagerWrite(pPage1->pDbPage);
42468   if( rc ) goto freepage_out;
42469   nFree = get4byte(&pPage1->aData[36]);
42470   put4byte(&pPage1->aData[36], nFree+1);
42471
42472 #ifdef SQLITE_SECURE_DELETE
42473   /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
42474   ** always fully overwrite deleted information with zeros.
42475   */
42476   if( (!pPage && (rc = btreeGetPage(pBt, iPage, &pPage, 0)))
42477    ||            (rc = sqlite3PagerWrite(pPage->pDbPage))
42478   ){
42479     goto freepage_out;
42480   }
42481   memset(pPage->aData, 0, pPage->pBt->pageSize);
42482 #endif
42483
42484   /* If the database supports auto-vacuum, write an entry in the pointer-map
42485   ** to indicate that the page is free.
42486   */
42487   if( ISAUTOVACUUM ){
42488     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
42489     if( rc ) goto freepage_out;
42490   }
42491
42492   /* Now manipulate the actual database free-list structure. There are two
42493   ** possibilities. If the free-list is currently empty, or if the first
42494   ** trunk page in the free-list is full, then this page will become a
42495   ** new free-list trunk page. Otherwise, it will become a leaf of the
42496   ** first trunk page in the current free-list. This block tests if it
42497   ** is possible to add the page as a new free-list leaf.
42498   */
42499   if( nFree!=0 ){
42500     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
42501
42502     iTrunk = get4byte(&pPage1->aData[32]);
42503     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
42504     if( rc!=SQLITE_OK ){
42505       goto freepage_out;
42506     }
42507
42508     nLeaf = get4byte(&pTrunk->aData[4]);
42509     assert( pBt->usableSize>32 );
42510     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
42511       rc = SQLITE_CORRUPT_BKPT;
42512       goto freepage_out;
42513     }
42514     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
42515       /* In this case there is room on the trunk page to insert the page
42516       ** being freed as a new leaf.
42517       **
42518       ** Note that the trunk page is not really full until it contains
42519       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
42520       ** coded.  But due to a coding error in versions of SQLite prior to
42521       ** 3.6.0, databases with freelist trunk pages holding more than
42522       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
42523       ** to maintain backwards compatibility with older versions of SQLite,
42524       ** we will continue to restrict the number of entries to usableSize/4 - 8
42525       ** for now.  At some point in the future (once everyone has upgraded
42526       ** to 3.6.0 or later) we should consider fixing the conditional above
42527       ** to read "usableSize/4-2" instead of "usableSize/4-8".
42528       */
42529       rc = sqlite3PagerWrite(pTrunk->pDbPage);
42530       if( rc==SQLITE_OK ){
42531         put4byte(&pTrunk->aData[4], nLeaf+1);
42532         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
42533 #ifndef SQLITE_SECURE_DELETE
42534         if( pPage ){
42535           sqlite3PagerDontWrite(pPage->pDbPage);
42536         }
42537 #endif
42538         rc = btreeSetHasContent(pBt, iPage);
42539       }
42540       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
42541       goto freepage_out;
42542     }
42543   }
42544
42545   /* If control flows to this point, then it was not possible to add the
42546   ** the page being freed as a leaf page of the first trunk in the free-list.
42547   ** Possibly because the free-list is empty, or possibly because the 
42548   ** first trunk in the free-list is full. Either way, the page being freed
42549   ** will become the new first trunk page in the free-list.
42550   */
42551   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
42552     goto freepage_out;
42553   }
42554   rc = sqlite3PagerWrite(pPage->pDbPage);
42555   if( rc!=SQLITE_OK ){
42556     goto freepage_out;
42557   }
42558   put4byte(pPage->aData, iTrunk);
42559   put4byte(&pPage->aData[4], 0);
42560   put4byte(&pPage1->aData[32], iPage);
42561   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
42562
42563 freepage_out:
42564   if( pPage ){
42565     pPage->isInit = 0;
42566   }
42567   releasePage(pPage);
42568   releasePage(pTrunk);
42569   return rc;
42570 }
42571 static void freePage(MemPage *pPage, int *pRC){
42572   if( (*pRC)==SQLITE_OK ){
42573     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
42574   }
42575 }
42576
42577 /*
42578 ** Free any overflow pages associated with the given Cell.
42579 */
42580 static int clearCell(MemPage *pPage, unsigned char *pCell){
42581   BtShared *pBt = pPage->pBt;
42582   CellInfo info;
42583   Pgno ovflPgno;
42584   int rc;
42585   int nOvfl;
42586   u16 ovflPageSize;
42587
42588   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42589   btreeParseCellPtr(pPage, pCell, &info);
42590   if( info.iOverflow==0 ){
42591     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
42592   }
42593   ovflPgno = get4byte(&pCell[info.iOverflow]);
42594   assert( pBt->usableSize > 4 );
42595   ovflPageSize = pBt->usableSize - 4;
42596   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
42597   assert( ovflPgno==0 || nOvfl>0 );
42598   while( nOvfl-- ){
42599     Pgno iNext = 0;
42600     MemPage *pOvfl = 0;
42601     if( ovflPgno<2 || ovflPgno>pagerPagecount(pBt) ){
42602       /* 0 is not a legal page number and page 1 cannot be an 
42603       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
42604       ** file the database must be corrupt. */
42605       return SQLITE_CORRUPT_BKPT;
42606     }
42607     if( nOvfl ){
42608       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
42609       if( rc ) return rc;
42610     }
42611     rc = freePage2(pBt, pOvfl, ovflPgno);
42612     if( pOvfl ){
42613       sqlite3PagerUnref(pOvfl->pDbPage);
42614     }
42615     if( rc ) return rc;
42616     ovflPgno = iNext;
42617   }
42618   return SQLITE_OK;
42619 }
42620
42621 /*
42622 ** Create the byte sequence used to represent a cell on page pPage
42623 ** and write that byte sequence into pCell[].  Overflow pages are
42624 ** allocated and filled in as necessary.  The calling procedure
42625 ** is responsible for making sure sufficient space has been allocated
42626 ** for pCell[].
42627 **
42628 ** Note that pCell does not necessary need to point to the pPage->aData
42629 ** area.  pCell might point to some temporary storage.  The cell will
42630 ** be constructed in this temporary area then copied into pPage->aData
42631 ** later.
42632 */
42633 static int fillInCell(
42634   MemPage *pPage,                /* The page that contains the cell */
42635   unsigned char *pCell,          /* Complete text of the cell */
42636   const void *pKey, i64 nKey,    /* The key */
42637   const void *pData,int nData,   /* The data */
42638   int nZero,                     /* Extra zero bytes to append to pData */
42639   int *pnSize                    /* Write cell size here */
42640 ){
42641   int nPayload;
42642   const u8 *pSrc;
42643   int nSrc, n, rc;
42644   int spaceLeft;
42645   MemPage *pOvfl = 0;
42646   MemPage *pToRelease = 0;
42647   unsigned char *pPrior;
42648   unsigned char *pPayload;
42649   BtShared *pBt = pPage->pBt;
42650   Pgno pgnoOvfl = 0;
42651   int nHeader;
42652   CellInfo info;
42653
42654   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42655
42656   /* pPage is not necessarily writeable since pCell might be auxiliary
42657   ** buffer space that is separate from the pPage buffer area */
42658   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
42659             || sqlite3PagerIswriteable(pPage->pDbPage) );
42660
42661   /* Fill in the header. */
42662   nHeader = 0;
42663   if( !pPage->leaf ){
42664     nHeader += 4;
42665   }
42666   if( pPage->hasData ){
42667     nHeader += putVarint(&pCell[nHeader], nData+nZero);
42668   }else{
42669     nData = nZero = 0;
42670   }
42671   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
42672   btreeParseCellPtr(pPage, pCell, &info);
42673   assert( info.nHeader==nHeader );
42674   assert( info.nKey==nKey );
42675   assert( info.nData==(u32)(nData+nZero) );
42676   
42677   /* Fill in the payload */
42678   nPayload = nData + nZero;
42679   if( pPage->intKey ){
42680     pSrc = pData;
42681     nSrc = nData;
42682     nData = 0;
42683   }else{ 
42684     if( NEVER(nKey>0x7fffffff || pKey==0) ){
42685       return SQLITE_CORRUPT_BKPT;
42686     }
42687     nPayload += (int)nKey;
42688     pSrc = pKey;
42689     nSrc = (int)nKey;
42690   }
42691   *pnSize = info.nSize;
42692   spaceLeft = info.nLocal;
42693   pPayload = &pCell[nHeader];
42694   pPrior = &pCell[info.iOverflow];
42695
42696   while( nPayload>0 ){
42697     if( spaceLeft==0 ){
42698 #ifndef SQLITE_OMIT_AUTOVACUUM
42699       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
42700       if( pBt->autoVacuum ){
42701         do{
42702           pgnoOvfl++;
42703         } while( 
42704           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
42705         );
42706       }
42707 #endif
42708       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
42709 #ifndef SQLITE_OMIT_AUTOVACUUM
42710       /* If the database supports auto-vacuum, and the second or subsequent
42711       ** overflow page is being allocated, add an entry to the pointer-map
42712       ** for that page now. 
42713       **
42714       ** If this is the first overflow page, then write a partial entry 
42715       ** to the pointer-map. If we write nothing to this pointer-map slot,
42716       ** then the optimistic overflow chain processing in clearCell()
42717       ** may misinterpret the uninitialised values and delete the
42718       ** wrong pages from the database.
42719       */
42720       if( pBt->autoVacuum && rc==SQLITE_OK ){
42721         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
42722         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
42723         if( rc ){
42724           releasePage(pOvfl);
42725         }
42726       }
42727 #endif
42728       if( rc ){
42729         releasePage(pToRelease);
42730         return rc;
42731       }
42732
42733       /* If pToRelease is not zero than pPrior points into the data area
42734       ** of pToRelease.  Make sure pToRelease is still writeable. */
42735       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
42736
42737       /* If pPrior is part of the data area of pPage, then make sure pPage
42738       ** is still writeable */
42739       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
42740             || sqlite3PagerIswriteable(pPage->pDbPage) );
42741
42742       put4byte(pPrior, pgnoOvfl);
42743       releasePage(pToRelease);
42744       pToRelease = pOvfl;
42745       pPrior = pOvfl->aData;
42746       put4byte(pPrior, 0);
42747       pPayload = &pOvfl->aData[4];
42748       spaceLeft = pBt->usableSize - 4;
42749     }
42750     n = nPayload;
42751     if( n>spaceLeft ) n = spaceLeft;
42752
42753     /* If pToRelease is not zero than pPayload points into the data area
42754     ** of pToRelease.  Make sure pToRelease is still writeable. */
42755     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
42756
42757     /* If pPayload is part of the data area of pPage, then make sure pPage
42758     ** is still writeable */
42759     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
42760             || sqlite3PagerIswriteable(pPage->pDbPage) );
42761
42762     if( nSrc>0 ){
42763       if( n>nSrc ) n = nSrc;
42764       assert( pSrc );
42765       memcpy(pPayload, pSrc, n);
42766     }else{
42767       memset(pPayload, 0, n);
42768     }
42769     nPayload -= n;
42770     pPayload += n;
42771     pSrc += n;
42772     nSrc -= n;
42773     spaceLeft -= n;
42774     if( nSrc==0 ){
42775       nSrc = nData;
42776       pSrc = pData;
42777     }
42778   }
42779   releasePage(pToRelease);
42780   return SQLITE_OK;
42781 }
42782
42783 /*
42784 ** Remove the i-th cell from pPage.  This routine effects pPage only.
42785 ** The cell content is not freed or deallocated.  It is assumed that
42786 ** the cell content has been copied someplace else.  This routine just
42787 ** removes the reference to the cell from pPage.
42788 **
42789 ** "sz" must be the number of bytes in the cell.
42790 */
42791 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
42792   int i;          /* Loop counter */
42793   int pc;         /* Offset to cell content of cell being deleted */
42794   u8 *data;       /* pPage->aData */
42795   u8 *ptr;        /* Used to move bytes around within data[] */
42796   int rc;         /* The return code */
42797   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
42798
42799   if( *pRC ) return;
42800
42801   assert( idx>=0 && idx<pPage->nCell );
42802   assert( sz==cellSize(pPage, idx) );
42803   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
42804   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42805   data = pPage->aData;
42806   ptr = &data[pPage->cellOffset + 2*idx];
42807   pc = get2byte(ptr);
42808   hdr = pPage->hdrOffset;
42809   testcase( pc==get2byte(&data[hdr+5]) );
42810   testcase( pc+sz==pPage->pBt->usableSize );
42811   if( pc < get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
42812     *pRC = SQLITE_CORRUPT_BKPT;
42813     return;
42814   }
42815   rc = freeSpace(pPage, pc, sz);
42816   if( rc ){
42817     *pRC = rc;
42818     return;
42819   }
42820   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
42821     ptr[0] = ptr[2];
42822     ptr[1] = ptr[3];
42823   }
42824   pPage->nCell--;
42825   put2byte(&data[hdr+3], pPage->nCell);
42826   pPage->nFree += 2;
42827 }
42828
42829 /*
42830 ** Insert a new cell on pPage at cell index "i".  pCell points to the
42831 ** content of the cell.
42832 **
42833 ** If the cell content will fit on the page, then put it there.  If it
42834 ** will not fit, then make a copy of the cell content into pTemp if
42835 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
42836 ** in pPage->aOvfl[] and make it point to the cell content (either
42837 ** in pTemp or the original pCell) and also record its index. 
42838 ** Allocating a new entry in pPage->aCell[] implies that 
42839 ** pPage->nOverflow is incremented.
42840 **
42841 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
42842 ** cell. The caller will overwrite them after this function returns. If
42843 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
42844 ** (but pCell+nSkip is always valid).
42845 */
42846 static void insertCell(
42847   MemPage *pPage,   /* Page into which we are copying */
42848   int i,            /* New cell becomes the i-th cell of the page */
42849   u8 *pCell,        /* Content of the new cell */
42850   int sz,           /* Bytes of content in pCell */
42851   u8 *pTemp,        /* Temp storage space for pCell, if needed */
42852   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
42853   int *pRC          /* Read and write return code from here */
42854 ){
42855   int idx;          /* Where to write new cell content in data[] */
42856   int j;            /* Loop counter */
42857   int end;          /* First byte past the last cell pointer in data[] */
42858   int ins;          /* Index in data[] where new cell pointer is inserted */
42859   int cellOffset;   /* Address of first cell pointer in data[] */
42860   u8 *data;         /* The content of the whole page */
42861   u8 *ptr;          /* Used for moving information around in data[] */
42862
42863   int nSkip = (iChild ? 4 : 0);
42864
42865   if( *pRC ) return;
42866
42867   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
42868   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
42869   assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
42870   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42871   /* The cell should normally be sized correctly.  However, when moving a
42872   ** malformed cell from a leaf page to an interior page, if the cell size
42873   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
42874   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
42875   ** the term after the || in the following assert(). */
42876   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
42877   if( pPage->nOverflow || sz+2>pPage->nFree ){
42878     if( pTemp ){
42879       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
42880       pCell = pTemp;
42881     }
42882     if( iChild ){
42883       put4byte(pCell, iChild);
42884     }
42885     j = pPage->nOverflow++;
42886     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
42887     pPage->aOvfl[j].pCell = pCell;
42888     pPage->aOvfl[j].idx = (u16)i;
42889   }else{
42890     int rc = sqlite3PagerWrite(pPage->pDbPage);
42891     if( rc!=SQLITE_OK ){
42892       *pRC = rc;
42893       return;
42894     }
42895     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
42896     data = pPage->aData;
42897     cellOffset = pPage->cellOffset;
42898     end = cellOffset + 2*pPage->nCell;
42899     ins = cellOffset + 2*i;
42900     rc = allocateSpace(pPage, sz, &idx);
42901     if( rc ){ *pRC = rc; return; }
42902     /* The allocateSpace() routine guarantees the following two properties
42903     ** if it returns success */
42904     assert( idx >= end+2 );
42905     assert( idx+sz <= pPage->pBt->usableSize );
42906     pPage->nCell++;
42907     pPage->nFree -= (u16)(2 + sz);
42908     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
42909     if( iChild ){
42910       put4byte(&data[idx], iChild);
42911     }
42912     for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
42913       ptr[0] = ptr[-2];
42914       ptr[1] = ptr[-1];
42915     }
42916     put2byte(&data[ins], idx);
42917     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
42918 #ifndef SQLITE_OMIT_AUTOVACUUM
42919     if( pPage->pBt->autoVacuum ){
42920       /* The cell may contain a pointer to an overflow page. If so, write
42921       ** the entry for the overflow page into the pointer map.
42922       */
42923       ptrmapPutOvflPtr(pPage, pCell, pRC);
42924     }
42925 #endif
42926   }
42927 }
42928
42929 /*
42930 ** Add a list of cells to a page.  The page should be initially empty.
42931 ** The cells are guaranteed to fit on the page.
42932 */
42933 static void assemblePage(
42934   MemPage *pPage,   /* The page to be assemblied */
42935   int nCell,        /* The number of cells to add to this page */
42936   u8 **apCell,      /* Pointers to cell bodies */
42937   u16 *aSize        /* Sizes of the cells */
42938 ){
42939   int i;            /* Loop counter */
42940   u8 *pCellptr;     /* Address of next cell pointer */
42941   int cellbody;     /* Address of next cell body */
42942   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
42943   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
42944   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
42945
42946   assert( pPage->nOverflow==0 );
42947   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42948   assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
42949   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
42950
42951   /* Check that the page has just been zeroed by zeroPage() */
42952   assert( pPage->nCell==0 );
42953   assert( get2byte(&data[hdr+5])==nUsable );
42954
42955   pCellptr = &data[pPage->cellOffset + nCell*2];
42956   cellbody = nUsable;
42957   for(i=nCell-1; i>=0; i--){
42958     pCellptr -= 2;
42959     cellbody -= aSize[i];
42960     put2byte(pCellptr, cellbody);
42961     memcpy(&data[cellbody], apCell[i], aSize[i]);
42962   }
42963   put2byte(&data[hdr+3], nCell);
42964   put2byte(&data[hdr+5], cellbody);
42965   pPage->nFree -= (nCell*2 + nUsable - cellbody);
42966   pPage->nCell = (u16)nCell;
42967 }
42968
42969 /*
42970 ** The following parameters determine how many adjacent pages get involved
42971 ** in a balancing operation.  NN is the number of neighbors on either side
42972 ** of the page that participate in the balancing operation.  NB is the
42973 ** total number of pages that participate, including the target page and
42974 ** NN neighbors on either side.
42975 **
42976 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
42977 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
42978 ** in exchange for a larger degradation in INSERT and UPDATE performance.
42979 ** The value of NN appears to give the best results overall.
42980 */
42981 #define NN 1             /* Number of neighbors on either side of pPage */
42982 #define NB (NN*2+1)      /* Total pages involved in the balance */
42983
42984
42985 #ifndef SQLITE_OMIT_QUICKBALANCE
42986 /*
42987 ** This version of balance() handles the common special case where
42988 ** a new entry is being inserted on the extreme right-end of the
42989 ** tree, in other words, when the new entry will become the largest
42990 ** entry in the tree.
42991 **
42992 ** Instead of trying to balance the 3 right-most leaf pages, just add
42993 ** a new page to the right-hand side and put the one new entry in
42994 ** that page.  This leaves the right side of the tree somewhat
42995 ** unbalanced.  But odds are that we will be inserting new entries
42996 ** at the end soon afterwards so the nearly empty page will quickly
42997 ** fill up.  On average.
42998 **
42999 ** pPage is the leaf page which is the right-most page in the tree.
43000 ** pParent is its parent.  pPage must have a single overflow entry
43001 ** which is also the right-most entry on the page.
43002 **
43003 ** The pSpace buffer is used to store a temporary copy of the divider
43004 ** cell that will be inserted into pParent. Such a cell consists of a 4
43005 ** byte page number followed by a variable length integer. In other
43006 ** words, at most 13 bytes. Hence the pSpace buffer must be at
43007 ** least 13 bytes in size.
43008 */
43009 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
43010   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
43011   MemPage *pNew;                       /* Newly allocated page */
43012   int rc;                              /* Return Code */
43013   Pgno pgnoNew;                        /* Page number of pNew */
43014
43015   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43016   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43017   assert( pPage->nOverflow==1 );
43018
43019   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
43020
43021   /* Allocate a new page. This page will become the right-sibling of 
43022   ** pPage. Make the parent page writable, so that the new divider cell
43023   ** may be inserted. If both these operations are successful, proceed.
43024   */
43025   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
43026
43027   if( rc==SQLITE_OK ){
43028
43029     u8 *pOut = &pSpace[4];
43030     u8 *pCell = pPage->aOvfl[0].pCell;
43031     u16 szCell = cellSizePtr(pPage, pCell);
43032     u8 *pStop;
43033
43034     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
43035     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
43036     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
43037     assemblePage(pNew, 1, &pCell, &szCell);
43038
43039     /* If this is an auto-vacuum database, update the pointer map
43040     ** with entries for the new page, and any pointer from the 
43041     ** cell on the page to an overflow page. If either of these
43042     ** operations fails, the return code is set, but the contents
43043     ** of the parent page are still manipulated by thh code below.
43044     ** That is Ok, at this point the parent page is guaranteed to
43045     ** be marked as dirty. Returning an error code will cause a
43046     ** rollback, undoing any changes made to the parent page.
43047     */
43048     if( ISAUTOVACUUM ){
43049       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
43050       if( szCell>pNew->minLocal ){
43051         ptrmapPutOvflPtr(pNew, pCell, &rc);
43052       }
43053     }
43054   
43055     /* Create a divider cell to insert into pParent. The divider cell
43056     ** consists of a 4-byte page number (the page number of pPage) and
43057     ** a variable length key value (which must be the same value as the
43058     ** largest key on pPage).
43059     **
43060     ** To find the largest key value on pPage, first find the right-most 
43061     ** cell on pPage. The first two fields of this cell are the 
43062     ** record-length (a variable length integer at most 32-bits in size)
43063     ** and the key value (a variable length integer, may have any value).
43064     ** The first of the while(...) loops below skips over the record-length
43065     ** field. The second while(...) loop copies the key value from the
43066     ** cell on pPage into the pSpace buffer.
43067     */
43068     pCell = findCell(pPage, pPage->nCell-1);
43069     pStop = &pCell[9];
43070     while( (*(pCell++)&0x80) && pCell<pStop );
43071     pStop = &pCell[9];
43072     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
43073
43074     /* Insert the new divider cell into pParent. */
43075     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
43076                0, pPage->pgno, &rc);
43077
43078     /* Set the right-child pointer of pParent to point to the new page. */
43079     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
43080   
43081     /* Release the reference to the new page. */
43082     releasePage(pNew);
43083   }
43084
43085   return rc;
43086 }
43087 #endif /* SQLITE_OMIT_QUICKBALANCE */
43088
43089 #if 0
43090 /*
43091 ** This function does not contribute anything to the operation of SQLite.
43092 ** it is sometimes activated temporarily while debugging code responsible 
43093 ** for setting pointer-map entries.
43094 */
43095 static int ptrmapCheckPages(MemPage **apPage, int nPage){
43096   int i, j;
43097   for(i=0; i<nPage; i++){
43098     Pgno n;
43099     u8 e;
43100     MemPage *pPage = apPage[i];
43101     BtShared *pBt = pPage->pBt;
43102     assert( pPage->isInit );
43103
43104     for(j=0; j<pPage->nCell; j++){
43105       CellInfo info;
43106       u8 *z;
43107      
43108       z = findCell(pPage, j);
43109       btreeParseCellPtr(pPage, z, &info);
43110       if( info.iOverflow ){
43111         Pgno ovfl = get4byte(&z[info.iOverflow]);
43112         ptrmapGet(pBt, ovfl, &e, &n);
43113         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
43114       }
43115       if( !pPage->leaf ){
43116         Pgno child = get4byte(z);
43117         ptrmapGet(pBt, child, &e, &n);
43118         assert( n==pPage->pgno && e==PTRMAP_BTREE );
43119       }
43120     }
43121     if( !pPage->leaf ){
43122       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
43123       ptrmapGet(pBt, child, &e, &n);
43124       assert( n==pPage->pgno && e==PTRMAP_BTREE );
43125     }
43126   }
43127   return 1;
43128 }
43129 #endif
43130
43131 /*
43132 ** This function is used to copy the contents of the b-tree node stored 
43133 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
43134 ** the pointer-map entries for each child page are updated so that the
43135 ** parent page stored in the pointer map is page pTo. If pFrom contained
43136 ** any cells with overflow page pointers, then the corresponding pointer
43137 ** map entries are also updated so that the parent page is page pTo.
43138 **
43139 ** If pFrom is currently carrying any overflow cells (entries in the
43140 ** MemPage.aOvfl[] array), they are not copied to pTo. 
43141 **
43142 ** Before returning, page pTo is reinitialized using btreeInitPage().
43143 **
43144 ** The performance of this function is not critical. It is only used by 
43145 ** the balance_shallower() and balance_deeper() procedures, neither of
43146 ** which are called often under normal circumstances.
43147 */
43148 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
43149   if( (*pRC)==SQLITE_OK ){
43150     BtShared * const pBt = pFrom->pBt;
43151     u8 * const aFrom = pFrom->aData;
43152     u8 * const aTo = pTo->aData;
43153     int const iFromHdr = pFrom->hdrOffset;
43154     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
43155     int rc;
43156     int iData;
43157   
43158   
43159     assert( pFrom->isInit );
43160     assert( pFrom->nFree>=iToHdr );
43161     assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
43162   
43163     /* Copy the b-tree node content from page pFrom to page pTo. */
43164     iData = get2byte(&aFrom[iFromHdr+5]);
43165     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
43166     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
43167   
43168     /* Reinitialize page pTo so that the contents of the MemPage structure
43169     ** match the new data. The initialization of pTo can actually fail under
43170     ** fairly obscure circumstances, even though it is a copy of initialized 
43171     ** page pFrom.
43172     */
43173     pTo->isInit = 0;
43174     rc = btreeInitPage(pTo);
43175     if( rc!=SQLITE_OK ){
43176       *pRC = rc;
43177       return;
43178     }
43179   
43180     /* If this is an auto-vacuum database, update the pointer-map entries
43181     ** for any b-tree or overflow pages that pTo now contains the pointers to.
43182     */
43183     if( ISAUTOVACUUM ){
43184       *pRC = setChildPtrmaps(pTo);
43185     }
43186   }
43187 }
43188
43189 /*
43190 ** This routine redistributes cells on the iParentIdx'th child of pParent
43191 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
43192 ** same amount of free space. Usually a single sibling on either side of the
43193 ** page are used in the balancing, though both siblings might come from one
43194 ** side if the page is the first or last child of its parent. If the page 
43195 ** has fewer than 2 siblings (something which can only happen if the page
43196 ** is a root page or a child of a root page) then all available siblings
43197 ** participate in the balancing.
43198 **
43199 ** The number of siblings of the page might be increased or decreased by 
43200 ** one or two in an effort to keep pages nearly full but not over full. 
43201 **
43202 ** Note that when this routine is called, some of the cells on the page
43203 ** might not actually be stored in MemPage.aData[]. This can happen
43204 ** if the page is overfull. This routine ensures that all cells allocated
43205 ** to the page and its siblings fit into MemPage.aData[] before returning.
43206 **
43207 ** In the course of balancing the page and its siblings, cells may be
43208 ** inserted into or removed from the parent page (pParent). Doing so
43209 ** may cause the parent page to become overfull or underfull. If this
43210 ** happens, it is the responsibility of the caller to invoke the correct
43211 ** balancing routine to fix this problem (see the balance() routine). 
43212 **
43213 ** If this routine fails for any reason, it might leave the database
43214 ** in a corrupted state. So if this routine fails, the database should
43215 ** be rolled back.
43216 **
43217 ** The third argument to this function, aOvflSpace, is a pointer to a
43218 ** buffer big enough to hold one page. If while inserting cells into the parent
43219 ** page (pParent) the parent page becomes overfull, this buffer is
43220 ** used to store the parent's overflow cells. Because this function inserts
43221 ** a maximum of four divider cells into the parent page, and the maximum
43222 ** size of a cell stored within an internal node is always less than 1/4
43223 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
43224 ** enough for all overflow cells.
43225 **
43226 ** If aOvflSpace is set to a null pointer, this function returns 
43227 ** SQLITE_NOMEM.
43228 */
43229 static int balance_nonroot(
43230   MemPage *pParent,               /* Parent page of siblings being balanced */
43231   int iParentIdx,                 /* Index of "the page" in pParent */
43232   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
43233   int isRoot                      /* True if pParent is a root-page */
43234 ){
43235   BtShared *pBt;               /* The whole database */
43236   int nCell = 0;               /* Number of cells in apCell[] */
43237   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
43238   int nNew = 0;                /* Number of pages in apNew[] */
43239   int nOld;                    /* Number of pages in apOld[] */
43240   int i, j, k;                 /* Loop counters */
43241   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
43242   int rc = SQLITE_OK;          /* The return code */
43243   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
43244   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
43245   int usableSpace;             /* Bytes in pPage beyond the header */
43246   int pageFlags;               /* Value of pPage->aData[0] */
43247   int subtotal;                /* Subtotal of bytes in cells on one page */
43248   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
43249   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
43250   int szScratch;               /* Size of scratch memory requested */
43251   MemPage *apOld[NB];          /* pPage and up to two siblings */
43252   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
43253   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
43254   u8 *pRight;                  /* Location in parent of right-sibling pointer */
43255   u8 *apDiv[NB-1];             /* Divider cells in pParent */
43256   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
43257   int szNew[NB+2];             /* Combined size of cells place on i-th page */
43258   u8 **apCell = 0;             /* All cells begin balanced */
43259   u16 *szCell;                 /* Local size of all cells in apCell[] */
43260   u8 *aSpace1;                 /* Space for copies of dividers cells */
43261   Pgno pgno;                   /* Temp var to store a page number in */
43262
43263   pBt = pParent->pBt;
43264   assert( sqlite3_mutex_held(pBt->mutex) );
43265   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43266
43267 #if 0
43268   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
43269 #endif
43270
43271   /* At this point pParent may have at most one overflow cell. And if
43272   ** this overflow cell is present, it must be the cell with 
43273   ** index iParentIdx. This scenario comes about when this function
43274   ** is called (indirectly) from sqlite3BtreeDelete().
43275   */
43276   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
43277   assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
43278
43279   if( !aOvflSpace ){
43280     return SQLITE_NOMEM;
43281   }
43282
43283   /* Find the sibling pages to balance. Also locate the cells in pParent 
43284   ** that divide the siblings. An attempt is made to find NN siblings on 
43285   ** either side of pPage. More siblings are taken from one side, however, 
43286   ** if there are fewer than NN siblings on the other side. If pParent
43287   ** has NB or fewer children then all children of pParent are taken.  
43288   **
43289   ** This loop also drops the divider cells from the parent page. This
43290   ** way, the remainder of the function does not have to deal with any
43291   ** overflow cells in the parent page, since if any existed they will
43292   ** have already been removed.
43293   */
43294   i = pParent->nOverflow + pParent->nCell;
43295   if( i<2 ){
43296     nxDiv = 0;
43297     nOld = i+1;
43298   }else{
43299     nOld = 3;
43300     if( iParentIdx==0 ){                 
43301       nxDiv = 0;
43302     }else if( iParentIdx==i ){
43303       nxDiv = i-2;
43304     }else{
43305       nxDiv = iParentIdx-1;
43306     }
43307     i = 2;
43308   }
43309   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
43310     pRight = &pParent->aData[pParent->hdrOffset+8];
43311   }else{
43312     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
43313   }
43314   pgno = get4byte(pRight);
43315   while( 1 ){
43316     rc = getAndInitPage(pBt, pgno, &apOld[i]);
43317     if( rc ){
43318       memset(apOld, 0, (i+1)*sizeof(MemPage*));
43319       goto balance_cleanup;
43320     }
43321     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
43322     if( (i--)==0 ) break;
43323
43324     if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
43325       apDiv[i] = pParent->aOvfl[0].pCell;
43326       pgno = get4byte(apDiv[i]);
43327       szNew[i] = cellSizePtr(pParent, apDiv[i]);
43328       pParent->nOverflow = 0;
43329     }else{
43330       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
43331       pgno = get4byte(apDiv[i]);
43332       szNew[i] = cellSizePtr(pParent, apDiv[i]);
43333
43334       /* Drop the cell from the parent page. apDiv[i] still points to
43335       ** the cell within the parent, even though it has been dropped.
43336       ** This is safe because dropping a cell only overwrites the first
43337       ** four bytes of it, and this function does not need the first
43338       ** four bytes of the divider cell. So the pointer is safe to use
43339       ** later on.  
43340       **
43341       ** Unless SQLite is compiled in secure-delete mode. In this case,
43342       ** the dropCell() routine will overwrite the entire cell with zeroes.
43343       ** In this case, temporarily copy the cell into the aOvflSpace[]
43344       ** buffer. It will be copied out again as soon as the aSpace[] buffer
43345       ** is allocated.  */
43346 #ifdef SQLITE_SECURE_DELETE
43347       memcpy(&aOvflSpace[apDiv[i]-pParent->aData], apDiv[i], szNew[i]);
43348       apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
43349 #endif
43350       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
43351     }
43352   }
43353
43354   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
43355   ** alignment */
43356   nMaxCells = (nMaxCells + 3)&~3;
43357
43358   /*
43359   ** Allocate space for memory structures
43360   */
43361   k = pBt->pageSize + ROUND8(sizeof(MemPage));
43362   szScratch =
43363        nMaxCells*sizeof(u8*)                       /* apCell */
43364      + nMaxCells*sizeof(u16)                       /* szCell */
43365      + pBt->pageSize                               /* aSpace1 */
43366      + k*nOld;                                     /* Page copies (apCopy) */
43367   apCell = sqlite3ScratchMalloc( szScratch ); 
43368   if( apCell==0 ){
43369     rc = SQLITE_NOMEM;
43370     goto balance_cleanup;
43371   }
43372   szCell = (u16*)&apCell[nMaxCells];
43373   aSpace1 = (u8*)&szCell[nMaxCells];
43374   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
43375
43376   /*
43377   ** Load pointers to all cells on sibling pages and the divider cells
43378   ** into the local apCell[] array.  Make copies of the divider cells
43379   ** into space obtained from aSpace1[] and remove the the divider Cells
43380   ** from pParent.
43381   **
43382   ** If the siblings are on leaf pages, then the child pointers of the
43383   ** divider cells are stripped from the cells before they are copied
43384   ** into aSpace1[].  In this way, all cells in apCell[] are without
43385   ** child pointers.  If siblings are not leaves, then all cell in
43386   ** apCell[] include child pointers.  Either way, all cells in apCell[]
43387   ** are alike.
43388   **
43389   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
43390   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
43391   */
43392   leafCorrection = apOld[0]->leaf*4;
43393   leafData = apOld[0]->hasData;
43394   for(i=0; i<nOld; i++){
43395     int limit;
43396     
43397     /* Before doing anything else, take a copy of the i'th original sibling
43398     ** The rest of this function will use data from the copies rather
43399     ** that the original pages since the original pages will be in the
43400     ** process of being overwritten.  */
43401     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
43402     memcpy(pOld, apOld[i], sizeof(MemPage));
43403     pOld->aData = (void*)&pOld[1];
43404     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
43405
43406     limit = pOld->nCell+pOld->nOverflow;
43407     for(j=0; j<limit; j++){
43408       assert( nCell<nMaxCells );
43409       apCell[nCell] = findOverflowCell(pOld, j);
43410       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
43411       nCell++;
43412     }
43413     if( i<nOld-1 && !leafData){
43414       u16 sz = (u16)szNew[i];
43415       u8 *pTemp;
43416       assert( nCell<nMaxCells );
43417       szCell[nCell] = sz;
43418       pTemp = &aSpace1[iSpace1];
43419       iSpace1 += sz;
43420       assert( sz<=pBt->pageSize/4 );
43421       assert( iSpace1<=pBt->pageSize );
43422       memcpy(pTemp, apDiv[i], sz);
43423       apCell[nCell] = pTemp+leafCorrection;
43424       assert( leafCorrection==0 || leafCorrection==4 );
43425       szCell[nCell] = szCell[nCell] - leafCorrection;
43426       if( !pOld->leaf ){
43427         assert( leafCorrection==0 );
43428         assert( pOld->hdrOffset==0 );
43429         /* The right pointer of the child page pOld becomes the left
43430         ** pointer of the divider cell */
43431         memcpy(apCell[nCell], &pOld->aData[8], 4);
43432       }else{
43433         assert( leafCorrection==4 );
43434         if( szCell[nCell]<4 ){
43435           /* Do not allow any cells smaller than 4 bytes. */
43436           szCell[nCell] = 4;
43437         }
43438       }
43439       nCell++;
43440     }
43441   }
43442
43443   /*
43444   ** Figure out the number of pages needed to hold all nCell cells.
43445   ** Store this number in "k".  Also compute szNew[] which is the total
43446   ** size of all cells on the i-th page and cntNew[] which is the index
43447   ** in apCell[] of the cell that divides page i from page i+1.  
43448   ** cntNew[k] should equal nCell.
43449   **
43450   ** Values computed by this block:
43451   **
43452   **           k: The total number of sibling pages
43453   **    szNew[i]: Spaced used on the i-th sibling page.
43454   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
43455   **              the right of the i-th sibling page.
43456   ** usableSpace: Number of bytes of space available on each sibling.
43457   ** 
43458   */
43459   usableSpace = pBt->usableSize - 12 + leafCorrection;
43460   for(subtotal=k=i=0; i<nCell; i++){
43461     assert( i<nMaxCells );
43462     subtotal += szCell[i] + 2;
43463     if( subtotal > usableSpace ){
43464       szNew[k] = subtotal - szCell[i];
43465       cntNew[k] = i;
43466       if( leafData ){ i--; }
43467       subtotal = 0;
43468       k++;
43469       if( k>NB+1 ){ rc = SQLITE_CORRUPT; goto balance_cleanup; }
43470     }
43471   }
43472   szNew[k] = subtotal;
43473   cntNew[k] = nCell;
43474   k++;
43475
43476   /*
43477   ** The packing computed by the previous block is biased toward the siblings
43478   ** on the left side.  The left siblings are always nearly full, while the
43479   ** right-most sibling might be nearly empty.  This block of code attempts
43480   ** to adjust the packing of siblings to get a better balance.
43481   **
43482   ** This adjustment is more than an optimization.  The packing above might
43483   ** be so out of balance as to be illegal.  For example, the right-most
43484   ** sibling might be completely empty.  This adjustment is not optional.
43485   */
43486   for(i=k-1; i>0; i--){
43487     int szRight = szNew[i];  /* Size of sibling on the right */
43488     int szLeft = szNew[i-1]; /* Size of sibling on the left */
43489     int r;              /* Index of right-most cell in left sibling */
43490     int d;              /* Index of first cell to the left of right sibling */
43491
43492     r = cntNew[i-1] - 1;
43493     d = r + 1 - leafData;
43494     assert( d<nMaxCells );
43495     assert( r<nMaxCells );
43496     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
43497       szRight += szCell[d] + 2;
43498       szLeft -= szCell[r] + 2;
43499       cntNew[i-1]--;
43500       r = cntNew[i-1] - 1;
43501       d = r + 1 - leafData;
43502     }
43503     szNew[i] = szRight;
43504     szNew[i-1] = szLeft;
43505   }
43506
43507   /* Either we found one or more cells (cntnew[0])>0) or pPage is
43508   ** a virtual root page.  A virtual root page is when the real root
43509   ** page is page 1 and we are the only child of that page.
43510   */
43511   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
43512
43513   TRACE(("BALANCE: old: %d %d %d  ",
43514     apOld[0]->pgno, 
43515     nOld>=2 ? apOld[1]->pgno : 0,
43516     nOld>=3 ? apOld[2]->pgno : 0
43517   ));
43518
43519   /*
43520   ** Allocate k new pages.  Reuse old pages where possible.
43521   */
43522   if( apOld[0]->pgno<=1 ){
43523     rc = SQLITE_CORRUPT;
43524     goto balance_cleanup;
43525   }
43526   pageFlags = apOld[0]->aData[0];
43527   for(i=0; i<k; i++){
43528     MemPage *pNew;
43529     if( i<nOld ){
43530       pNew = apNew[i] = apOld[i];
43531       apOld[i] = 0;
43532       rc = sqlite3PagerWrite(pNew->pDbPage);
43533       nNew++;
43534       if( rc ) goto balance_cleanup;
43535     }else{
43536       assert( i>0 );
43537       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
43538       if( rc ) goto balance_cleanup;
43539       apNew[i] = pNew;
43540       nNew++;
43541
43542       /* Set the pointer-map entry for the new sibling page. */
43543       if( ISAUTOVACUUM ){
43544         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
43545         if( rc!=SQLITE_OK ){
43546           goto balance_cleanup;
43547         }
43548       }
43549     }
43550   }
43551
43552   /* Free any old pages that were not reused as new pages.
43553   */
43554   while( i<nOld ){
43555     freePage(apOld[i], &rc);
43556     if( rc ) goto balance_cleanup;
43557     releasePage(apOld[i]);
43558     apOld[i] = 0;
43559     i++;
43560   }
43561
43562   /*
43563   ** Put the new pages in accending order.  This helps to
43564   ** keep entries in the disk file in order so that a scan
43565   ** of the table is a linear scan through the file.  That
43566   ** in turn helps the operating system to deliver pages
43567   ** from the disk more rapidly.
43568   **
43569   ** An O(n^2) insertion sort algorithm is used, but since
43570   ** n is never more than NB (a small constant), that should
43571   ** not be a problem.
43572   **
43573   ** When NB==3, this one optimization makes the database
43574   ** about 25% faster for large insertions and deletions.
43575   */
43576   for(i=0; i<k-1; i++){
43577     int minV = apNew[i]->pgno;
43578     int minI = i;
43579     for(j=i+1; j<k; j++){
43580       if( apNew[j]->pgno<(unsigned)minV ){
43581         minI = j;
43582         minV = apNew[j]->pgno;
43583       }
43584     }
43585     if( minI>i ){
43586       int t;
43587       MemPage *pT;
43588       t = apNew[i]->pgno;
43589       pT = apNew[i];
43590       apNew[i] = apNew[minI];
43591       apNew[minI] = pT;
43592     }
43593   }
43594   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
43595     apNew[0]->pgno, szNew[0],
43596     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
43597     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
43598     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
43599     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
43600
43601   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43602   put4byte(pRight, apNew[nNew-1]->pgno);
43603
43604   /*
43605   ** Evenly distribute the data in apCell[] across the new pages.
43606   ** Insert divider cells into pParent as necessary.
43607   */
43608   j = 0;
43609   for(i=0; i<nNew; i++){
43610     /* Assemble the new sibling page. */
43611     MemPage *pNew = apNew[i];
43612     assert( j<nMaxCells );
43613     zeroPage(pNew, pageFlags);
43614     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
43615     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
43616     assert( pNew->nOverflow==0 );
43617
43618     j = cntNew[i];
43619
43620     /* If the sibling page assembled above was not the right-most sibling,
43621     ** insert a divider cell into the parent page.
43622     */
43623     assert( i<nNew-1 || j==nCell );
43624     if( j<nCell ){
43625       u8 *pCell;
43626       u8 *pTemp;
43627       int sz;
43628
43629       assert( j<nMaxCells );
43630       pCell = apCell[j];
43631       sz = szCell[j] + leafCorrection;
43632       pTemp = &aOvflSpace[iOvflSpace];
43633       if( !pNew->leaf ){
43634         memcpy(&pNew->aData[8], pCell, 4);
43635       }else if( leafData ){
43636         /* If the tree is a leaf-data tree, and the siblings are leaves, 
43637         ** then there is no divider cell in apCell[]. Instead, the divider 
43638         ** cell consists of the integer key for the right-most cell of 
43639         ** the sibling-page assembled above only.
43640         */
43641         CellInfo info;
43642         j--;
43643         btreeParseCellPtr(pNew, apCell[j], &info);
43644         pCell = pTemp;
43645         sz = 4 + putVarint(&pCell[4], info.nKey);
43646         pTemp = 0;
43647       }else{
43648         pCell -= 4;
43649         /* Obscure case for non-leaf-data trees: If the cell at pCell was
43650         ** previously stored on a leaf node, and its reported size was 4
43651         ** bytes, then it may actually be smaller than this 
43652         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
43653         ** any cell). But it is important to pass the correct size to 
43654         ** insertCell(), so reparse the cell now.
43655         **
43656         ** Note that this can never happen in an SQLite data file, as all
43657         ** cells are at least 4 bytes. It only happens in b-trees used
43658         ** to evaluate "IN (SELECT ...)" and similar clauses.
43659         */
43660         if( szCell[j]==4 ){
43661           assert(leafCorrection==4);
43662           sz = cellSizePtr(pParent, pCell);
43663         }
43664       }
43665       iOvflSpace += sz;
43666       assert( sz<=pBt->pageSize/4 );
43667       assert( iOvflSpace<=pBt->pageSize );
43668       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
43669       if( rc!=SQLITE_OK ) goto balance_cleanup;
43670       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43671
43672       j++;
43673       nxDiv++;
43674     }
43675   }
43676   assert( j==nCell );
43677   assert( nOld>0 );
43678   assert( nNew>0 );
43679   if( (pageFlags & PTF_LEAF)==0 ){
43680     u8 *zChild = &apCopy[nOld-1]->aData[8];
43681     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
43682   }
43683
43684   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
43685     /* The root page of the b-tree now contains no cells. The only sibling
43686     ** page is the right-child of the parent. Copy the contents of the
43687     ** child page into the parent, decreasing the overall height of the
43688     ** b-tree structure by one. This is described as the "balance-shallower"
43689     ** sub-algorithm in some documentation.
43690     **
43691     ** If this is an auto-vacuum database, the call to copyNodeContent() 
43692     ** sets all pointer-map entries corresponding to database image pages 
43693     ** for which the pointer is stored within the content being copied.
43694     **
43695     ** The second assert below verifies that the child page is defragmented
43696     ** (it must be, as it was just reconstructed using assemblePage()). This
43697     ** is important if the parent page happens to be page 1 of the database
43698     ** image.  */
43699     assert( nNew==1 );
43700     assert( apNew[0]->nFree == 
43701         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
43702     );
43703     copyNodeContent(apNew[0], pParent, &rc);
43704     freePage(apNew[0], &rc);
43705   }else if( ISAUTOVACUUM ){
43706     /* Fix the pointer-map entries for all the cells that were shifted around. 
43707     ** There are several different types of pointer-map entries that need to
43708     ** be dealt with by this routine. Some of these have been set already, but
43709     ** many have not. The following is a summary:
43710     **
43711     **   1) The entries associated with new sibling pages that were not
43712     **      siblings when this function was called. These have already
43713     **      been set. We don't need to worry about old siblings that were
43714     **      moved to the free-list - the freePage() code has taken care
43715     **      of those.
43716     **
43717     **   2) The pointer-map entries associated with the first overflow
43718     **      page in any overflow chains used by new divider cells. These 
43719     **      have also already been taken care of by the insertCell() code.
43720     **
43721     **   3) If the sibling pages are not leaves, then the child pages of
43722     **      cells stored on the sibling pages may need to be updated.
43723     **
43724     **   4) If the sibling pages are not internal intkey nodes, then any
43725     **      overflow pages used by these cells may need to be updated
43726     **      (internal intkey nodes never contain pointers to overflow pages).
43727     **
43728     **   5) If the sibling pages are not leaves, then the pointer-map
43729     **      entries for the right-child pages of each sibling may need
43730     **      to be updated.
43731     **
43732     ** Cases 1 and 2 are dealt with above by other code. The next
43733     ** block deals with cases 3 and 4 and the one after that, case 5. Since
43734     ** setting a pointer map entry is a relatively expensive operation, this
43735     ** code only sets pointer map entries for child or overflow pages that have
43736     ** actually moved between pages.  */
43737     MemPage *pNew = apNew[0];
43738     MemPage *pOld = apCopy[0];
43739     int nOverflow = pOld->nOverflow;
43740     int iNextOld = pOld->nCell + nOverflow;
43741     int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
43742     j = 0;                             /* Current 'old' sibling page */
43743     k = 0;                             /* Current 'new' sibling page */
43744     for(i=0; i<nCell; i++){
43745       int isDivider = 0;
43746       while( i==iNextOld ){
43747         /* Cell i is the cell immediately following the last cell on old
43748         ** sibling page j. If the siblings are not leaf pages of an
43749         ** intkey b-tree, then cell i was a divider cell. */
43750         pOld = apCopy[++j];
43751         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
43752         if( pOld->nOverflow ){
43753           nOverflow = pOld->nOverflow;
43754           iOverflow = i + !leafData + pOld->aOvfl[0].idx;
43755         }
43756         isDivider = !leafData;  
43757       }
43758
43759       assert(nOverflow>0 || iOverflow<i );
43760       assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
43761       assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
43762       if( i==iOverflow ){
43763         isDivider = 1;
43764         if( (--nOverflow)>0 ){
43765           iOverflow++;
43766         }
43767       }
43768
43769       if( i==cntNew[k] ){
43770         /* Cell i is the cell immediately following the last cell on new
43771         ** sibling page k. If the siblings are not leaf pages of an
43772         ** intkey b-tree, then cell i is a divider cell.  */
43773         pNew = apNew[++k];
43774         if( !leafData ) continue;
43775       }
43776       assert( j<nOld );
43777       assert( k<nNew );
43778
43779       /* If the cell was originally divider cell (and is not now) or
43780       ** an overflow cell, or if the cell was located on a different sibling
43781       ** page before the balancing, then the pointer map entries associated
43782       ** with any child or overflow pages need to be updated.  */
43783       if( isDivider || pOld->pgno!=pNew->pgno ){
43784         if( !leafCorrection ){
43785           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
43786         }
43787         if( szCell[i]>pNew->minLocal ){
43788           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
43789         }
43790       }
43791     }
43792
43793     if( !leafCorrection ){
43794       for(i=0; i<nNew; i++){
43795         u32 key = get4byte(&apNew[i]->aData[8]);
43796         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
43797       }
43798     }
43799
43800 #if 0
43801     /* The ptrmapCheckPages() contains assert() statements that verify that
43802     ** all pointer map pages are set correctly. This is helpful while 
43803     ** debugging. This is usually disabled because a corrupt database may
43804     ** cause an assert() statement to fail.  */
43805     ptrmapCheckPages(apNew, nNew);
43806     ptrmapCheckPages(&pParent, 1);
43807 #endif
43808   }
43809
43810   assert( pParent->isInit );
43811   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
43812           nOld, nNew, nCell));
43813
43814   /*
43815   ** Cleanup before returning.
43816   */
43817 balance_cleanup:
43818   sqlite3ScratchFree(apCell);
43819   for(i=0; i<nOld; i++){
43820     releasePage(apOld[i]);
43821   }
43822   for(i=0; i<nNew; i++){
43823     releasePage(apNew[i]);
43824   }
43825
43826   return rc;
43827 }
43828
43829
43830 /*
43831 ** This function is called when the root page of a b-tree structure is
43832 ** overfull (has one or more overflow pages).
43833 **
43834 ** A new child page is allocated and the contents of the current root
43835 ** page, including overflow cells, are copied into the child. The root
43836 ** page is then overwritten to make it an empty page with the right-child 
43837 ** pointer pointing to the new page.
43838 **
43839 ** Before returning, all pointer-map entries corresponding to pages 
43840 ** that the new child-page now contains pointers to are updated. The
43841 ** entry corresponding to the new right-child pointer of the root
43842 ** page is also updated.
43843 **
43844 ** If successful, *ppChild is set to contain a reference to the child 
43845 ** page and SQLITE_OK is returned. In this case the caller is required
43846 ** to call releasePage() on *ppChild exactly once. If an error occurs,
43847 ** an error code is returned and *ppChild is set to 0.
43848 */
43849 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
43850   int rc;                        /* Return value from subprocedures */
43851   MemPage *pChild = 0;           /* Pointer to a new child page */
43852   Pgno pgnoChild = 0;            /* Page number of the new child page */
43853   BtShared *pBt = pRoot->pBt;    /* The BTree */
43854
43855   assert( pRoot->nOverflow>0 );
43856   assert( sqlite3_mutex_held(pBt->mutex) );
43857
43858   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
43859   ** page that will become the new right-child of pPage. Copy the contents
43860   ** of the node stored on pRoot into the new child page.
43861   */
43862   rc = sqlite3PagerWrite(pRoot->pDbPage);
43863   if( rc==SQLITE_OK ){
43864     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
43865     copyNodeContent(pRoot, pChild, &rc);
43866     if( ISAUTOVACUUM ){
43867       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
43868     }
43869   }
43870   if( rc ){
43871     *ppChild = 0;
43872     releasePage(pChild);
43873     return rc;
43874   }
43875   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
43876   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
43877   assert( pChild->nCell==pRoot->nCell );
43878
43879   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
43880
43881   /* Copy the overflow cells from pRoot to pChild */
43882   memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
43883   pChild->nOverflow = pRoot->nOverflow;
43884
43885   /* Zero the contents of pRoot. Then install pChild as the right-child. */
43886   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
43887   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
43888
43889   *ppChild = pChild;
43890   return SQLITE_OK;
43891 }
43892
43893 /*
43894 ** The page that pCur currently points to has just been modified in
43895 ** some way. This function figures out if this modification means the
43896 ** tree needs to be balanced, and if so calls the appropriate balancing 
43897 ** routine. Balancing routines are:
43898 **
43899 **   balance_quick()
43900 **   balance_deeper()
43901 **   balance_nonroot()
43902 */
43903 static int balance(BtCursor *pCur){
43904   int rc = SQLITE_OK;
43905   const int nMin = pCur->pBt->usableSize * 2 / 3;
43906   u8 aBalanceQuickSpace[13];
43907   u8 *pFree = 0;
43908
43909   TESTONLY( int balance_quick_called = 0 );
43910   TESTONLY( int balance_deeper_called = 0 );
43911
43912   do {
43913     int iPage = pCur->iPage;
43914     MemPage *pPage = pCur->apPage[iPage];
43915
43916     if( iPage==0 ){
43917       if( pPage->nOverflow ){
43918         /* The root page of the b-tree is overfull. In this case call the
43919         ** balance_deeper() function to create a new child for the root-page
43920         ** and copy the current contents of the root-page to it. The
43921         ** next iteration of the do-loop will balance the child page.
43922         */ 
43923         assert( (balance_deeper_called++)==0 );
43924         rc = balance_deeper(pPage, &pCur->apPage[1]);
43925         if( rc==SQLITE_OK ){
43926           pCur->iPage = 1;
43927           pCur->aiIdx[0] = 0;
43928           pCur->aiIdx[1] = 0;
43929           assert( pCur->apPage[1]->nOverflow );
43930         }
43931       }else{
43932         break;
43933       }
43934     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
43935       break;
43936     }else{
43937       MemPage * const pParent = pCur->apPage[iPage-1];
43938       int const iIdx = pCur->aiIdx[iPage-1];
43939
43940       rc = sqlite3PagerWrite(pParent->pDbPage);
43941       if( rc==SQLITE_OK ){
43942 #ifndef SQLITE_OMIT_QUICKBALANCE
43943         if( pPage->hasData
43944          && pPage->nOverflow==1
43945          && pPage->aOvfl[0].idx==pPage->nCell
43946          && pParent->pgno!=1
43947          && pParent->nCell==iIdx
43948         ){
43949           /* Call balance_quick() to create a new sibling of pPage on which
43950           ** to store the overflow cell. balance_quick() inserts a new cell
43951           ** into pParent, which may cause pParent overflow. If this
43952           ** happens, the next interation of the do-loop will balance pParent 
43953           ** use either balance_nonroot() or balance_deeper(). Until this
43954           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
43955           ** buffer. 
43956           **
43957           ** The purpose of the following assert() is to check that only a
43958           ** single call to balance_quick() is made for each call to this
43959           ** function. If this were not verified, a subtle bug involving reuse
43960           ** of the aBalanceQuickSpace[] might sneak in.
43961           */
43962           assert( (balance_quick_called++)==0 );
43963           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
43964         }else
43965 #endif
43966         {
43967           /* In this case, call balance_nonroot() to redistribute cells
43968           ** between pPage and up to 2 of its sibling pages. This involves
43969           ** modifying the contents of pParent, which may cause pParent to
43970           ** become overfull or underfull. The next iteration of the do-loop
43971           ** will balance the parent page to correct this.
43972           ** 
43973           ** If the parent page becomes overfull, the overflow cell or cells
43974           ** are stored in the pSpace buffer allocated immediately below. 
43975           ** A subsequent iteration of the do-loop will deal with this by
43976           ** calling balance_nonroot() (balance_deeper() may be called first,
43977           ** but it doesn't deal with overflow cells - just moves them to a
43978           ** different page). Once this subsequent call to balance_nonroot() 
43979           ** has completed, it is safe to release the pSpace buffer used by
43980           ** the previous call, as the overflow cell data will have been 
43981           ** copied either into the body of a database page or into the new
43982           ** pSpace buffer passed to the latter call to balance_nonroot().
43983           */
43984           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
43985           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
43986           if( pFree ){
43987             /* If pFree is not NULL, it points to the pSpace buffer used 
43988             ** by a previous call to balance_nonroot(). Its contents are
43989             ** now stored either on real database pages or within the 
43990             ** new pSpace buffer, so it may be safely freed here. */
43991             sqlite3PageFree(pFree);
43992           }
43993
43994           /* The pSpace buffer will be freed after the next call to
43995           ** balance_nonroot(), or just before this function returns, whichever
43996           ** comes first. */
43997           pFree = pSpace;
43998         }
43999       }
44000
44001       pPage->nOverflow = 0;
44002
44003       /* The next iteration of the do-loop balances the parent page. */
44004       releasePage(pPage);
44005       pCur->iPage--;
44006     }
44007   }while( rc==SQLITE_OK );
44008
44009   if( pFree ){
44010     sqlite3PageFree(pFree);
44011   }
44012   return rc;
44013 }
44014
44015
44016 /*
44017 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
44018 ** and the data is given by (pData,nData).  The cursor is used only to
44019 ** define what table the record should be inserted into.  The cursor
44020 ** is left pointing at a random location.
44021 **
44022 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
44023 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
44024 **
44025 ** If the seekResult parameter is non-zero, then a successful call to
44026 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
44027 ** been performed. seekResult is the search result returned (a negative
44028 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
44029 ** a positive value if pCur points at an etry that is larger than 
44030 ** (pKey, nKey)). 
44031 **
44032 ** If the seekResult parameter is non-zero, then the caller guarantees that
44033 ** cursor pCur is pointing at the existing copy of a row that is to be
44034 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
44035 ** point to any entry or to no entry at all and so this function has to seek
44036 ** the cursor before the new key can be inserted.
44037 */
44038 SQLITE_PRIVATE int sqlite3BtreeInsert(
44039   BtCursor *pCur,                /* Insert data into the table of this cursor */
44040   const void *pKey, i64 nKey,    /* The key of the new record */
44041   const void *pData, int nData,  /* The data of the new record */
44042   int nZero,                     /* Number of extra 0 bytes to append to data */
44043   int appendBias,                /* True if this is likely an append */
44044   int seekResult                 /* Result of prior MovetoUnpacked() call */
44045 ){
44046   int rc;
44047   int loc = seekResult;          /* -1: before desired location  +1: after */
44048   int szNew = 0;
44049   int idx;
44050   MemPage *pPage;
44051   Btree *p = pCur->pBtree;
44052   BtShared *pBt = p->pBt;
44053   unsigned char *oldCell;
44054   unsigned char *newCell = 0;
44055
44056   if( pCur->eState==CURSOR_FAULT ){
44057     assert( pCur->skipNext!=SQLITE_OK );
44058     return pCur->skipNext;
44059   }
44060
44061   assert( cursorHoldsMutex(pCur) );
44062   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
44063   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
44064
44065   /* Assert that the caller has been consistent. If this cursor was opened
44066   ** expecting an index b-tree, then the caller should be inserting blob
44067   ** keys with no associated data. If the cursor was opened expecting an
44068   ** intkey table, the caller should be inserting integer keys with a
44069   ** blob of associated data.  */
44070   assert( (pKey==0)==(pCur->pKeyInfo==0) );
44071
44072   /* If this is an insert into a table b-tree, invalidate any incrblob 
44073   ** cursors open on the row being replaced (assuming this is a replace
44074   ** operation - if it is not, the following is a no-op).  */
44075   if( pCur->pKeyInfo==0 ){
44076     invalidateIncrblobCursors(p, nKey, 0);
44077   }
44078
44079   /* Save the positions of any other cursors open on this table.
44080   **
44081   ** In some cases, the call to btreeMoveto() below is a no-op. For
44082   ** example, when inserting data into a table with auto-generated integer
44083   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
44084   ** integer key to use. It then calls this function to actually insert the 
44085   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
44086   ** that the cursor is already where it needs to be and returns without
44087   ** doing any work. To avoid thwarting these optimizations, it is important
44088   ** not to clear the cursor here.
44089   */
44090   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
44091   if( rc ) return rc;
44092   if( !loc ){
44093     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
44094     if( rc ) return rc;
44095   }
44096   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
44097
44098   pPage = pCur->apPage[pCur->iPage];
44099   assert( pPage->intKey || nKey>=0 );
44100   assert( pPage->leaf || !pPage->intKey );
44101
44102   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
44103           pCur->pgnoRoot, nKey, nData, pPage->pgno,
44104           loc==0 ? "overwrite" : "new entry"));
44105   assert( pPage->isInit );
44106   allocateTempSpace(pBt);
44107   newCell = pBt->pTmpSpace;
44108   if( newCell==0 ) return SQLITE_NOMEM;
44109   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
44110   if( rc ) goto end_insert;
44111   assert( szNew==cellSizePtr(pPage, newCell) );
44112   assert( szNew<=MX_CELL_SIZE(pBt) );
44113   idx = pCur->aiIdx[pCur->iPage];
44114   if( loc==0 ){
44115     u16 szOld;
44116     assert( idx<pPage->nCell );
44117     rc = sqlite3PagerWrite(pPage->pDbPage);
44118     if( rc ){
44119       goto end_insert;
44120     }
44121     oldCell = findCell(pPage, idx);
44122     if( !pPage->leaf ){
44123       memcpy(newCell, oldCell, 4);
44124     }
44125     szOld = cellSizePtr(pPage, oldCell);
44126     rc = clearCell(pPage, oldCell);
44127     dropCell(pPage, idx, szOld, &rc);
44128     if( rc ) goto end_insert;
44129   }else if( loc<0 && pPage->nCell>0 ){
44130     assert( pPage->leaf );
44131     idx = ++pCur->aiIdx[pCur->iPage];
44132   }else{
44133     assert( pPage->leaf );
44134   }
44135   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
44136   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
44137
44138   /* If no error has occured and pPage has an overflow cell, call balance() 
44139   ** to redistribute the cells within the tree. Since balance() may move
44140   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
44141   ** variables.
44142   **
44143   ** Previous versions of SQLite called moveToRoot() to move the cursor
44144   ** back to the root page as balance() used to invalidate the contents
44145   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
44146   ** set the cursor state to "invalid". This makes common insert operations
44147   ** slightly faster.
44148   **
44149   ** There is a subtle but important optimization here too. When inserting
44150   ** multiple records into an intkey b-tree using a single cursor (as can
44151   ** happen while processing an "INSERT INTO ... SELECT" statement), it
44152   ** is advantageous to leave the cursor pointing to the last entry in
44153   ** the b-tree if possible. If the cursor is left pointing to the last
44154   ** entry in the table, and the next row inserted has an integer key
44155   ** larger than the largest existing key, it is possible to insert the
44156   ** row without seeking the cursor. This can be a big performance boost.
44157   */
44158   pCur->info.nSize = 0;
44159   pCur->validNKey = 0;
44160   if( rc==SQLITE_OK && pPage->nOverflow ){
44161     rc = balance(pCur);
44162
44163     /* Must make sure nOverflow is reset to zero even if the balance()
44164     ** fails. Internal data structure corruption will result otherwise. 
44165     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
44166     ** from trying to save the current position of the cursor.  */
44167     pCur->apPage[pCur->iPage]->nOverflow = 0;
44168     pCur->eState = CURSOR_INVALID;
44169   }
44170   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
44171
44172 end_insert:
44173   return rc;
44174 }
44175
44176 /*
44177 ** Delete the entry that the cursor is pointing to.  The cursor
44178 ** is left pointing at a arbitrary location.
44179 */
44180 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
44181   Btree *p = pCur->pBtree;
44182   BtShared *pBt = p->pBt;              
44183   int rc;                              /* Return code */
44184   MemPage *pPage;                      /* Page to delete cell from */
44185   unsigned char *pCell;                /* Pointer to cell to delete */
44186   int iCellIdx;                        /* Index of cell to delete */
44187   int iCellDepth;                      /* Depth of node containing pCell */ 
44188
44189   assert( cursorHoldsMutex(pCur) );
44190   assert( pBt->inTransaction==TRANS_WRITE );
44191   assert( !pBt->readOnly );
44192   assert( pCur->wrFlag );
44193   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
44194   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
44195
44196   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
44197    || NEVER(pCur->eState!=CURSOR_VALID)
44198   ){
44199     return SQLITE_ERROR;  /* Something has gone awry. */
44200   }
44201
44202   /* If this is a delete operation to remove a row from a table b-tree,
44203   ** invalidate any incrblob cursors open on the row being deleted.  */
44204   if( pCur->pKeyInfo==0 ){
44205     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
44206   }
44207
44208   iCellDepth = pCur->iPage;
44209   iCellIdx = pCur->aiIdx[iCellDepth];
44210   pPage = pCur->apPage[iCellDepth];
44211   pCell = findCell(pPage, iCellIdx);
44212
44213   /* If the page containing the entry to delete is not a leaf page, move
44214   ** the cursor to the largest entry in the tree that is smaller than
44215   ** the entry being deleted. This cell will replace the cell being deleted
44216   ** from the internal node. The 'previous' entry is used for this instead
44217   ** of the 'next' entry, as the previous entry is always a part of the
44218   ** sub-tree headed by the child page of the cell being deleted. This makes
44219   ** balancing the tree following the delete operation easier.  */
44220   if( !pPage->leaf ){
44221     int notUsed;
44222     rc = sqlite3BtreePrevious(pCur, &notUsed);
44223     if( rc ) return rc;
44224   }
44225
44226   /* Save the positions of any other cursors open on this table before
44227   ** making any modifications. Make the page containing the entry to be 
44228   ** deleted writable. Then free any overflow pages associated with the 
44229   ** entry and finally remove the cell itself from within the page.  
44230   */
44231   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
44232   if( rc ) return rc;
44233   rc = sqlite3PagerWrite(pPage->pDbPage);
44234   if( rc ) return rc;
44235   rc = clearCell(pPage, pCell);
44236   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
44237   if( rc ) return rc;
44238
44239   /* If the cell deleted was not located on a leaf page, then the cursor
44240   ** is currently pointing to the largest entry in the sub-tree headed
44241   ** by the child-page of the cell that was just deleted from an internal
44242   ** node. The cell from the leaf node needs to be moved to the internal
44243   ** node to replace the deleted cell.  */
44244   if( !pPage->leaf ){
44245     MemPage *pLeaf = pCur->apPage[pCur->iPage];
44246     int nCell;
44247     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
44248     unsigned char *pTmp;
44249
44250     pCell = findCell(pLeaf, pLeaf->nCell-1);
44251     nCell = cellSizePtr(pLeaf, pCell);
44252     assert( MX_CELL_SIZE(pBt)>=nCell );
44253
44254     allocateTempSpace(pBt);
44255     pTmp = pBt->pTmpSpace;
44256
44257     rc = sqlite3PagerWrite(pLeaf->pDbPage);
44258     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
44259     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
44260     if( rc ) return rc;
44261   }
44262
44263   /* Balance the tree. If the entry deleted was located on a leaf page,
44264   ** then the cursor still points to that page. In this case the first
44265   ** call to balance() repairs the tree, and the if(...) condition is
44266   ** never true.
44267   **
44268   ** Otherwise, if the entry deleted was on an internal node page, then
44269   ** pCur is pointing to the leaf page from which a cell was removed to
44270   ** replace the cell deleted from the internal node. This is slightly
44271   ** tricky as the leaf node may be underfull, and the internal node may
44272   ** be either under or overfull. In this case run the balancing algorithm
44273   ** on the leaf node first. If the balance proceeds far enough up the
44274   ** tree that we can be sure that any problem in the internal node has
44275   ** been corrected, so be it. Otherwise, after balancing the leaf node,
44276   ** walk the cursor up the tree to the internal node and balance it as 
44277   ** well.  */
44278   rc = balance(pCur);
44279   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
44280     while( pCur->iPage>iCellDepth ){
44281       releasePage(pCur->apPage[pCur->iPage--]);
44282     }
44283     rc = balance(pCur);
44284   }
44285
44286   if( rc==SQLITE_OK ){
44287     moveToRoot(pCur);
44288   }
44289   return rc;
44290 }
44291
44292 /*
44293 ** Create a new BTree table.  Write into *piTable the page
44294 ** number for the root page of the new table.
44295 **
44296 ** The type of type is determined by the flags parameter.  Only the
44297 ** following values of flags are currently in use.  Other values for
44298 ** flags might not work:
44299 **
44300 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
44301 **     BTREE_ZERODATA                  Used for SQL indices
44302 */
44303 static int btreeCreateTable(Btree *p, int *piTable, int flags){
44304   BtShared *pBt = p->pBt;
44305   MemPage *pRoot;
44306   Pgno pgnoRoot;
44307   int rc;
44308
44309   assert( sqlite3BtreeHoldsMutex(p) );
44310   assert( pBt->inTransaction==TRANS_WRITE );
44311   assert( !pBt->readOnly );
44312
44313 #ifdef SQLITE_OMIT_AUTOVACUUM
44314   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
44315   if( rc ){
44316     return rc;
44317   }
44318 #else
44319   if( pBt->autoVacuum ){
44320     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
44321     MemPage *pPageMove; /* The page to move to. */
44322
44323     /* Creating a new table may probably require moving an existing database
44324     ** to make room for the new tables root page. In case this page turns
44325     ** out to be an overflow page, delete all overflow page-map caches
44326     ** held by open cursors.
44327     */
44328     invalidateAllOverflowCache(pBt);
44329
44330     /* Read the value of meta[3] from the database to determine where the
44331     ** root page of the new table should go. meta[3] is the largest root-page
44332     ** created so far, so the new root-page is (meta[3]+1).
44333     */
44334     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
44335     pgnoRoot++;
44336
44337     /* The new root-page may not be allocated on a pointer-map page, or the
44338     ** PENDING_BYTE page.
44339     */
44340     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
44341         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
44342       pgnoRoot++;
44343     }
44344     assert( pgnoRoot>=3 );
44345
44346     /* Allocate a page. The page that currently resides at pgnoRoot will
44347     ** be moved to the allocated page (unless the allocated page happens
44348     ** to reside at pgnoRoot).
44349     */
44350     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
44351     if( rc!=SQLITE_OK ){
44352       return rc;
44353     }
44354
44355     if( pgnoMove!=pgnoRoot ){
44356       /* pgnoRoot is the page that will be used for the root-page of
44357       ** the new table (assuming an error did not occur). But we were
44358       ** allocated pgnoMove. If required (i.e. if it was not allocated
44359       ** by extending the file), the current page at position pgnoMove
44360       ** is already journaled.
44361       */
44362       u8 eType = 0;
44363       Pgno iPtrPage = 0;
44364
44365       releasePage(pPageMove);
44366
44367       /* Move the page currently at pgnoRoot to pgnoMove. */
44368       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
44369       if( rc!=SQLITE_OK ){
44370         return rc;
44371       }
44372       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
44373       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
44374         rc = SQLITE_CORRUPT_BKPT;
44375       }
44376       if( rc!=SQLITE_OK ){
44377         releasePage(pRoot);
44378         return rc;
44379       }
44380       assert( eType!=PTRMAP_ROOTPAGE );
44381       assert( eType!=PTRMAP_FREEPAGE );
44382       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
44383       releasePage(pRoot);
44384
44385       /* Obtain the page at pgnoRoot */
44386       if( rc!=SQLITE_OK ){
44387         return rc;
44388       }
44389       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
44390       if( rc!=SQLITE_OK ){
44391         return rc;
44392       }
44393       rc = sqlite3PagerWrite(pRoot->pDbPage);
44394       if( rc!=SQLITE_OK ){
44395         releasePage(pRoot);
44396         return rc;
44397       }
44398     }else{
44399       pRoot = pPageMove;
44400     } 
44401
44402     /* Update the pointer-map and meta-data with the new root-page number. */
44403     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
44404     if( rc ){
44405       releasePage(pRoot);
44406       return rc;
44407     }
44408     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
44409     if( rc ){
44410       releasePage(pRoot);
44411       return rc;
44412     }
44413
44414   }else{
44415     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
44416     if( rc ) return rc;
44417   }
44418 #endif
44419   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
44420   zeroPage(pRoot, flags | PTF_LEAF);
44421   sqlite3PagerUnref(pRoot->pDbPage);
44422   *piTable = (int)pgnoRoot;
44423   return SQLITE_OK;
44424 }
44425 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
44426   int rc;
44427   sqlite3BtreeEnter(p);
44428   rc = btreeCreateTable(p, piTable, flags);
44429   sqlite3BtreeLeave(p);
44430   return rc;
44431 }
44432
44433 /*
44434 ** Erase the given database page and all its children.  Return
44435 ** the page to the freelist.
44436 */
44437 static int clearDatabasePage(
44438   BtShared *pBt,           /* The BTree that contains the table */
44439   Pgno pgno,               /* Page number to clear */
44440   int freePageFlag,        /* Deallocate page if true */
44441   int *pnChange            /* Add number of Cells freed to this counter */
44442 ){
44443   MemPage *pPage;
44444   int rc;
44445   unsigned char *pCell;
44446   int i;
44447
44448   assert( sqlite3_mutex_held(pBt->mutex) );
44449   if( pgno>pagerPagecount(pBt) ){
44450     return SQLITE_CORRUPT_BKPT;
44451   }
44452
44453   rc = getAndInitPage(pBt, pgno, &pPage);
44454   if( rc ) return rc;
44455   for(i=0; i<pPage->nCell; i++){
44456     pCell = findCell(pPage, i);
44457     if( !pPage->leaf ){
44458       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
44459       if( rc ) goto cleardatabasepage_out;
44460     }
44461     rc = clearCell(pPage, pCell);
44462     if( rc ) goto cleardatabasepage_out;
44463   }
44464   if( !pPage->leaf ){
44465     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
44466     if( rc ) goto cleardatabasepage_out;
44467   }else if( pnChange ){
44468     assert( pPage->intKey );
44469     *pnChange += pPage->nCell;
44470   }
44471   if( freePageFlag ){
44472     freePage(pPage, &rc);
44473   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
44474     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
44475   }
44476
44477 cleardatabasepage_out:
44478   releasePage(pPage);
44479   return rc;
44480 }
44481
44482 /*
44483 ** Delete all information from a single table in the database.  iTable is
44484 ** the page number of the root of the table.  After this routine returns,
44485 ** the root page is empty, but still exists.
44486 **
44487 ** This routine will fail with SQLITE_LOCKED if there are any open
44488 ** read cursors on the table.  Open write cursors are moved to the
44489 ** root of the table.
44490 **
44491 ** If pnChange is not NULL, then table iTable must be an intkey table. The
44492 ** integer value pointed to by pnChange is incremented by the number of
44493 ** entries in the table.
44494 */
44495 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
44496   int rc;
44497   BtShared *pBt = p->pBt;
44498   sqlite3BtreeEnter(p);
44499   assert( p->inTrans==TRANS_WRITE );
44500
44501   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
44502   ** is the root of a table b-tree - if it is not, the following call is
44503   ** a no-op).  */
44504   invalidateIncrblobCursors(p, 0, 1);
44505
44506   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
44507   if( SQLITE_OK==rc ){
44508     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
44509   }
44510   sqlite3BtreeLeave(p);
44511   return rc;
44512 }
44513
44514 /*
44515 ** Erase all information in a table and add the root of the table to
44516 ** the freelist.  Except, the root of the principle table (the one on
44517 ** page 1) is never added to the freelist.
44518 **
44519 ** This routine will fail with SQLITE_LOCKED if there are any open
44520 ** cursors on the table.
44521 **
44522 ** If AUTOVACUUM is enabled and the page at iTable is not the last
44523 ** root page in the database file, then the last root page 
44524 ** in the database file is moved into the slot formerly occupied by
44525 ** iTable and that last slot formerly occupied by the last root page
44526 ** is added to the freelist instead of iTable.  In this say, all
44527 ** root pages are kept at the beginning of the database file, which
44528 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
44529 ** page number that used to be the last root page in the file before
44530 ** the move.  If no page gets moved, *piMoved is set to 0.
44531 ** The last root page is recorded in meta[3] and the value of
44532 ** meta[3] is updated by this procedure.
44533 */
44534 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
44535   int rc;
44536   MemPage *pPage = 0;
44537   BtShared *pBt = p->pBt;
44538
44539   assert( sqlite3BtreeHoldsMutex(p) );
44540   assert( p->inTrans==TRANS_WRITE );
44541
44542   /* It is illegal to drop a table if any cursors are open on the
44543   ** database. This is because in auto-vacuum mode the backend may
44544   ** need to move another root-page to fill a gap left by the deleted
44545   ** root page. If an open cursor was using this page a problem would 
44546   ** occur.
44547   **
44548   ** This error is caught long before control reaches this point.
44549   */
44550   if( NEVER(pBt->pCursor) ){
44551     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
44552     return SQLITE_LOCKED_SHAREDCACHE;
44553   }
44554
44555   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
44556   if( rc ) return rc;
44557   rc = sqlite3BtreeClearTable(p, iTable, 0);
44558   if( rc ){
44559     releasePage(pPage);
44560     return rc;
44561   }
44562
44563   *piMoved = 0;
44564
44565   if( iTable>1 ){
44566 #ifdef SQLITE_OMIT_AUTOVACUUM
44567     freePage(pPage, &rc);
44568     releasePage(pPage);
44569 #else
44570     if( pBt->autoVacuum ){
44571       Pgno maxRootPgno;
44572       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
44573
44574       if( iTable==maxRootPgno ){
44575         /* If the table being dropped is the table with the largest root-page
44576         ** number in the database, put the root page on the free list. 
44577         */
44578         freePage(pPage, &rc);
44579         releasePage(pPage);
44580         if( rc!=SQLITE_OK ){
44581           return rc;
44582         }
44583       }else{
44584         /* The table being dropped does not have the largest root-page
44585         ** number in the database. So move the page that does into the 
44586         ** gap left by the deleted root-page.
44587         */
44588         MemPage *pMove;
44589         releasePage(pPage);
44590         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
44591         if( rc!=SQLITE_OK ){
44592           return rc;
44593         }
44594         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
44595         releasePage(pMove);
44596         if( rc!=SQLITE_OK ){
44597           return rc;
44598         }
44599         pMove = 0;
44600         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
44601         freePage(pMove, &rc);
44602         releasePage(pMove);
44603         if( rc!=SQLITE_OK ){
44604           return rc;
44605         }
44606         *piMoved = maxRootPgno;
44607       }
44608
44609       /* Set the new 'max-root-page' value in the database header. This
44610       ** is the old value less one, less one more if that happens to
44611       ** be a root-page number, less one again if that is the
44612       ** PENDING_BYTE_PAGE.
44613       */
44614       maxRootPgno--;
44615       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
44616              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
44617         maxRootPgno--;
44618       }
44619       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
44620
44621       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
44622     }else{
44623       freePage(pPage, &rc);
44624       releasePage(pPage);
44625     }
44626 #endif
44627   }else{
44628     /* If sqlite3BtreeDropTable was called on page 1.
44629     ** This really never should happen except in a corrupt
44630     ** database. 
44631     */
44632     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
44633     releasePage(pPage);
44634   }
44635   return rc;  
44636 }
44637 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
44638   int rc;
44639   sqlite3BtreeEnter(p);
44640   rc = btreeDropTable(p, iTable, piMoved);
44641   sqlite3BtreeLeave(p);
44642   return rc;
44643 }
44644
44645
44646 /*
44647 ** This function may only be called if the b-tree connection already
44648 ** has a read or write transaction open on the database.
44649 **
44650 ** Read the meta-information out of a database file.  Meta[0]
44651 ** is the number of free pages currently in the database.  Meta[1]
44652 ** through meta[15] are available for use by higher layers.  Meta[0]
44653 ** is read-only, the others are read/write.
44654 ** 
44655 ** The schema layer numbers meta values differently.  At the schema
44656 ** layer (and the SetCookie and ReadCookie opcodes) the number of
44657 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
44658 */
44659 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
44660   BtShared *pBt = p->pBt;
44661
44662   sqlite3BtreeEnter(p);
44663   assert( p->inTrans>TRANS_NONE );
44664   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
44665   assert( pBt->pPage1 );
44666   assert( idx>=0 && idx<=15 );
44667
44668   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
44669
44670   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
44671   ** database, mark the database as read-only.  */
44672 #ifdef SQLITE_OMIT_AUTOVACUUM
44673   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
44674 #endif
44675
44676   sqlite3BtreeLeave(p);
44677 }
44678
44679 /*
44680 ** Write meta-information back into the database.  Meta[0] is
44681 ** read-only and may not be written.
44682 */
44683 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
44684   BtShared *pBt = p->pBt;
44685   unsigned char *pP1;
44686   int rc;
44687   assert( idx>=1 && idx<=15 );
44688   sqlite3BtreeEnter(p);
44689   assert( p->inTrans==TRANS_WRITE );
44690   assert( pBt->pPage1!=0 );
44691   pP1 = pBt->pPage1->aData;
44692   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
44693   if( rc==SQLITE_OK ){
44694     put4byte(&pP1[36 + idx*4], iMeta);
44695 #ifndef SQLITE_OMIT_AUTOVACUUM
44696     if( idx==BTREE_INCR_VACUUM ){
44697       assert( pBt->autoVacuum || iMeta==0 );
44698       assert( iMeta==0 || iMeta==1 );
44699       pBt->incrVacuum = (u8)iMeta;
44700     }
44701 #endif
44702   }
44703   sqlite3BtreeLeave(p);
44704   return rc;
44705 }
44706
44707 #ifndef SQLITE_OMIT_BTREECOUNT
44708 /*
44709 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
44710 ** number of entries in the b-tree and write the result to *pnEntry.
44711 **
44712 ** SQLITE_OK is returned if the operation is successfully executed. 
44713 ** Otherwise, if an error is encountered (i.e. an IO error or database
44714 ** corruption) an SQLite error code is returned.
44715 */
44716 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
44717   i64 nEntry = 0;                      /* Value to return in *pnEntry */
44718   int rc;                              /* Return code */
44719   rc = moveToRoot(pCur);
44720
44721   /* Unless an error occurs, the following loop runs one iteration for each
44722   ** page in the B-Tree structure (not including overflow pages). 
44723   */
44724   while( rc==SQLITE_OK ){
44725     int iIdx;                          /* Index of child node in parent */
44726     MemPage *pPage;                    /* Current page of the b-tree */
44727
44728     /* If this is a leaf page or the tree is not an int-key tree, then 
44729     ** this page contains countable entries. Increment the entry counter
44730     ** accordingly.
44731     */
44732     pPage = pCur->apPage[pCur->iPage];
44733     if( pPage->leaf || !pPage->intKey ){
44734       nEntry += pPage->nCell;
44735     }
44736
44737     /* pPage is a leaf node. This loop navigates the cursor so that it 
44738     ** points to the first interior cell that it points to the parent of
44739     ** the next page in the tree that has not yet been visited. The
44740     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
44741     ** of the page, or to the number of cells in the page if the next page
44742     ** to visit is the right-child of its parent.
44743     **
44744     ** If all pages in the tree have been visited, return SQLITE_OK to the
44745     ** caller.
44746     */
44747     if( pPage->leaf ){
44748       do {
44749         if( pCur->iPage==0 ){
44750           /* All pages of the b-tree have been visited. Return successfully. */
44751           *pnEntry = nEntry;
44752           return SQLITE_OK;
44753         }
44754         moveToParent(pCur);
44755       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
44756
44757       pCur->aiIdx[pCur->iPage]++;
44758       pPage = pCur->apPage[pCur->iPage];
44759     }
44760
44761     /* Descend to the child node of the cell that the cursor currently 
44762     ** points at. This is the right-child if (iIdx==pPage->nCell).
44763     */
44764     iIdx = pCur->aiIdx[pCur->iPage];
44765     if( iIdx==pPage->nCell ){
44766       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
44767     }else{
44768       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
44769     }
44770   }
44771
44772   /* An error has occurred. Return an error code. */
44773   return rc;
44774 }
44775 #endif
44776
44777 /*
44778 ** Return the pager associated with a BTree.  This routine is used for
44779 ** testing and debugging only.
44780 */
44781 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
44782   return p->pBt->pPager;
44783 }
44784
44785 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
44786 /*
44787 ** Append a message to the error message string.
44788 */
44789 static void checkAppendMsg(
44790   IntegrityCk *pCheck,
44791   char *zMsg1,
44792   const char *zFormat,
44793   ...
44794 ){
44795   va_list ap;
44796   if( !pCheck->mxErr ) return;
44797   pCheck->mxErr--;
44798   pCheck->nErr++;
44799   va_start(ap, zFormat);
44800   if( pCheck->errMsg.nChar ){
44801     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
44802   }
44803   if( zMsg1 ){
44804     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
44805   }
44806   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
44807   va_end(ap);
44808   if( pCheck->errMsg.mallocFailed ){
44809     pCheck->mallocFailed = 1;
44810   }
44811 }
44812 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
44813
44814 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
44815 /*
44816 ** Add 1 to the reference count for page iPage.  If this is the second
44817 ** reference to the page, add an error message to pCheck->zErrMsg.
44818 ** Return 1 if there are 2 ore more references to the page and 0 if
44819 ** if this is the first reference to the page.
44820 **
44821 ** Also check that the page number is in bounds.
44822 */
44823 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
44824   if( iPage==0 ) return 1;
44825   if( iPage>pCheck->nPage ){
44826     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
44827     return 1;
44828   }
44829   if( pCheck->anRef[iPage]==1 ){
44830     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
44831     return 1;
44832   }
44833   return  (pCheck->anRef[iPage]++)>1;
44834 }
44835
44836 #ifndef SQLITE_OMIT_AUTOVACUUM
44837 /*
44838 ** Check that the entry in the pointer-map for page iChild maps to 
44839 ** page iParent, pointer type ptrType. If not, append an error message
44840 ** to pCheck.
44841 */
44842 static void checkPtrmap(
44843   IntegrityCk *pCheck,   /* Integrity check context */
44844   Pgno iChild,           /* Child page number */
44845   u8 eType,              /* Expected pointer map type */
44846   Pgno iParent,          /* Expected pointer map parent page number */
44847   char *zContext         /* Context description (used for error msg) */
44848 ){
44849   int rc;
44850   u8 ePtrmapType;
44851   Pgno iPtrmapParent;
44852
44853   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
44854   if( rc!=SQLITE_OK ){
44855     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
44856     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
44857     return;
44858   }
44859
44860   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
44861     checkAppendMsg(pCheck, zContext, 
44862       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
44863       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
44864   }
44865 }
44866 #endif
44867
44868 /*
44869 ** Check the integrity of the freelist or of an overflow page list.
44870 ** Verify that the number of pages on the list is N.
44871 */
44872 static void checkList(
44873   IntegrityCk *pCheck,  /* Integrity checking context */
44874   int isFreeList,       /* True for a freelist.  False for overflow page list */
44875   int iPage,            /* Page number for first page in the list */
44876   int N,                /* Expected number of pages in the list */
44877   char *zContext        /* Context for error messages */
44878 ){
44879   int i;
44880   int expected = N;
44881   int iFirst = iPage;
44882   while( N-- > 0 && pCheck->mxErr ){
44883     DbPage *pOvflPage;
44884     unsigned char *pOvflData;
44885     if( iPage<1 ){
44886       checkAppendMsg(pCheck, zContext,
44887          "%d of %d pages missing from overflow list starting at %d",
44888           N+1, expected, iFirst);
44889       break;
44890     }
44891     if( checkRef(pCheck, iPage, zContext) ) break;
44892     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
44893       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
44894       break;
44895     }
44896     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
44897     if( isFreeList ){
44898       int n = get4byte(&pOvflData[4]);
44899 #ifndef SQLITE_OMIT_AUTOVACUUM
44900       if( pCheck->pBt->autoVacuum ){
44901         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
44902       }
44903 #endif
44904       if( n>pCheck->pBt->usableSize/4-2 ){
44905         checkAppendMsg(pCheck, zContext,
44906            "freelist leaf count too big on page %d", iPage);
44907         N--;
44908       }else{
44909         for(i=0; i<n; i++){
44910           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
44911 #ifndef SQLITE_OMIT_AUTOVACUUM
44912           if( pCheck->pBt->autoVacuum ){
44913             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
44914           }
44915 #endif
44916           checkRef(pCheck, iFreePage, zContext);
44917         }
44918         N -= n;
44919       }
44920     }
44921 #ifndef SQLITE_OMIT_AUTOVACUUM
44922     else{
44923       /* If this database supports auto-vacuum and iPage is not the last
44924       ** page in this overflow list, check that the pointer-map entry for
44925       ** the following page matches iPage.
44926       */
44927       if( pCheck->pBt->autoVacuum && N>0 ){
44928         i = get4byte(pOvflData);
44929         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
44930       }
44931     }
44932 #endif
44933     iPage = get4byte(pOvflData);
44934     sqlite3PagerUnref(pOvflPage);
44935   }
44936 }
44937 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
44938
44939 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
44940 /*
44941 ** Do various sanity checks on a single page of a tree.  Return
44942 ** the tree depth.  Root pages return 0.  Parents of root pages
44943 ** return 1, and so forth.
44944 ** 
44945 ** These checks are done:
44946 **
44947 **      1.  Make sure that cells and freeblocks do not overlap
44948 **          but combine to completely cover the page.
44949 **  NO  2.  Make sure cell keys are in order.
44950 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
44951 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
44952 **      5.  Check the integrity of overflow pages.
44953 **      6.  Recursively call checkTreePage on all children.
44954 **      7.  Verify that the depth of all children is the same.
44955 **      8.  Make sure this page is at least 33% full or else it is
44956 **          the root of the tree.
44957 */
44958 static int checkTreePage(
44959   IntegrityCk *pCheck,  /* Context for the sanity check */
44960   int iPage,            /* Page number of the page to check */
44961   char *zParentContext  /* Parent context */
44962 ){
44963   MemPage *pPage;
44964   int i, rc, depth, d2, pgno, cnt;
44965   int hdr, cellStart;
44966   int nCell;
44967   u8 *data;
44968   BtShared *pBt;
44969   int usableSize;
44970   char zContext[100];
44971   char *hit = 0;
44972
44973   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
44974
44975   /* Check that the page exists
44976   */
44977   pBt = pCheck->pBt;
44978   usableSize = pBt->usableSize;
44979   if( iPage==0 ) return 0;
44980   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
44981   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
44982     checkAppendMsg(pCheck, zContext,
44983        "unable to get the page. error code=%d", rc);
44984     return 0;
44985   }
44986
44987   /* Clear MemPage.isInit to make sure the corruption detection code in
44988   ** btreeInitPage() is executed.  */
44989   pPage->isInit = 0;
44990   if( (rc = btreeInitPage(pPage))!=0 ){
44991     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
44992     checkAppendMsg(pCheck, zContext, 
44993                    "btreeInitPage() returns error code %d", rc);
44994     releasePage(pPage);
44995     return 0;
44996   }
44997
44998   /* Check out all the cells.
44999   */
45000   depth = 0;
45001   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
45002     u8 *pCell;
45003     u32 sz;
45004     CellInfo info;
45005
45006     /* Check payload overflow pages
45007     */
45008     sqlite3_snprintf(sizeof(zContext), zContext,
45009              "On tree page %d cell %d: ", iPage, i);
45010     pCell = findCell(pPage,i);
45011     btreeParseCellPtr(pPage, pCell, &info);
45012     sz = info.nData;
45013     if( !pPage->intKey ) sz += (int)info.nKey;
45014     assert( sz==info.nPayload );
45015     if( (sz>info.nLocal) 
45016      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
45017     ){
45018       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
45019       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
45020 #ifndef SQLITE_OMIT_AUTOVACUUM
45021       if( pBt->autoVacuum ){
45022         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
45023       }
45024 #endif
45025       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
45026     }
45027
45028     /* Check sanity of left child page.
45029     */
45030     if( !pPage->leaf ){
45031       pgno = get4byte(pCell);
45032 #ifndef SQLITE_OMIT_AUTOVACUUM
45033       if( pBt->autoVacuum ){
45034         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
45035       }
45036 #endif
45037       d2 = checkTreePage(pCheck, pgno, zContext);
45038       if( i>0 && d2!=depth ){
45039         checkAppendMsg(pCheck, zContext, "Child page depth differs");
45040       }
45041       depth = d2;
45042     }
45043   }
45044   if( !pPage->leaf ){
45045     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
45046     sqlite3_snprintf(sizeof(zContext), zContext, 
45047                      "On page %d at right child: ", iPage);
45048 #ifndef SQLITE_OMIT_AUTOVACUUM
45049     if( pBt->autoVacuum ){
45050       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
45051     }
45052 #endif
45053     checkTreePage(pCheck, pgno, zContext);
45054   }
45055  
45056   /* Check for complete coverage of the page
45057   */
45058   data = pPage->aData;
45059   hdr = pPage->hdrOffset;
45060   hit = sqlite3PageMalloc( pBt->pageSize );
45061   if( hit==0 ){
45062     pCheck->mallocFailed = 1;
45063   }else{
45064     u16 contentOffset = get2byte(&data[hdr+5]);
45065     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
45066     memset(hit+contentOffset, 0, usableSize-contentOffset);
45067     memset(hit, 1, contentOffset);
45068     nCell = get2byte(&data[hdr+3]);
45069     cellStart = hdr + 12 - 4*pPage->leaf;
45070     for(i=0; i<nCell; i++){
45071       int pc = get2byte(&data[cellStart+i*2]);
45072       u16 size = 1024;
45073       int j;
45074       if( pc<=usableSize-4 ){
45075         size = cellSizePtr(pPage, &data[pc]);
45076       }
45077       if( (pc+size-1)>=usableSize ){
45078         checkAppendMsg(pCheck, 0, 
45079             "Corruption detected in cell %d on page %d",i,iPage,0);
45080       }else{
45081         for(j=pc+size-1; j>=pc; j--) hit[j]++;
45082       }
45083     }
45084     i = get2byte(&data[hdr+1]);
45085     while( i>0 ){
45086       int size, j;
45087       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
45088       size = get2byte(&data[i+2]);
45089       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
45090       for(j=i+size-1; j>=i; j--) hit[j]++;
45091       j = get2byte(&data[i]);
45092       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
45093       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
45094       i = j;
45095     }
45096     for(i=cnt=0; i<usableSize; i++){
45097       if( hit[i]==0 ){
45098         cnt++;
45099       }else if( hit[i]>1 ){
45100         checkAppendMsg(pCheck, 0,
45101           "Multiple uses for byte %d of page %d", i, iPage);
45102         break;
45103       }
45104     }
45105     if( cnt!=data[hdr+7] ){
45106       checkAppendMsg(pCheck, 0, 
45107           "Fragmentation of %d bytes reported as %d on page %d",
45108           cnt, data[hdr+7], iPage);
45109     }
45110   }
45111   sqlite3PageFree(hit);
45112   releasePage(pPage);
45113   return depth+1;
45114 }
45115 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45116
45117 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
45118 /*
45119 ** This routine does a complete check of the given BTree file.  aRoot[] is
45120 ** an array of pages numbers were each page number is the root page of
45121 ** a table.  nRoot is the number of entries in aRoot.
45122 **
45123 ** A read-only or read-write transaction must be opened before calling
45124 ** this function.
45125 **
45126 ** Write the number of error seen in *pnErr.  Except for some memory
45127 ** allocation errors,  an error message held in memory obtained from
45128 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
45129 ** returned.  If a memory allocation error occurs, NULL is returned.
45130 */
45131 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
45132   Btree *p,     /* The btree to be checked */
45133   int *aRoot,   /* An array of root pages numbers for individual trees */
45134   int nRoot,    /* Number of entries in aRoot[] */
45135   int mxErr,    /* Stop reporting errors after this many */
45136   int *pnErr    /* Write number of errors seen to this variable */
45137 ){
45138   Pgno i;
45139   int nRef;
45140   IntegrityCk sCheck;
45141   BtShared *pBt = p->pBt;
45142   char zErr[100];
45143
45144   sqlite3BtreeEnter(p);
45145   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
45146   nRef = sqlite3PagerRefcount(pBt->pPager);
45147   sCheck.pBt = pBt;
45148   sCheck.pPager = pBt->pPager;
45149   sCheck.nPage = pagerPagecount(sCheck.pBt);
45150   sCheck.mxErr = mxErr;
45151   sCheck.nErr = 0;
45152   sCheck.mallocFailed = 0;
45153   *pnErr = 0;
45154   if( sCheck.nPage==0 ){
45155     sqlite3BtreeLeave(p);
45156     return 0;
45157   }
45158   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
45159   if( !sCheck.anRef ){
45160     *pnErr = 1;
45161     sqlite3BtreeLeave(p);
45162     return 0;
45163   }
45164   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
45165   i = PENDING_BYTE_PAGE(pBt);
45166   if( i<=sCheck.nPage ){
45167     sCheck.anRef[i] = 1;
45168   }
45169   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
45170
45171   /* Check the integrity of the freelist
45172   */
45173   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
45174             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
45175
45176   /* Check all the tables.
45177   */
45178   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
45179     if( aRoot[i]==0 ) continue;
45180 #ifndef SQLITE_OMIT_AUTOVACUUM
45181     if( pBt->autoVacuum && aRoot[i]>1 ){
45182       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
45183     }
45184 #endif
45185     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
45186   }
45187
45188   /* Make sure every page in the file is referenced
45189   */
45190   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
45191 #ifdef SQLITE_OMIT_AUTOVACUUM
45192     if( sCheck.anRef[i]==0 ){
45193       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
45194     }
45195 #else
45196     /* If the database supports auto-vacuum, make sure no tables contain
45197     ** references to pointer-map pages.
45198     */
45199     if( sCheck.anRef[i]==0 && 
45200        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
45201       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
45202     }
45203     if( sCheck.anRef[i]!=0 && 
45204        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
45205       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
45206     }
45207 #endif
45208   }
45209
45210   /* Make sure this analysis did not leave any unref() pages.
45211   ** This is an internal consistency check; an integrity check
45212   ** of the integrity check.
45213   */
45214   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
45215     checkAppendMsg(&sCheck, 0, 
45216       "Outstanding page count goes from %d to %d during this analysis",
45217       nRef, sqlite3PagerRefcount(pBt->pPager)
45218     );
45219   }
45220
45221   /* Clean  up and report errors.
45222   */
45223   sqlite3BtreeLeave(p);
45224   sqlite3_free(sCheck.anRef);
45225   if( sCheck.mallocFailed ){
45226     sqlite3StrAccumReset(&sCheck.errMsg);
45227     *pnErr = sCheck.nErr+1;
45228     return 0;
45229   }
45230   *pnErr = sCheck.nErr;
45231   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
45232   return sqlite3StrAccumFinish(&sCheck.errMsg);
45233 }
45234 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45235
45236 /*
45237 ** Return the full pathname of the underlying database file.
45238 **
45239 ** The pager filename is invariant as long as the pager is
45240 ** open so it is safe to access without the BtShared mutex.
45241 */
45242 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
45243   assert( p->pBt->pPager!=0 );
45244   return sqlite3PagerFilename(p->pBt->pPager);
45245 }
45246
45247 /*
45248 ** Return the pathname of the journal file for this database. The return
45249 ** value of this routine is the same regardless of whether the journal file
45250 ** has been created or not.
45251 **
45252 ** The pager journal filename is invariant as long as the pager is
45253 ** open so it is safe to access without the BtShared mutex.
45254 */
45255 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
45256   assert( p->pBt->pPager!=0 );
45257   return sqlite3PagerJournalname(p->pBt->pPager);
45258 }
45259
45260 /*
45261 ** Return non-zero if a transaction is active.
45262 */
45263 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
45264   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
45265   return (p && (p->inTrans==TRANS_WRITE));
45266 }
45267
45268 /*
45269 ** Return non-zero if a read (or write) transaction is active.
45270 */
45271 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
45272   assert( p );
45273   assert( sqlite3_mutex_held(p->db->mutex) );
45274   return p->inTrans!=TRANS_NONE;
45275 }
45276
45277 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
45278   assert( p );
45279   assert( sqlite3_mutex_held(p->db->mutex) );
45280   return p->nBackup!=0;
45281 }
45282
45283 /*
45284 ** This function returns a pointer to a blob of memory associated with
45285 ** a single shared-btree. The memory is used by client code for its own
45286 ** purposes (for example, to store a high-level schema associated with 
45287 ** the shared-btree). The btree layer manages reference counting issues.
45288 **
45289 ** The first time this is called on a shared-btree, nBytes bytes of memory
45290 ** are allocated, zeroed, and returned to the caller. For each subsequent 
45291 ** call the nBytes parameter is ignored and a pointer to the same blob
45292 ** of memory returned. 
45293 **
45294 ** If the nBytes parameter is 0 and the blob of memory has not yet been
45295 ** allocated, a null pointer is returned. If the blob has already been
45296 ** allocated, it is returned as normal.
45297 **
45298 ** Just before the shared-btree is closed, the function passed as the 
45299 ** xFree argument when the memory allocation was made is invoked on the 
45300 ** blob of allocated memory. This function should not call sqlite3_free()
45301 ** on the memory, the btree layer does that.
45302 */
45303 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
45304   BtShared *pBt = p->pBt;
45305   sqlite3BtreeEnter(p);
45306   if( !pBt->pSchema && nBytes ){
45307     pBt->pSchema = sqlite3MallocZero(nBytes);
45308     pBt->xFreeSchema = xFree;
45309   }
45310   sqlite3BtreeLeave(p);
45311   return pBt->pSchema;
45312 }
45313
45314 /*
45315 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
45316 ** btree as the argument handle holds an exclusive lock on the 
45317 ** sqlite_master table. Otherwise SQLITE_OK.
45318 */
45319 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
45320   int rc;
45321   assert( sqlite3_mutex_held(p->db->mutex) );
45322   sqlite3BtreeEnter(p);
45323   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
45324   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
45325   sqlite3BtreeLeave(p);
45326   return rc;
45327 }
45328
45329
45330 #ifndef SQLITE_OMIT_SHARED_CACHE
45331 /*
45332 ** Obtain a lock on the table whose root page is iTab.  The
45333 ** lock is a write lock if isWritelock is true or a read lock
45334 ** if it is false.
45335 */
45336 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
45337   int rc = SQLITE_OK;
45338   assert( p->inTrans!=TRANS_NONE );
45339   if( p->sharable ){
45340     u8 lockType = READ_LOCK + isWriteLock;
45341     assert( READ_LOCK+1==WRITE_LOCK );
45342     assert( isWriteLock==0 || isWriteLock==1 );
45343
45344     sqlite3BtreeEnter(p);
45345     rc = querySharedCacheTableLock(p, iTab, lockType);
45346     if( rc==SQLITE_OK ){
45347       rc = setSharedCacheTableLock(p, iTab, lockType);
45348     }
45349     sqlite3BtreeLeave(p);
45350   }
45351   return rc;
45352 }
45353 #endif
45354
45355 #ifndef SQLITE_OMIT_INCRBLOB
45356 /*
45357 ** Argument pCsr must be a cursor opened for writing on an 
45358 ** INTKEY table currently pointing at a valid table entry. 
45359 ** This function modifies the data stored as part of that entry.
45360 **
45361 ** Only the data content may only be modified, it is not possible to 
45362 ** change the length of the data stored. If this function is called with
45363 ** parameters that attempt to write past the end of the existing data,
45364 ** no modifications are made and SQLITE_CORRUPT is returned.
45365 */
45366 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
45367   int rc;
45368   assert( cursorHoldsMutex(pCsr) );
45369   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
45370   assert( pCsr->isIncrblobHandle );
45371
45372   rc = restoreCursorPosition(pCsr);
45373   if( rc!=SQLITE_OK ){
45374     return rc;
45375   }
45376   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
45377   if( pCsr->eState!=CURSOR_VALID ){
45378     return SQLITE_ABORT;
45379   }
45380
45381   /* Check some assumptions: 
45382   **   (a) the cursor is open for writing,
45383   **   (b) there is a read/write transaction open,
45384   **   (c) the connection holds a write-lock on the table (if required),
45385   **   (d) there are no conflicting read-locks, and
45386   **   (e) the cursor points at a valid row of an intKey table.
45387   */
45388   if( !pCsr->wrFlag ){
45389     return SQLITE_READONLY;
45390   }
45391   assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
45392   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
45393   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
45394   assert( pCsr->apPage[pCsr->iPage]->intKey );
45395
45396   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
45397 }
45398
45399 /* 
45400 ** Set a flag on this cursor to cache the locations of pages from the 
45401 ** overflow list for the current row. This is used by cursors opened
45402 ** for incremental blob IO only.
45403 **
45404 ** This function sets a flag only. The actual page location cache
45405 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
45406 ** accessPayload() (the worker function for sqlite3BtreeData() and
45407 ** sqlite3BtreePutData()).
45408 */
45409 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
45410   assert( cursorHoldsMutex(pCur) );
45411   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
45412   assert(!pCur->isIncrblobHandle);
45413   assert(!pCur->aOverflow);
45414   pCur->isIncrblobHandle = 1;
45415 }
45416 #endif
45417
45418 /************** End of btree.c ***********************************************/
45419 /************** Begin file backup.c ******************************************/
45420 /*
45421 ** 2009 January 28
45422 **
45423 ** The author disclaims copyright to this source code.  In place of
45424 ** a legal notice, here is a blessing:
45425 **
45426 **    May you do good and not evil.
45427 **    May you find forgiveness for yourself and forgive others.
45428 **    May you share freely, never taking more than you give.
45429 **
45430 *************************************************************************
45431 ** This file contains the implementation of the sqlite3_backup_XXX() 
45432 ** API functions and the related features.
45433 */
45434
45435 /* Macro to find the minimum of two numeric values.
45436 */
45437 #ifndef MIN
45438 # define MIN(x,y) ((x)<(y)?(x):(y))
45439 #endif
45440
45441 /*
45442 ** Structure allocated for each backup operation.
45443 */
45444 struct sqlite3_backup {
45445   sqlite3* pDestDb;        /* Destination database handle */
45446   Btree *pDest;            /* Destination b-tree file */
45447   u32 iDestSchema;         /* Original schema cookie in destination */
45448   int bDestLocked;         /* True once a write-transaction is open on pDest */
45449
45450   Pgno iNext;              /* Page number of the next source page to copy */
45451   sqlite3* pSrcDb;         /* Source database handle */
45452   Btree *pSrc;             /* Source b-tree file */
45453
45454   int rc;                  /* Backup process error code */
45455
45456   /* These two variables are set by every call to backup_step(). They are
45457   ** read by calls to backup_remaining() and backup_pagecount().
45458   */
45459   Pgno nRemaining;         /* Number of pages left to copy */
45460   Pgno nPagecount;         /* Total number of pages to copy */
45461
45462   int isAttached;          /* True once backup has been registered with pager */
45463   sqlite3_backup *pNext;   /* Next backup associated with source pager */
45464 };
45465
45466 /*
45467 ** THREAD SAFETY NOTES:
45468 **
45469 **   Once it has been created using backup_init(), a single sqlite3_backup
45470 **   structure may be accessed via two groups of thread-safe entry points:
45471 **
45472 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
45473 **       backup_finish(). Both these functions obtain the source database
45474 **       handle mutex and the mutex associated with the source BtShared 
45475 **       structure, in that order.
45476 **
45477 **     * Via the BackupUpdate() and BackupRestart() functions, which are
45478 **       invoked by the pager layer to report various state changes in
45479 **       the page cache associated with the source database. The mutex
45480 **       associated with the source database BtShared structure will always 
45481 **       be held when either of these functions are invoked.
45482 **
45483 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
45484 **   backup_pagecount() are not thread-safe functions. If they are called
45485 **   while some other thread is calling backup_step() or backup_finish(),
45486 **   the values returned may be invalid. There is no way for a call to
45487 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
45488 **   or backup_pagecount().
45489 **
45490 **   Depending on the SQLite configuration, the database handles and/or
45491 **   the Btree objects may have their own mutexes that require locking.
45492 **   Non-sharable Btrees (in-memory databases for example), do not have
45493 **   associated mutexes.
45494 */
45495
45496 /*
45497 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
45498 ** in connection handle pDb. If such a database cannot be found, return
45499 ** a NULL pointer and write an error message to pErrorDb.
45500 **
45501 ** If the "temp" database is requested, it may need to be opened by this 
45502 ** function. If an error occurs while doing so, return 0 and write an 
45503 ** error message to pErrorDb.
45504 */
45505 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
45506   int i = sqlite3FindDbName(pDb, zDb);
45507
45508   if( i==1 ){
45509     Parse *pParse;
45510     int rc = 0;
45511     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
45512     if( pParse==0 ){
45513       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
45514       rc = SQLITE_NOMEM;
45515     }else{
45516       pParse->db = pDb;
45517       if( sqlite3OpenTempDatabase(pParse) ){
45518         sqlite3ErrorClear(pParse);
45519         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
45520         rc = SQLITE_ERROR;
45521       }
45522       sqlite3StackFree(pErrorDb, pParse);
45523     }
45524     if( rc ){
45525       return 0;
45526     }
45527   }
45528
45529   if( i<0 ){
45530     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
45531     return 0;
45532   }
45533
45534   return pDb->aDb[i].pBt;
45535 }
45536
45537 /*
45538 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
45539 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
45540 ** a pointer to the new sqlite3_backup object.
45541 **
45542 ** If an error occurs, NULL is returned and an error code and error message
45543 ** stored in database handle pDestDb.
45544 */
45545 SQLITE_API sqlite3_backup *sqlite3_backup_init(
45546   sqlite3* pDestDb,                     /* Database to write to */
45547   const char *zDestDb,                  /* Name of database within pDestDb */
45548   sqlite3* pSrcDb,                      /* Database connection to read from */
45549   const char *zSrcDb                    /* Name of database within pSrcDb */
45550 ){
45551   sqlite3_backup *p;                    /* Value to return */
45552
45553   /* Lock the source database handle. The destination database
45554   ** handle is not locked in this routine, but it is locked in
45555   ** sqlite3_backup_step(). The user is required to ensure that no
45556   ** other thread accesses the destination handle for the duration
45557   ** of the backup operation.  Any attempt to use the destination
45558   ** database connection while a backup is in progress may cause
45559   ** a malfunction or a deadlock.
45560   */
45561   sqlite3_mutex_enter(pSrcDb->mutex);
45562   sqlite3_mutex_enter(pDestDb->mutex);
45563
45564   if( pSrcDb==pDestDb ){
45565     sqlite3Error(
45566         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
45567     );
45568     p = 0;
45569   }else {
45570     /* Allocate space for a new sqlite3_backup object */
45571     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
45572     if( !p ){
45573       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
45574     }
45575   }
45576
45577   /* If the allocation succeeded, populate the new object. */
45578   if( p ){
45579     memset(p, 0, sizeof(sqlite3_backup));
45580     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
45581     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
45582     p->pDestDb = pDestDb;
45583     p->pSrcDb = pSrcDb;
45584     p->iNext = 1;
45585     p->isAttached = 0;
45586
45587     if( 0==p->pSrc || 0==p->pDest ){
45588       /* One (or both) of the named databases did not exist. An error has
45589       ** already been written into the pDestDb handle. All that is left
45590       ** to do here is free the sqlite3_backup structure.
45591       */
45592       sqlite3_free(p);
45593       p = 0;
45594     }
45595   }
45596   if( p ){
45597     p->pSrc->nBackup++;
45598   }
45599
45600   sqlite3_mutex_leave(pDestDb->mutex);
45601   sqlite3_mutex_leave(pSrcDb->mutex);
45602   return p;
45603 }
45604
45605 /*
45606 ** Argument rc is an SQLite error code. Return true if this error is 
45607 ** considered fatal if encountered during a backup operation. All errors
45608 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
45609 */
45610 static int isFatalError(int rc){
45611   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
45612 }
45613
45614 /*
45615 ** Parameter zSrcData points to a buffer containing the data for 
45616 ** page iSrcPg from the source database. Copy this data into the 
45617 ** destination database.
45618 */
45619 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
45620   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
45621   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
45622   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
45623   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
45624   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
45625
45626   int rc = SQLITE_OK;
45627   i64 iOff;
45628
45629   assert( p->bDestLocked );
45630   assert( !isFatalError(p->rc) );
45631   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
45632   assert( zSrcData );
45633
45634   /* Catch the case where the destination is an in-memory database and the
45635   ** page sizes of the source and destination differ. 
45636   */
45637   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(sqlite3BtreePager(p->pDest)) ){
45638     rc = SQLITE_READONLY;
45639   }
45640
45641   /* This loop runs once for each destination page spanned by the source 
45642   ** page. For each iteration, variable iOff is set to the byte offset
45643   ** of the destination page.
45644   */
45645   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
45646     DbPage *pDestPg = 0;
45647     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
45648     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
45649     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
45650      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
45651     ){
45652       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
45653       u8 *zDestData = sqlite3PagerGetData(pDestPg);
45654       u8 *zOut = &zDestData[iOff%nDestPgsz];
45655
45656       /* Copy the data from the source page into the destination page.
45657       ** Then clear the Btree layer MemPage.isInit flag. Both this module
45658       ** and the pager code use this trick (clearing the first byte
45659       ** of the page 'extra' space to invalidate the Btree layers
45660       ** cached parse of the page). MemPage.isInit is marked 
45661       ** "MUST BE FIRST" for this purpose.
45662       */
45663       memcpy(zOut, zIn, nCopy);
45664       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
45665     }
45666     sqlite3PagerUnref(pDestPg);
45667   }
45668
45669   return rc;
45670 }
45671
45672 /*
45673 ** If pFile is currently larger than iSize bytes, then truncate it to
45674 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
45675 ** this function is a no-op.
45676 **
45677 ** Return SQLITE_OK if everything is successful, or an SQLite error 
45678 ** code if an error occurs.
45679 */
45680 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
45681   i64 iCurrent;
45682   int rc = sqlite3OsFileSize(pFile, &iCurrent);
45683   if( rc==SQLITE_OK && iCurrent>iSize ){
45684     rc = sqlite3OsTruncate(pFile, iSize);
45685   }
45686   return rc;
45687 }
45688
45689 /*
45690 ** Register this backup object with the associated source pager for
45691 ** callbacks when pages are changed or the cache invalidated.
45692 */
45693 static void attachBackupObject(sqlite3_backup *p){
45694   sqlite3_backup **pp;
45695   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
45696   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
45697   p->pNext = *pp;
45698   *pp = p;
45699   p->isAttached = 1;
45700 }
45701
45702 /*
45703 ** Copy nPage pages from the source b-tree to the destination.
45704 */
45705 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
45706   int rc;
45707
45708   sqlite3_mutex_enter(p->pSrcDb->mutex);
45709   sqlite3BtreeEnter(p->pSrc);
45710   if( p->pDestDb ){
45711     sqlite3_mutex_enter(p->pDestDb->mutex);
45712   }
45713
45714   rc = p->rc;
45715   if( !isFatalError(rc) ){
45716     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
45717     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
45718     int ii;                            /* Iterator variable */
45719     int nSrcPage = -1;                 /* Size of source db in pages */
45720     int bCloseTrans = 0;               /* True if src db requires unlocking */
45721
45722     /* If the source pager is currently in a write-transaction, return
45723     ** SQLITE_BUSY immediately.
45724     */
45725     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
45726       rc = SQLITE_BUSY;
45727     }else{
45728       rc = SQLITE_OK;
45729     }
45730
45731     /* Lock the destination database, if it is not locked already. */
45732     if( SQLITE_OK==rc && p->bDestLocked==0
45733      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
45734     ){
45735       p->bDestLocked = 1;
45736       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
45737     }
45738
45739     /* If there is no open read-transaction on the source database, open
45740     ** one now. If a transaction is opened here, then it will be closed
45741     ** before this function exits.
45742     */
45743     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
45744       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
45745       bCloseTrans = 1;
45746     }
45747   
45748     /* Now that there is a read-lock on the source database, query the
45749     ** source pager for the number of pages in the database.
45750     */
45751     if( rc==SQLITE_OK ){
45752       rc = sqlite3PagerPagecount(pSrcPager, &nSrcPage);
45753     }
45754     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
45755       const Pgno iSrcPg = p->iNext;                 /* Source page number */
45756       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
45757         DbPage *pSrcPg;                             /* Source page object */
45758         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
45759         if( rc==SQLITE_OK ){
45760           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
45761           sqlite3PagerUnref(pSrcPg);
45762         }
45763       }
45764       p->iNext++;
45765     }
45766     if( rc==SQLITE_OK ){
45767       p->nPagecount = nSrcPage;
45768       p->nRemaining = nSrcPage+1-p->iNext;
45769       if( p->iNext>(Pgno)nSrcPage ){
45770         rc = SQLITE_DONE;
45771       }else if( !p->isAttached ){
45772         attachBackupObject(p);
45773       }
45774     }
45775   
45776     /* Update the schema version field in the destination database. This
45777     ** is to make sure that the schema-version really does change in
45778     ** the case where the source and destination databases have the
45779     ** same schema version.
45780     */
45781     if( rc==SQLITE_DONE 
45782      && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
45783     ){
45784       const int nSrcPagesize = sqlite3BtreeGetPageSize(p->pSrc);
45785       const int nDestPagesize = sqlite3BtreeGetPageSize(p->pDest);
45786       int nDestTruncate;
45787   
45788       if( p->pDestDb ){
45789         sqlite3ResetInternalSchema(p->pDestDb, 0);
45790       }
45791
45792       /* Set nDestTruncate to the final number of pages in the destination
45793       ** database. The complication here is that the destination page
45794       ** size may be different to the source page size. 
45795       **
45796       ** If the source page size is smaller than the destination page size, 
45797       ** round up. In this case the call to sqlite3OsTruncate() below will
45798       ** fix the size of the file. However it is important to call
45799       ** sqlite3PagerTruncateImage() here so that any pages in the 
45800       ** destination file that lie beyond the nDestTruncate page mark are
45801       ** journalled by PagerCommitPhaseOne() before they are destroyed
45802       ** by the file truncation.
45803       */
45804       if( nSrcPagesize<nDestPagesize ){
45805         int ratio = nDestPagesize/nSrcPagesize;
45806         nDestTruncate = (nSrcPage+ratio-1)/ratio;
45807         if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
45808           nDestTruncate--;
45809         }
45810       }else{
45811         nDestTruncate = nSrcPage * (nSrcPagesize/nDestPagesize);
45812       }
45813       sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
45814
45815       if( nSrcPagesize<nDestPagesize ){
45816         /* If the source page-size is smaller than the destination page-size,
45817         ** two extra things may need to happen:
45818         **
45819         **   * The destination may need to be truncated, and
45820         **
45821         **   * Data stored on the pages immediately following the 
45822         **     pending-byte page in the source database may need to be
45823         **     copied into the destination database.
45824         */
45825         const i64 iSize = (i64)nSrcPagesize * (i64)nSrcPage;
45826         sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
45827
45828         assert( pFile );
45829         assert( (i64)nDestTruncate*(i64)nDestPagesize >= iSize || (
45830               nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
45831            && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+nDestPagesize
45832         ));
45833         if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
45834          && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
45835          && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
45836         ){
45837           i64 iOff;
45838           i64 iEnd = MIN(PENDING_BYTE + nDestPagesize, iSize);
45839           for(
45840             iOff=PENDING_BYTE+nSrcPagesize; 
45841             rc==SQLITE_OK && iOff<iEnd; 
45842             iOff+=nSrcPagesize
45843           ){
45844             PgHdr *pSrcPg = 0;
45845             const Pgno iSrcPg = (Pgno)((iOff/nSrcPagesize)+1);
45846             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
45847             if( rc==SQLITE_OK ){
45848               u8 *zData = sqlite3PagerGetData(pSrcPg);
45849               rc = sqlite3OsWrite(pFile, zData, nSrcPagesize, iOff);
45850             }
45851             sqlite3PagerUnref(pSrcPg);
45852           }
45853         }
45854       }else{
45855         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
45856       }
45857   
45858       /* Finish committing the transaction to the destination database. */
45859       if( SQLITE_OK==rc
45860        && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
45861       ){
45862         rc = SQLITE_DONE;
45863       }
45864     }
45865   
45866     /* If bCloseTrans is true, then this function opened a read transaction
45867     ** on the source database. Close the read transaction here. There is
45868     ** no need to check the return values of the btree methods here, as
45869     ** "committing" a read-only transaction cannot fail.
45870     */
45871     if( bCloseTrans ){
45872       TESTONLY( int rc2 );
45873       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
45874       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
45875       assert( rc2==SQLITE_OK );
45876     }
45877   
45878     p->rc = rc;
45879   }
45880   if( p->pDestDb ){
45881     sqlite3_mutex_leave(p->pDestDb->mutex);
45882   }
45883   sqlite3BtreeLeave(p->pSrc);
45884   sqlite3_mutex_leave(p->pSrcDb->mutex);
45885   return rc;
45886 }
45887
45888 /*
45889 ** Release all resources associated with an sqlite3_backup* handle.
45890 */
45891 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
45892   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
45893   sqlite3_mutex *mutex;                /* Mutex to protect source database */
45894   int rc;                              /* Value to return */
45895
45896   /* Enter the mutexes */
45897   if( p==0 ) return SQLITE_OK;
45898   sqlite3_mutex_enter(p->pSrcDb->mutex);
45899   sqlite3BtreeEnter(p->pSrc);
45900   mutex = p->pSrcDb->mutex;
45901   if( p->pDestDb ){
45902     sqlite3_mutex_enter(p->pDestDb->mutex);
45903   }
45904
45905   /* Detach this backup from the source pager. */
45906   if( p->pDestDb ){
45907     p->pSrc->nBackup--;
45908   }
45909   if( p->isAttached ){
45910     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
45911     while( *pp!=p ){
45912       pp = &(*pp)->pNext;
45913     }
45914     *pp = p->pNext;
45915   }
45916
45917   /* If a transaction is still open on the Btree, roll it back. */
45918   sqlite3BtreeRollback(p->pDest);
45919
45920   /* Set the error code of the destination database handle. */
45921   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
45922   sqlite3Error(p->pDestDb, rc, 0);
45923
45924   /* Exit the mutexes and free the backup context structure. */
45925   if( p->pDestDb ){
45926     sqlite3_mutex_leave(p->pDestDb->mutex);
45927   }
45928   sqlite3BtreeLeave(p->pSrc);
45929   if( p->pDestDb ){
45930     sqlite3_free(p);
45931   }
45932   sqlite3_mutex_leave(mutex);
45933   return rc;
45934 }
45935
45936 /*
45937 ** Return the number of pages still to be backed up as of the most recent
45938 ** call to sqlite3_backup_step().
45939 */
45940 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
45941   return p->nRemaining;
45942 }
45943
45944 /*
45945 ** Return the total number of pages in the source database as of the most 
45946 ** recent call to sqlite3_backup_step().
45947 */
45948 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
45949   return p->nPagecount;
45950 }
45951
45952 /*
45953 ** This function is called after the contents of page iPage of the
45954 ** source database have been modified. If page iPage has already been 
45955 ** copied into the destination database, then the data written to the
45956 ** destination is now invalidated. The destination copy of iPage needs
45957 ** to be updated with the new data before the backup operation is
45958 ** complete.
45959 **
45960 ** It is assumed that the mutex associated with the BtShared object
45961 ** corresponding to the source database is held when this function is
45962 ** called.
45963 */
45964 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
45965   sqlite3_backup *p;                   /* Iterator variable */
45966   for(p=pBackup; p; p=p->pNext){
45967     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
45968     if( !isFatalError(p->rc) && iPage<p->iNext ){
45969       /* The backup process p has already copied page iPage. But now it
45970       ** has been modified by a transaction on the source pager. Copy
45971       ** the new data into the backup.
45972       */
45973       int rc = backupOnePage(p, iPage, aData);
45974       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
45975       if( rc!=SQLITE_OK ){
45976         p->rc = rc;
45977       }
45978     }
45979   }
45980 }
45981
45982 /*
45983 ** Restart the backup process. This is called when the pager layer
45984 ** detects that the database has been modified by an external database
45985 ** connection. In this case there is no way of knowing which of the
45986 ** pages that have been copied into the destination database are still 
45987 ** valid and which are not, so the entire process needs to be restarted.
45988 **
45989 ** It is assumed that the mutex associated with the BtShared object
45990 ** corresponding to the source database is held when this function is
45991 ** called.
45992 */
45993 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
45994   sqlite3_backup *p;                   /* Iterator variable */
45995   for(p=pBackup; p; p=p->pNext){
45996     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
45997     p->iNext = 1;
45998   }
45999 }
46000
46001 #ifndef SQLITE_OMIT_VACUUM
46002 /*
46003 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
46004 ** must be active for both files.
46005 **
46006 ** The size of file pTo may be reduced by this operation. If anything 
46007 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
46008 ** transaction is committed before returning.
46009 */
46010 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
46011   int rc;
46012   sqlite3_backup b;
46013   sqlite3BtreeEnter(pTo);
46014   sqlite3BtreeEnter(pFrom);
46015
46016   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
46017   ** to 0. This is used by the implementations of sqlite3_backup_step()
46018   ** and sqlite3_backup_finish() to detect that they are being called
46019   ** from this function, not directly by the user.
46020   */
46021   memset(&b, 0, sizeof(b));
46022   b.pSrcDb = pFrom->db;
46023   b.pSrc = pFrom;
46024   b.pDest = pTo;
46025   b.iNext = 1;
46026
46027   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
46028   ** file. By passing this as the number of pages to copy to
46029   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
46030   ** within a single call (unless an error occurs). The assert() statement
46031   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
46032   ** or an error code.
46033   */
46034   sqlite3_backup_step(&b, 0x7FFFFFFF);
46035   assert( b.rc!=SQLITE_OK );
46036   rc = sqlite3_backup_finish(&b);
46037   if( rc==SQLITE_OK ){
46038     pTo->pBt->pageSizeFixed = 0;
46039   }
46040
46041   sqlite3BtreeLeave(pFrom);
46042   sqlite3BtreeLeave(pTo);
46043   return rc;
46044 }
46045 #endif /* SQLITE_OMIT_VACUUM */
46046
46047 /************** End of backup.c **********************************************/
46048 /************** Begin file vdbemem.c *****************************************/
46049 /*
46050 ** 2004 May 26
46051 **
46052 ** The author disclaims copyright to this source code.  In place of
46053 ** a legal notice, here is a blessing:
46054 **
46055 **    May you do good and not evil.
46056 **    May you find forgiveness for yourself and forgive others.
46057 **    May you share freely, never taking more than you give.
46058 **
46059 *************************************************************************
46060 **
46061 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
46062 ** stores a single value in the VDBE.  Mem is an opaque structure visible
46063 ** only within the VDBE.  Interface routines refer to a Mem using the
46064 ** name sqlite_value
46065 */
46066
46067 /*
46068 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
46069 ** P if required.
46070 */
46071 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
46072
46073 /*
46074 ** If pMem is an object with a valid string representation, this routine
46075 ** ensures the internal encoding for the string representation is
46076 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
46077 **
46078 ** If pMem is not a string object, or the encoding of the string
46079 ** representation is already stored using the requested encoding, then this
46080 ** routine is a no-op.
46081 **
46082 ** SQLITE_OK is returned if the conversion is successful (or not required).
46083 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
46084 ** between formats.
46085 */
46086 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
46087   int rc;
46088   assert( (pMem->flags&MEM_RowSet)==0 );
46089   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
46090            || desiredEnc==SQLITE_UTF16BE );
46091   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
46092     return SQLITE_OK;
46093   }
46094   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46095 #ifdef SQLITE_OMIT_UTF16
46096   return SQLITE_ERROR;
46097 #else
46098
46099   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
46100   ** then the encoding of the value may not have changed.
46101   */
46102   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
46103   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
46104   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
46105   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
46106   return rc;
46107 #endif
46108 }
46109
46110 /*
46111 ** Make sure pMem->z points to a writable allocation of at least 
46112 ** n bytes.
46113 **
46114 ** If the memory cell currently contains string or blob data
46115 ** and the third argument passed to this function is true, the 
46116 ** current content of the cell is preserved. Otherwise, it may
46117 ** be discarded.  
46118 **
46119 ** This function sets the MEM_Dyn flag and clears any xDel callback.
46120 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
46121 ** not set, Mem.n is zeroed.
46122 */
46123 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
46124   assert( 1 >=
46125     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
46126     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
46127     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
46128     ((pMem->flags&MEM_Static) ? 1 : 0)
46129   );
46130   assert( (pMem->flags&MEM_RowSet)==0 );
46131
46132   if( n<32 ) n = 32;
46133   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
46134     if( preserve && pMem->z==pMem->zMalloc ){
46135       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
46136       preserve = 0;
46137     }else{
46138       sqlite3DbFree(pMem->db, pMem->zMalloc);
46139       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
46140     }
46141   }
46142
46143   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
46144     memcpy(pMem->zMalloc, pMem->z, pMem->n);
46145   }
46146   if( pMem->flags&MEM_Dyn && pMem->xDel ){
46147     pMem->xDel((void *)(pMem->z));
46148   }
46149
46150   pMem->z = pMem->zMalloc;
46151   if( pMem->z==0 ){
46152     pMem->flags = MEM_Null;
46153   }else{
46154     pMem->flags &= ~(MEM_Ephem|MEM_Static);
46155   }
46156   pMem->xDel = 0;
46157   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
46158 }
46159
46160 /*
46161 ** Make the given Mem object MEM_Dyn.  In other words, make it so
46162 ** that any TEXT or BLOB content is stored in memory obtained from
46163 ** malloc().  In this way, we know that the memory is safe to be
46164 ** overwritten or altered.
46165 **
46166 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
46167 */
46168 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
46169   int f;
46170   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46171   assert( (pMem->flags&MEM_RowSet)==0 );
46172   expandBlob(pMem);
46173   f = pMem->flags;
46174   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
46175     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
46176       return SQLITE_NOMEM;
46177     }
46178     pMem->z[pMem->n] = 0;
46179     pMem->z[pMem->n+1] = 0;
46180     pMem->flags |= MEM_Term;
46181   }
46182
46183   return SQLITE_OK;
46184 }
46185
46186 /*
46187 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
46188 ** blob stored in dynamically allocated space.
46189 */
46190 #ifndef SQLITE_OMIT_INCRBLOB
46191 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
46192   if( pMem->flags & MEM_Zero ){
46193     int nByte;
46194     assert( pMem->flags&MEM_Blob );
46195     assert( (pMem->flags&MEM_RowSet)==0 );
46196     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46197
46198     /* Set nByte to the number of bytes required to store the expanded blob. */
46199     nByte = pMem->n + pMem->u.nZero;
46200     if( nByte<=0 ){
46201       nByte = 1;
46202     }
46203     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
46204       return SQLITE_NOMEM;
46205     }
46206
46207     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
46208     pMem->n += pMem->u.nZero;
46209     pMem->flags &= ~(MEM_Zero|MEM_Term);
46210   }
46211   return SQLITE_OK;
46212 }
46213 #endif
46214
46215
46216 /*
46217 ** Make sure the given Mem is \u0000 terminated.
46218 */
46219 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
46220   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46221   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
46222     return SQLITE_OK;   /* Nothing to do */
46223   }
46224   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
46225     return SQLITE_NOMEM;
46226   }
46227   pMem->z[pMem->n] = 0;
46228   pMem->z[pMem->n+1] = 0;
46229   pMem->flags |= MEM_Term;
46230   return SQLITE_OK;
46231 }
46232
46233 /*
46234 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
46235 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
46236 ** is a no-op.
46237 **
46238 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
46239 **
46240 ** A MEM_Null value will never be passed to this function. This function is
46241 ** used for converting values to text for returning to the user (i.e. via
46242 ** sqlite3_value_text()), or for ensuring that values to be used as btree
46243 ** keys are strings. In the former case a NULL pointer is returned the
46244 ** user and the later is an internal programming error.
46245 */
46246 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
46247   int rc = SQLITE_OK;
46248   int fg = pMem->flags;
46249   const int nByte = 32;
46250
46251   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46252   assert( !(fg&MEM_Zero) );
46253   assert( !(fg&(MEM_Str|MEM_Blob)) );
46254   assert( fg&(MEM_Int|MEM_Real) );
46255   assert( (pMem->flags&MEM_RowSet)==0 );
46256   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46257
46258
46259   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
46260     return SQLITE_NOMEM;
46261   }
46262
46263   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
46264   ** string representation of the value. Then, if the required encoding
46265   ** is UTF-16le or UTF-16be do a translation.
46266   ** 
46267   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
46268   */
46269   if( fg & MEM_Int ){
46270     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
46271   }else{
46272     assert( fg & MEM_Real );
46273     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
46274   }
46275   pMem->n = sqlite3Strlen30(pMem->z);
46276   pMem->enc = SQLITE_UTF8;
46277   pMem->flags |= MEM_Str|MEM_Term;
46278   sqlite3VdbeChangeEncoding(pMem, enc);
46279   return rc;
46280 }
46281
46282 /*
46283 ** Memory cell pMem contains the context of an aggregate function.
46284 ** This routine calls the finalize method for that function.  The
46285 ** result of the aggregate is stored back into pMem.
46286 **
46287 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
46288 ** otherwise.
46289 */
46290 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
46291   int rc = SQLITE_OK;
46292   if( ALWAYS(pFunc && pFunc->xFinalize) ){
46293     sqlite3_context ctx;
46294     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
46295     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46296     memset(&ctx, 0, sizeof(ctx));
46297     ctx.s.flags = MEM_Null;
46298     ctx.s.db = pMem->db;
46299     ctx.pMem = pMem;
46300     ctx.pFunc = pFunc;
46301     pFunc->xFinalize(&ctx);
46302     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
46303     sqlite3DbFree(pMem->db, pMem->zMalloc);
46304     memcpy(pMem, &ctx.s, sizeof(ctx.s));
46305     rc = ctx.isError;
46306   }
46307   return rc;
46308 }
46309
46310 /*
46311 ** If the memory cell contains a string value that must be freed by
46312 ** invoking an external callback, free it now. Calling this function
46313 ** does not free any Mem.zMalloc buffer.
46314 */
46315 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
46316   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
46317   testcase( p->flags & MEM_Agg );
46318   testcase( p->flags & MEM_Dyn );
46319   testcase( p->flags & MEM_RowSet );
46320   testcase( p->flags & MEM_Frame );
46321   if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
46322     if( p->flags&MEM_Agg ){
46323       sqlite3VdbeMemFinalize(p, p->u.pDef);
46324       assert( (p->flags & MEM_Agg)==0 );
46325       sqlite3VdbeMemRelease(p);
46326     }else if( p->flags&MEM_Dyn && p->xDel ){
46327       assert( (p->flags&MEM_RowSet)==0 );
46328       p->xDel((void *)p->z);
46329       p->xDel = 0;
46330     }else if( p->flags&MEM_RowSet ){
46331       sqlite3RowSetClear(p->u.pRowSet);
46332     }else if( p->flags&MEM_Frame ){
46333       sqlite3VdbeMemSetNull(p);
46334     }
46335   }
46336 }
46337
46338 /*
46339 ** Release any memory held by the Mem. This may leave the Mem in an
46340 ** inconsistent state, for example with (Mem.z==0) and
46341 ** (Mem.type==SQLITE_TEXT).
46342 */
46343 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
46344   sqlite3VdbeMemReleaseExternal(p);
46345   sqlite3DbFree(p->db, p->zMalloc);
46346   p->z = 0;
46347   p->zMalloc = 0;
46348   p->xDel = 0;
46349 }
46350
46351 /*
46352 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
46353 ** If the double is too large, return 0x8000000000000000.
46354 **
46355 ** Most systems appear to do this simply by assigning
46356 ** variables and without the extra range tests.  But
46357 ** there are reports that windows throws an expection
46358 ** if the floating point value is out of range. (See ticket #2880.)
46359 ** Because we do not completely understand the problem, we will
46360 ** take the conservative approach and always do range tests
46361 ** before attempting the conversion.
46362 */
46363 static i64 doubleToInt64(double r){
46364   /*
46365   ** Many compilers we encounter do not define constants for the
46366   ** minimum and maximum 64-bit integers, or they define them
46367   ** inconsistently.  And many do not understand the "LL" notation.
46368   ** So we define our own static constants here using nothing
46369   ** larger than a 32-bit integer constant.
46370   */
46371   static const i64 maxInt = LARGEST_INT64;
46372   static const i64 minInt = SMALLEST_INT64;
46373
46374   if( r<(double)minInt ){
46375     return minInt;
46376   }else if( r>(double)maxInt ){
46377     /* minInt is correct here - not maxInt.  It turns out that assigning
46378     ** a very large positive number to an integer results in a very large
46379     ** negative integer.  This makes no sense, but it is what x86 hardware
46380     ** does so for compatibility we will do the same in software. */
46381     return minInt;
46382   }else{
46383     return (i64)r;
46384   }
46385 }
46386
46387 /*
46388 ** Return some kind of integer value which is the best we can do
46389 ** at representing the value that *pMem describes as an integer.
46390 ** If pMem is an integer, then the value is exact.  If pMem is
46391 ** a floating-point then the value returned is the integer part.
46392 ** If pMem is a string or blob, then we make an attempt to convert
46393 ** it into a integer and return that.  If pMem represents an
46394 ** an SQL-NULL value, return 0.
46395 **
46396 ** If pMem represents a string value, its encoding might be changed.
46397 */
46398 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
46399   int flags;
46400   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46401   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46402   flags = pMem->flags;
46403   if( flags & MEM_Int ){
46404     return pMem->u.i;
46405   }else if( flags & MEM_Real ){
46406     return doubleToInt64(pMem->r);
46407   }else if( flags & (MEM_Str|MEM_Blob) ){
46408     i64 value;
46409     pMem->flags |= MEM_Str;
46410     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
46411        || sqlite3VdbeMemNulTerminate(pMem) ){
46412       return 0;
46413     }
46414     assert( pMem->z );
46415     sqlite3Atoi64(pMem->z, &value);
46416     return value;
46417   }else{
46418     return 0;
46419   }
46420 }
46421
46422 /*
46423 ** Return the best representation of pMem that we can get into a
46424 ** double.  If pMem is already a double or an integer, return its
46425 ** value.  If it is a string or blob, try to convert it to a double.
46426 ** If it is a NULL, return 0.0.
46427 */
46428 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
46429   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46430   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46431   if( pMem->flags & MEM_Real ){
46432     return pMem->r;
46433   }else if( pMem->flags & MEM_Int ){
46434     return (double)pMem->u.i;
46435   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
46436     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
46437     double val = (double)0;
46438     pMem->flags |= MEM_Str;
46439     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
46440        || sqlite3VdbeMemNulTerminate(pMem) ){
46441       /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
46442       return (double)0;
46443     }
46444     assert( pMem->z );
46445     sqlite3AtoF(pMem->z, &val);
46446     return val;
46447   }else{
46448     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
46449     return (double)0;
46450   }
46451 }
46452
46453 /*
46454 ** The MEM structure is already a MEM_Real.  Try to also make it a
46455 ** MEM_Int if we can.
46456 */
46457 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
46458   assert( pMem->flags & MEM_Real );
46459   assert( (pMem->flags & MEM_RowSet)==0 );
46460   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46461   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46462
46463   pMem->u.i = doubleToInt64(pMem->r);
46464
46465   /* Only mark the value as an integer if
46466   **
46467   **    (1) the round-trip conversion real->int->real is a no-op, and
46468   **    (2) The integer is neither the largest nor the smallest
46469   **        possible integer (ticket #3922)
46470   **
46471   ** The second and third terms in the following conditional enforces
46472   ** the second condition under the assumption that addition overflow causes
46473   ** values to wrap around.  On x86 hardware, the third term is always
46474   ** true and could be omitted.  But we leave it in because other
46475   ** architectures might behave differently.
46476   */
46477   if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
46478       && ALWAYS(pMem->u.i<LARGEST_INT64) ){
46479     pMem->flags |= MEM_Int;
46480   }
46481 }
46482
46483 /*
46484 ** Convert pMem to type integer.  Invalidate any prior representations.
46485 */
46486 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
46487   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46488   assert( (pMem->flags & MEM_RowSet)==0 );
46489   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46490
46491   pMem->u.i = sqlite3VdbeIntValue(pMem);
46492   MemSetTypeFlag(pMem, MEM_Int);
46493   return SQLITE_OK;
46494 }
46495
46496 /*
46497 ** Convert pMem so that it is of type MEM_Real.
46498 ** Invalidate any prior representations.
46499 */
46500 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
46501   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46502   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46503
46504   pMem->r = sqlite3VdbeRealValue(pMem);
46505   MemSetTypeFlag(pMem, MEM_Real);
46506   return SQLITE_OK;
46507 }
46508
46509 /*
46510 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
46511 ** Invalidate any prior representations.
46512 */
46513 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
46514   double r1, r2;
46515   i64 i;
46516   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
46517   assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
46518   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46519   r1 = sqlite3VdbeRealValue(pMem);
46520   i = doubleToInt64(r1);
46521   r2 = (double)i;
46522   if( r1==r2 ){
46523     sqlite3VdbeMemIntegerify(pMem);
46524   }else{
46525     pMem->r = r1;
46526     MemSetTypeFlag(pMem, MEM_Real);
46527   }
46528   return SQLITE_OK;
46529 }
46530
46531 /*
46532 ** Delete any previous value and set the value stored in *pMem to NULL.
46533 */
46534 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
46535   if( pMem->flags & MEM_Frame ){
46536     sqlite3VdbeFrameDelete(pMem->u.pFrame);
46537   }
46538   if( pMem->flags & MEM_RowSet ){
46539     sqlite3RowSetClear(pMem->u.pRowSet);
46540   }
46541   MemSetTypeFlag(pMem, MEM_Null);
46542   pMem->type = SQLITE_NULL;
46543 }
46544
46545 /*
46546 ** Delete any previous value and set the value to be a BLOB of length
46547 ** n containing all zeros.
46548 */
46549 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
46550   sqlite3VdbeMemRelease(pMem);
46551   pMem->flags = MEM_Blob|MEM_Zero;
46552   pMem->type = SQLITE_BLOB;
46553   pMem->n = 0;
46554   if( n<0 ) n = 0;
46555   pMem->u.nZero = n;
46556   pMem->enc = SQLITE_UTF8;
46557
46558 #ifdef SQLITE_OMIT_INCRBLOB
46559   sqlite3VdbeMemGrow(pMem, n, 0);
46560   if( pMem->z ){
46561     pMem->n = n;
46562     memset(pMem->z, 0, n);
46563   }
46564 #endif
46565 }
46566
46567 /*
46568 ** Delete any previous value and set the value stored in *pMem to val,
46569 ** manifest type INTEGER.
46570 */
46571 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
46572   sqlite3VdbeMemRelease(pMem);
46573   pMem->u.i = val;
46574   pMem->flags = MEM_Int;
46575   pMem->type = SQLITE_INTEGER;
46576 }
46577
46578 /*
46579 ** Delete any previous value and set the value stored in *pMem to val,
46580 ** manifest type REAL.
46581 */
46582 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
46583   if( sqlite3IsNaN(val) ){
46584     sqlite3VdbeMemSetNull(pMem);
46585   }else{
46586     sqlite3VdbeMemRelease(pMem);
46587     pMem->r = val;
46588     pMem->flags = MEM_Real;
46589     pMem->type = SQLITE_FLOAT;
46590   }
46591 }
46592
46593 /*
46594 ** Delete any previous value and set the value of pMem to be an
46595 ** empty boolean index.
46596 */
46597 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
46598   sqlite3 *db = pMem->db;
46599   assert( db!=0 );
46600   assert( (pMem->flags & MEM_RowSet)==0 );
46601   sqlite3VdbeMemRelease(pMem);
46602   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
46603   if( db->mallocFailed ){
46604     pMem->flags = MEM_Null;
46605   }else{
46606     assert( pMem->zMalloc );
46607     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
46608                                        sqlite3DbMallocSize(db, pMem->zMalloc));
46609     assert( pMem->u.pRowSet!=0 );
46610     pMem->flags = MEM_RowSet;
46611   }
46612 }
46613
46614 /*
46615 ** Return true if the Mem object contains a TEXT or BLOB that is
46616 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
46617 */
46618 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
46619   assert( p->db!=0 );
46620   if( p->flags & (MEM_Str|MEM_Blob) ){
46621     int n = p->n;
46622     if( p->flags & MEM_Zero ){
46623       n += p->u.nZero;
46624     }
46625     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
46626   }
46627   return 0; 
46628 }
46629
46630 /*
46631 ** Size of struct Mem not including the Mem.zMalloc member.
46632 */
46633 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
46634
46635 /*
46636 ** Make an shallow copy of pFrom into pTo.  Prior contents of
46637 ** pTo are freed.  The pFrom->z field is not duplicated.  If
46638 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
46639 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
46640 */
46641 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
46642   assert( (pFrom->flags & MEM_RowSet)==0 );
46643   sqlite3VdbeMemReleaseExternal(pTo);
46644   memcpy(pTo, pFrom, MEMCELLSIZE);
46645   pTo->xDel = 0;
46646   if( (pFrom->flags&MEM_Dyn)!=0 || pFrom->z==pFrom->zMalloc ){
46647     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
46648     assert( srcType==MEM_Ephem || srcType==MEM_Static );
46649     pTo->flags |= srcType;
46650   }
46651 }
46652
46653 /*
46654 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
46655 ** freed before the copy is made.
46656 */
46657 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
46658   int rc = SQLITE_OK;
46659
46660   assert( (pFrom->flags & MEM_RowSet)==0 );
46661   sqlite3VdbeMemReleaseExternal(pTo);
46662   memcpy(pTo, pFrom, MEMCELLSIZE);
46663   pTo->flags &= ~MEM_Dyn;
46664
46665   if( pTo->flags&(MEM_Str|MEM_Blob) ){
46666     if( 0==(pFrom->flags&MEM_Static) ){
46667       pTo->flags |= MEM_Ephem;
46668       rc = sqlite3VdbeMemMakeWriteable(pTo);
46669     }
46670   }
46671
46672   return rc;
46673 }
46674
46675 /*
46676 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
46677 ** freed. If pFrom contains ephemeral data, a copy is made.
46678 **
46679 ** pFrom contains an SQL NULL when this routine returns.
46680 */
46681 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
46682   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
46683   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
46684   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
46685
46686   sqlite3VdbeMemRelease(pTo);
46687   memcpy(pTo, pFrom, sizeof(Mem));
46688   pFrom->flags = MEM_Null;
46689   pFrom->xDel = 0;
46690   pFrom->zMalloc = 0;
46691 }
46692
46693 /*
46694 ** Change the value of a Mem to be a string or a BLOB.
46695 **
46696 ** The memory management strategy depends on the value of the xDel
46697 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
46698 ** string is copied into a (possibly existing) buffer managed by the 
46699 ** Mem structure. Otherwise, any existing buffer is freed and the
46700 ** pointer copied.
46701 **
46702 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
46703 ** size limit) then no memory allocation occurs.  If the string can be
46704 ** stored without allocating memory, then it is.  If a memory allocation
46705 ** is required to store the string, then value of pMem is unchanged.  In
46706 ** either case, SQLITE_TOOBIG is returned.
46707 */
46708 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
46709   Mem *pMem,          /* Memory cell to set to string value */
46710   const char *z,      /* String pointer */
46711   int n,              /* Bytes in string, or negative */
46712   u8 enc,             /* Encoding of z.  0 for BLOBs */
46713   void (*xDel)(void*) /* Destructor function */
46714 ){
46715   int nByte = n;      /* New value for pMem->n */
46716   int iLimit;         /* Maximum allowed string or blob size */
46717   u16 flags = 0;      /* New value for pMem->flags */
46718
46719   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46720   assert( (pMem->flags & MEM_RowSet)==0 );
46721
46722   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
46723   if( !z ){
46724     sqlite3VdbeMemSetNull(pMem);
46725     return SQLITE_OK;
46726   }
46727
46728   if( pMem->db ){
46729     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
46730   }else{
46731     iLimit = SQLITE_MAX_LENGTH;
46732   }
46733   flags = (enc==0?MEM_Blob:MEM_Str);
46734   if( nByte<0 ){
46735     assert( enc!=0 );
46736     if( enc==SQLITE_UTF8 ){
46737       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
46738     }else{
46739       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
46740     }
46741     flags |= MEM_Term;
46742   }
46743
46744   /* The following block sets the new values of Mem.z and Mem.xDel. It
46745   ** also sets a flag in local variable "flags" to indicate the memory
46746   ** management (one of MEM_Dyn or MEM_Static).
46747   */
46748   if( xDel==SQLITE_TRANSIENT ){
46749     int nAlloc = nByte;
46750     if( flags&MEM_Term ){
46751       nAlloc += (enc==SQLITE_UTF8?1:2);
46752     }
46753     if( nByte>iLimit ){
46754       return SQLITE_TOOBIG;
46755     }
46756     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
46757       return SQLITE_NOMEM;
46758     }
46759     memcpy(pMem->z, z, nAlloc);
46760   }else if( xDel==SQLITE_DYNAMIC ){
46761     sqlite3VdbeMemRelease(pMem);
46762     pMem->zMalloc = pMem->z = (char *)z;
46763     pMem->xDel = 0;
46764   }else{
46765     sqlite3VdbeMemRelease(pMem);
46766     pMem->z = (char *)z;
46767     pMem->xDel = xDel;
46768     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
46769   }
46770
46771   pMem->n = nByte;
46772   pMem->flags = flags;
46773   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
46774   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
46775
46776 #ifndef SQLITE_OMIT_UTF16
46777   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
46778     return SQLITE_NOMEM;
46779   }
46780 #endif
46781
46782   if( nByte>iLimit ){
46783     return SQLITE_TOOBIG;
46784   }
46785
46786   return SQLITE_OK;
46787 }
46788
46789 /*
46790 ** Compare the values contained by the two memory cells, returning
46791 ** negative, zero or positive if pMem1 is less than, equal to, or greater
46792 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
46793 ** and reals) sorted numerically, followed by text ordered by the collating
46794 ** sequence pColl and finally blob's ordered by memcmp().
46795 **
46796 ** Two NULL values are considered equal by this function.
46797 */
46798 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
46799   int rc;
46800   int f1, f2;
46801   int combined_flags;
46802
46803   f1 = pMem1->flags;
46804   f2 = pMem2->flags;
46805   combined_flags = f1|f2;
46806   assert( (combined_flags & MEM_RowSet)==0 );
46807  
46808   /* If one value is NULL, it is less than the other. If both values
46809   ** are NULL, return 0.
46810   */
46811   if( combined_flags&MEM_Null ){
46812     return (f2&MEM_Null) - (f1&MEM_Null);
46813   }
46814
46815   /* If one value is a number and the other is not, the number is less.
46816   ** If both are numbers, compare as reals if one is a real, or as integers
46817   ** if both values are integers.
46818   */
46819   if( combined_flags&(MEM_Int|MEM_Real) ){
46820     if( !(f1&(MEM_Int|MEM_Real)) ){
46821       return 1;
46822     }
46823     if( !(f2&(MEM_Int|MEM_Real)) ){
46824       return -1;
46825     }
46826     if( (f1 & f2 & MEM_Int)==0 ){
46827       double r1, r2;
46828       if( (f1&MEM_Real)==0 ){
46829         r1 = (double)pMem1->u.i;
46830       }else{
46831         r1 = pMem1->r;
46832       }
46833       if( (f2&MEM_Real)==0 ){
46834         r2 = (double)pMem2->u.i;
46835       }else{
46836         r2 = pMem2->r;
46837       }
46838       if( r1<r2 ) return -1;
46839       if( r1>r2 ) return 1;
46840       return 0;
46841     }else{
46842       assert( f1&MEM_Int );
46843       assert( f2&MEM_Int );
46844       if( pMem1->u.i < pMem2->u.i ) return -1;
46845       if( pMem1->u.i > pMem2->u.i ) return 1;
46846       return 0;
46847     }
46848   }
46849
46850   /* If one value is a string and the other is a blob, the string is less.
46851   ** If both are strings, compare using the collating functions.
46852   */
46853   if( combined_flags&MEM_Str ){
46854     if( (f1 & MEM_Str)==0 ){
46855       return 1;
46856     }
46857     if( (f2 & MEM_Str)==0 ){
46858       return -1;
46859     }
46860
46861     assert( pMem1->enc==pMem2->enc );
46862     assert( pMem1->enc==SQLITE_UTF8 || 
46863             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
46864
46865     /* The collation sequence must be defined at this point, even if
46866     ** the user deletes the collation sequence after the vdbe program is
46867     ** compiled (this was not always the case).
46868     */
46869     assert( !pColl || pColl->xCmp );
46870
46871     if( pColl ){
46872       if( pMem1->enc==pColl->enc ){
46873         /* The strings are already in the correct encoding.  Call the
46874         ** comparison function directly */
46875         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
46876       }else{
46877         const void *v1, *v2;
46878         int n1, n2;
46879         Mem c1;
46880         Mem c2;
46881         memset(&c1, 0, sizeof(c1));
46882         memset(&c2, 0, sizeof(c2));
46883         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
46884         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
46885         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
46886         n1 = v1==0 ? 0 : c1.n;
46887         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
46888         n2 = v2==0 ? 0 : c2.n;
46889         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
46890         sqlite3VdbeMemRelease(&c1);
46891         sqlite3VdbeMemRelease(&c2);
46892         return rc;
46893       }
46894     }
46895     /* If a NULL pointer was passed as the collate function, fall through
46896     ** to the blob case and use memcmp().  */
46897   }
46898  
46899   /* Both values must be blobs.  Compare using memcmp().  */
46900   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
46901   if( rc==0 ){
46902     rc = pMem1->n - pMem2->n;
46903   }
46904   return rc;
46905 }
46906
46907 /*
46908 ** Move data out of a btree key or data field and into a Mem structure.
46909 ** The data or key is taken from the entry that pCur is currently pointing
46910 ** to.  offset and amt determine what portion of the data or key to retrieve.
46911 ** key is true to get the key or false to get data.  The result is written
46912 ** into the pMem element.
46913 **
46914 ** The pMem structure is assumed to be uninitialized.  Any prior content
46915 ** is overwritten without being freed.
46916 **
46917 ** If this routine fails for any reason (malloc returns NULL or unable
46918 ** to read from the disk) then the pMem is left in an inconsistent state.
46919 */
46920 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
46921   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
46922   int offset,       /* Offset from the start of data to return bytes from. */
46923   int amt,          /* Number of bytes to return. */
46924   int key,          /* If true, retrieve from the btree key, not data. */
46925   Mem *pMem         /* OUT: Return data in this Mem structure. */
46926 ){
46927   char *zData;        /* Data from the btree layer */
46928   int available = 0;  /* Number of bytes available on the local btree page */
46929   int rc = SQLITE_OK; /* Return code */
46930
46931   assert( sqlite3BtreeCursorIsValid(pCur) );
46932
46933   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
46934   ** that both the BtShared and database handle mutexes are held. */
46935   assert( (pMem->flags & MEM_RowSet)==0 );
46936   if( key ){
46937     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
46938   }else{
46939     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
46940   }
46941   assert( zData!=0 );
46942
46943   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
46944     sqlite3VdbeMemRelease(pMem);
46945     pMem->z = &zData[offset];
46946     pMem->flags = MEM_Blob|MEM_Ephem;
46947   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
46948     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
46949     pMem->enc = 0;
46950     pMem->type = SQLITE_BLOB;
46951     if( key ){
46952       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
46953     }else{
46954       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
46955     }
46956     pMem->z[amt] = 0;
46957     pMem->z[amt+1] = 0;
46958     if( rc!=SQLITE_OK ){
46959       sqlite3VdbeMemRelease(pMem);
46960     }
46961   }
46962   pMem->n = amt;
46963
46964   return rc;
46965 }
46966
46967 /* This function is only available internally, it is not part of the
46968 ** external API. It works in a similar way to sqlite3_value_text(),
46969 ** except the data returned is in the encoding specified by the second
46970 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
46971 ** SQLITE_UTF8.
46972 **
46973 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
46974 ** If that is the case, then the result must be aligned on an even byte
46975 ** boundary.
46976 */
46977 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
46978   if( !pVal ) return 0;
46979
46980   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
46981   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
46982   assert( (pVal->flags & MEM_RowSet)==0 );
46983
46984   if( pVal->flags&MEM_Null ){
46985     return 0;
46986   }
46987   assert( (MEM_Blob>>3) == MEM_Str );
46988   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
46989   expandBlob(pVal);
46990   if( pVal->flags&MEM_Str ){
46991     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
46992     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
46993       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
46994       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
46995         return 0;
46996       }
46997     }
46998     sqlite3VdbeMemNulTerminate(pVal);
46999   }else{
47000     assert( (pVal->flags&MEM_Blob)==0 );
47001     sqlite3VdbeMemStringify(pVal, enc);
47002     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
47003   }
47004   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
47005               || pVal->db->mallocFailed );
47006   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
47007     return pVal->z;
47008   }else{
47009     return 0;
47010   }
47011 }
47012
47013 /*
47014 ** Create a new sqlite3_value object.
47015 */
47016 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
47017   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
47018   if( p ){
47019     p->flags = MEM_Null;
47020     p->type = SQLITE_NULL;
47021     p->db = db;
47022   }
47023   return p;
47024 }
47025
47026 /*
47027 ** Create a new sqlite3_value object, containing the value of pExpr.
47028 **
47029 ** This only works for very simple expressions that consist of one constant
47030 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
47031 ** be converted directly into a value, then the value is allocated and
47032 ** a pointer written to *ppVal. The caller is responsible for deallocating
47033 ** the value by passing it to sqlite3ValueFree() later on. If the expression
47034 ** cannot be converted to a value, then *ppVal is set to NULL.
47035 */
47036 SQLITE_PRIVATE int sqlite3ValueFromExpr(
47037   sqlite3 *db,              /* The database connection */
47038   Expr *pExpr,              /* The expression to evaluate */
47039   u8 enc,                   /* Encoding to use */
47040   u8 affinity,              /* Affinity to use */
47041   sqlite3_value **ppVal     /* Write the new value here */
47042 ){
47043   int op;
47044   char *zVal = 0;
47045   sqlite3_value *pVal = 0;
47046
47047   if( !pExpr ){
47048     *ppVal = 0;
47049     return SQLITE_OK;
47050   }
47051   op = pExpr->op;
47052   if( op==TK_REGISTER ){
47053     op = pExpr->op2;  /* This only happens with SQLITE_ENABLE_STAT2 */
47054   }
47055
47056   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
47057     pVal = sqlite3ValueNew(db);
47058     if( pVal==0 ) goto no_mem;
47059     if( ExprHasProperty(pExpr, EP_IntValue) ){
47060       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue);
47061     }else{
47062       zVal = sqlite3DbStrDup(db, pExpr->u.zToken);
47063       if( zVal==0 ) goto no_mem;
47064       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
47065       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
47066     }
47067     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
47068       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
47069     }else{
47070       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
47071     }
47072     if( enc!=SQLITE_UTF8 ){
47073       sqlite3VdbeChangeEncoding(pVal, enc);
47074     }
47075   }else if( op==TK_UMINUS ) {
47076     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
47077       pVal->u.i = -1 * pVal->u.i;
47078       /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
47079       pVal->r = (double)-1 * pVal->r;
47080     }
47081   }
47082 #ifndef SQLITE_OMIT_BLOB_LITERAL
47083   else if( op==TK_BLOB ){
47084     int nVal;
47085     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
47086     assert( pExpr->u.zToken[1]=='\'' );
47087     pVal = sqlite3ValueNew(db);
47088     if( !pVal ) goto no_mem;
47089     zVal = &pExpr->u.zToken[2];
47090     nVal = sqlite3Strlen30(zVal)-1;
47091     assert( zVal[nVal]=='\'' );
47092     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
47093                          0, SQLITE_DYNAMIC);
47094   }
47095 #endif
47096
47097   if( pVal ){
47098     sqlite3VdbeMemStoreType(pVal);
47099   }
47100   *ppVal = pVal;
47101   return SQLITE_OK;
47102
47103 no_mem:
47104   db->mallocFailed = 1;
47105   sqlite3DbFree(db, zVal);
47106   sqlite3ValueFree(pVal);
47107   *ppVal = 0;
47108   return SQLITE_NOMEM;
47109 }
47110
47111 /*
47112 ** Change the string value of an sqlite3_value object
47113 */
47114 SQLITE_PRIVATE void sqlite3ValueSetStr(
47115   sqlite3_value *v,     /* Value to be set */
47116   int n,                /* Length of string z */
47117   const void *z,        /* Text of the new string */
47118   u8 enc,               /* Encoding to use */
47119   void (*xDel)(void*)   /* Destructor for the string */
47120 ){
47121   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
47122 }
47123
47124 /*
47125 ** Free an sqlite3_value object
47126 */
47127 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
47128   if( !v ) return;
47129   sqlite3VdbeMemRelease((Mem *)v);
47130   sqlite3DbFree(((Mem*)v)->db, v);
47131 }
47132
47133 /*
47134 ** Return the number of bytes in the sqlite3_value object assuming
47135 ** that it uses the encoding "enc"
47136 */
47137 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
47138   Mem *p = (Mem*)pVal;
47139   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
47140     if( p->flags & MEM_Zero ){
47141       return p->n + p->u.nZero;
47142     }else{
47143       return p->n;
47144     }
47145   }
47146   return 0;
47147 }
47148
47149 /************** End of vdbemem.c *********************************************/
47150 /************** Begin file vdbeaux.c *****************************************/
47151 /*
47152 ** 2003 September 6
47153 **
47154 ** The author disclaims copyright to this source code.  In place of
47155 ** a legal notice, here is a blessing:
47156 **
47157 **    May you do good and not evil.
47158 **    May you find forgiveness for yourself and forgive others.
47159 **    May you share freely, never taking more than you give.
47160 **
47161 *************************************************************************
47162 ** This file contains code used for creating, destroying, and populating
47163 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
47164 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
47165 ** But that file was getting too big so this subroutines were split out.
47166 */
47167
47168
47169
47170 /*
47171 ** When debugging the code generator in a symbolic debugger, one can
47172 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
47173 ** as they are added to the instruction stream.
47174 */
47175 #ifdef SQLITE_DEBUG
47176 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
47177 #endif
47178
47179
47180 /*
47181 ** Create a new virtual database engine.
47182 */
47183 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
47184   Vdbe *p;
47185   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
47186   if( p==0 ) return 0;
47187   p->db = db;
47188   if( db->pVdbe ){
47189     db->pVdbe->pPrev = p;
47190   }
47191   p->pNext = db->pVdbe;
47192   p->pPrev = 0;
47193   db->pVdbe = p;
47194   p->magic = VDBE_MAGIC_INIT;
47195   return p;
47196 }
47197
47198 /*
47199 ** Remember the SQL string for a prepared statement.
47200 */
47201 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
47202   assert( isPrepareV2==1 || isPrepareV2==0 );
47203   if( p==0 ) return;
47204 #ifdef SQLITE_OMIT_TRACE
47205   if( !isPrepareV2 ) return;
47206 #endif
47207   assert( p->zSql==0 );
47208   p->zSql = sqlite3DbStrNDup(p->db, z, n);
47209   p->isPrepareV2 = (u8)isPrepareV2;
47210 }
47211
47212 /*
47213 ** Return the SQL associated with a prepared statement
47214 */
47215 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
47216   Vdbe *p = (Vdbe *)pStmt;
47217   return (p->isPrepareV2 ? p->zSql : 0);
47218 }
47219
47220 /*
47221 ** Swap all content between two VDBE structures.
47222 */
47223 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
47224   Vdbe tmp, *pTmp;
47225   char *zTmp;
47226   tmp = *pA;
47227   *pA = *pB;
47228   *pB = tmp;
47229   pTmp = pA->pNext;
47230   pA->pNext = pB->pNext;
47231   pB->pNext = pTmp;
47232   pTmp = pA->pPrev;
47233   pA->pPrev = pB->pPrev;
47234   pB->pPrev = pTmp;
47235   zTmp = pA->zSql;
47236   pA->zSql = pB->zSql;
47237   pB->zSql = zTmp;
47238   pB->isPrepareV2 = pA->isPrepareV2;
47239 }
47240
47241 #ifdef SQLITE_DEBUG
47242 /*
47243 ** Turn tracing on or off
47244 */
47245 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
47246   p->trace = trace;
47247 }
47248 #endif
47249
47250 /*
47251 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
47252 ** it was.
47253 **
47254 ** If an out-of-memory error occurs while resizing the array, return
47255 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
47256 ** unchanged (this is so that any opcodes already allocated can be 
47257 ** correctly deallocated along with the rest of the Vdbe).
47258 */
47259 static int growOpArray(Vdbe *p){
47260   VdbeOp *pNew;
47261   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
47262   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
47263   if( pNew ){
47264     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
47265     p->aOp = pNew;
47266   }
47267   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
47268 }
47269
47270 /*
47271 ** Add a new instruction to the list of instructions current in the
47272 ** VDBE.  Return the address of the new instruction.
47273 **
47274 ** Parameters:
47275 **
47276 **    p               Pointer to the VDBE
47277 **
47278 **    op              The opcode for this instruction
47279 **
47280 **    p1, p2, p3      Operands
47281 **
47282 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
47283 ** the sqlite3VdbeChangeP4() function to change the value of the P4
47284 ** operand.
47285 */
47286 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
47287   int i;
47288   VdbeOp *pOp;
47289
47290   i = p->nOp;
47291   assert( p->magic==VDBE_MAGIC_INIT );
47292   assert( op>0 && op<0xff );
47293   if( p->nOpAlloc<=i ){
47294     if( growOpArray(p) ){
47295       return 1;
47296     }
47297   }
47298   p->nOp++;
47299   pOp = &p->aOp[i];
47300   pOp->opcode = (u8)op;
47301   pOp->p5 = 0;
47302   pOp->p1 = p1;
47303   pOp->p2 = p2;
47304   pOp->p3 = p3;
47305   pOp->p4.p = 0;
47306   pOp->p4type = P4_NOTUSED;
47307   p->expired = 0;
47308 #ifdef SQLITE_DEBUG
47309   pOp->zComment = 0;
47310   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
47311 #endif
47312 #ifdef VDBE_PROFILE
47313   pOp->cycles = 0;
47314   pOp->cnt = 0;
47315 #endif
47316   return i;
47317 }
47318 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
47319   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
47320 }
47321 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
47322   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
47323 }
47324 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
47325   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
47326 }
47327
47328
47329 /*
47330 ** Add an opcode that includes the p4 value as a pointer.
47331 */
47332 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
47333   Vdbe *p,            /* Add the opcode to this VM */
47334   int op,             /* The new opcode */
47335   int p1,             /* The P1 operand */
47336   int p2,             /* The P2 operand */
47337   int p3,             /* The P3 operand */
47338   const char *zP4,    /* The P4 operand */
47339   int p4type          /* P4 operand type */
47340 ){
47341   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
47342   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
47343   return addr;
47344 }
47345
47346 /*
47347 ** Add an opcode that includes the p4 value as an integer.
47348 */
47349 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
47350   Vdbe *p,            /* Add the opcode to this VM */
47351   int op,             /* The new opcode */
47352   int p1,             /* The P1 operand */
47353   int p2,             /* The P2 operand */
47354   int p3,             /* The P3 operand */
47355   int p4              /* The P4 operand as an integer */
47356 ){
47357   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
47358   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
47359   return addr;
47360 }
47361
47362 /*
47363 ** Create a new symbolic label for an instruction that has yet to be
47364 ** coded.  The symbolic label is really just a negative number.  The
47365 ** label can be used as the P2 value of an operation.  Later, when
47366 ** the label is resolved to a specific address, the VDBE will scan
47367 ** through its operation list and change all values of P2 which match
47368 ** the label into the resolved address.
47369 **
47370 ** The VDBE knows that a P2 value is a label because labels are
47371 ** always negative and P2 values are suppose to be non-negative.
47372 ** Hence, a negative P2 value is a label that has yet to be resolved.
47373 **
47374 ** Zero is returned if a malloc() fails.
47375 */
47376 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
47377   int i;
47378   i = p->nLabel++;
47379   assert( p->magic==VDBE_MAGIC_INIT );
47380   if( i>=p->nLabelAlloc ){
47381     int n = p->nLabelAlloc*2 + 5;
47382     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
47383                                        n*sizeof(p->aLabel[0]));
47384     p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
47385   }
47386   if( p->aLabel ){
47387     p->aLabel[i] = -1;
47388   }
47389   return -1-i;
47390 }
47391
47392 /*
47393 ** Resolve label "x" to be the address of the next instruction to
47394 ** be inserted.  The parameter "x" must have been obtained from
47395 ** a prior call to sqlite3VdbeMakeLabel().
47396 */
47397 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
47398   int j = -1-x;
47399   assert( p->magic==VDBE_MAGIC_INIT );
47400   assert( j>=0 && j<p->nLabel );
47401   if( p->aLabel ){
47402     p->aLabel[j] = p->nOp;
47403   }
47404 }
47405
47406 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
47407
47408 /*
47409 ** The following type and function are used to iterate through all opcodes
47410 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
47411 ** invoke directly or indirectly. It should be used as follows:
47412 **
47413 **   Op *pOp;
47414 **   VdbeOpIter sIter;
47415 **
47416 **   memset(&sIter, 0, sizeof(sIter));
47417 **   sIter.v = v;                            // v is of type Vdbe* 
47418 **   while( (pOp = opIterNext(&sIter)) ){
47419 **     // Do something with pOp
47420 **   }
47421 **   sqlite3DbFree(v->db, sIter.apSub);
47422 ** 
47423 */
47424 typedef struct VdbeOpIter VdbeOpIter;
47425 struct VdbeOpIter {
47426   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
47427   SubProgram **apSub;        /* Array of subprograms */
47428   int nSub;                  /* Number of entries in apSub */
47429   int iAddr;                 /* Address of next instruction to return */
47430   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
47431 };
47432 static Op *opIterNext(VdbeOpIter *p){
47433   Vdbe *v = p->v;
47434   Op *pRet = 0;
47435   Op *aOp;
47436   int nOp;
47437
47438   if( p->iSub<=p->nSub ){
47439
47440     if( p->iSub==0 ){
47441       aOp = v->aOp;
47442       nOp = v->nOp;
47443     }else{
47444       aOp = p->apSub[p->iSub-1]->aOp;
47445       nOp = p->apSub[p->iSub-1]->nOp;
47446     }
47447     assert( p->iAddr<nOp );
47448
47449     pRet = &aOp[p->iAddr];
47450     p->iAddr++;
47451     if( p->iAddr==nOp ){
47452       p->iSub++;
47453       p->iAddr = 0;
47454     }
47455   
47456     if( pRet->p4type==P4_SUBPROGRAM ){
47457       int nByte = (p->nSub+1)*sizeof(SubProgram*);
47458       int j;
47459       for(j=0; j<p->nSub; j++){
47460         if( p->apSub[j]==pRet->p4.pProgram ) break;
47461       }
47462       if( j==p->nSub ){
47463         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
47464         if( !p->apSub ){
47465           pRet = 0;
47466         }else{
47467           p->apSub[p->nSub++] = pRet->p4.pProgram;
47468         }
47469       }
47470     }
47471   }
47472
47473   return pRet;
47474 }
47475
47476 /*
47477 ** Check if the program stored in the VM associated with pParse may
47478 ** throw an ABORT exception (causing the statement, but not entire transaction
47479 ** to be rolled back). This condition is true if the main program or any
47480 ** sub-programs contains any of the following:
47481 **
47482 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
47483 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
47484 **   *  OP_Destroy
47485 **   *  OP_VUpdate
47486 **   *  OP_VRename
47487 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
47488 **
47489 ** Then check that the value of Parse.mayAbort is true if an
47490 ** ABORT may be thrown, or false otherwise. Return true if it does
47491 ** match, or false otherwise. This function is intended to be used as
47492 ** part of an assert statement in the compiler. Similar to:
47493 **
47494 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
47495 */
47496 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
47497   int hasAbort = 0;
47498   Op *pOp;
47499   VdbeOpIter sIter;
47500   memset(&sIter, 0, sizeof(sIter));
47501   sIter.v = v;
47502
47503   while( (pOp = opIterNext(&sIter))!=0 ){
47504     int opcode = pOp->opcode;
47505     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
47506 #ifndef SQLITE_OMIT_FOREIGN_KEY
47507      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
47508 #endif
47509      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
47510       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
47511     ){
47512       hasAbort = 1;
47513       break;
47514     }
47515   }
47516   sqlite3DbFree(v->db, sIter.apSub);
47517
47518   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
47519   ** If malloc failed, then the while() loop above may not have iterated
47520   ** through all opcodes and hasAbort may be set incorrectly. Return
47521   ** true for this case to prevent the assert() in the callers frame
47522   ** from failing.  */
47523   return ( v->db->mallocFailed || hasAbort==mayAbort );
47524 }
47525 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
47526
47527 /*
47528 ** Loop through the program looking for P2 values that are negative
47529 ** on jump instructions.  Each such value is a label.  Resolve the
47530 ** label by setting the P2 value to its correct non-zero value.
47531 **
47532 ** This routine is called once after all opcodes have been inserted.
47533 **
47534 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
47535 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
47536 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
47537 **
47538 ** The Op.opflags field is set on all opcodes.
47539 */
47540 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
47541   int i;
47542   int nMaxArgs = *pMaxFuncArgs;
47543   Op *pOp;
47544   int *aLabel = p->aLabel;
47545   p->readOnly = 1;
47546   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
47547     u8 opcode = pOp->opcode;
47548
47549     pOp->opflags = sqlite3OpcodeProperty[opcode];
47550     if( opcode==OP_Function || opcode==OP_AggStep ){
47551       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
47552     }else if( opcode==OP_Transaction && pOp->p2!=0 ){
47553       p->readOnly = 0;
47554 #ifndef SQLITE_OMIT_VIRTUALTABLE
47555     }else if( opcode==OP_VUpdate ){
47556       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
47557     }else if( opcode==OP_VFilter ){
47558       int n;
47559       assert( p->nOp - i >= 3 );
47560       assert( pOp[-1].opcode==OP_Integer );
47561       n = pOp[-1].p1;
47562       if( n>nMaxArgs ) nMaxArgs = n;
47563 #endif
47564     }
47565
47566     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
47567       assert( -1-pOp->p2<p->nLabel );
47568       pOp->p2 = aLabel[-1-pOp->p2];
47569     }
47570   }
47571   sqlite3DbFree(p->db, p->aLabel);
47572   p->aLabel = 0;
47573
47574   *pMaxFuncArgs = nMaxArgs;
47575 }
47576
47577 /*
47578 ** Return the address of the next instruction to be inserted.
47579 */
47580 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
47581   assert( p->magic==VDBE_MAGIC_INIT );
47582   return p->nOp;
47583 }
47584
47585 /*
47586 ** This function returns a pointer to the array of opcodes associated with
47587 ** the Vdbe passed as the first argument. It is the callers responsibility
47588 ** to arrange for the returned array to be eventually freed using the 
47589 ** vdbeFreeOpArray() function.
47590 **
47591 ** Before returning, *pnOp is set to the number of entries in the returned
47592 ** array. Also, *pnMaxArg is set to the larger of its current value and 
47593 ** the number of entries in the Vdbe.apArg[] array required to execute the 
47594 ** returned program.
47595 */
47596 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
47597   VdbeOp *aOp = p->aOp;
47598   assert( aOp && !p->db->mallocFailed );
47599
47600   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
47601   assert( p->aMutex.nMutex==0 );
47602
47603   resolveP2Values(p, pnMaxArg);
47604   *pnOp = p->nOp;
47605   p->aOp = 0;
47606   return aOp;
47607 }
47608
47609 /*
47610 ** Add a whole list of operations to the operation stack.  Return the
47611 ** address of the first operation added.
47612 */
47613 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
47614   int addr;
47615   assert( p->magic==VDBE_MAGIC_INIT );
47616   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
47617     return 0;
47618   }
47619   addr = p->nOp;
47620   if( ALWAYS(nOp>0) ){
47621     int i;
47622     VdbeOpList const *pIn = aOp;
47623     for(i=0; i<nOp; i++, pIn++){
47624       int p2 = pIn->p2;
47625       VdbeOp *pOut = &p->aOp[i+addr];
47626       pOut->opcode = pIn->opcode;
47627       pOut->p1 = pIn->p1;
47628       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
47629         pOut->p2 = addr + ADDR(p2);
47630       }else{
47631         pOut->p2 = p2;
47632       }
47633       pOut->p3 = pIn->p3;
47634       pOut->p4type = P4_NOTUSED;
47635       pOut->p4.p = 0;
47636       pOut->p5 = 0;
47637 #ifdef SQLITE_DEBUG
47638       pOut->zComment = 0;
47639       if( sqlite3VdbeAddopTrace ){
47640         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
47641       }
47642 #endif
47643     }
47644     p->nOp += nOp;
47645   }
47646   return addr;
47647 }
47648
47649 /*
47650 ** Change the value of the P1 operand for a specific instruction.
47651 ** This routine is useful when a large program is loaded from a
47652 ** static array using sqlite3VdbeAddOpList but we want to make a
47653 ** few minor changes to the program.
47654 */
47655 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
47656   assert( p!=0 );
47657   assert( addr>=0 );
47658   if( p->nOp>addr ){
47659     p->aOp[addr].p1 = val;
47660   }
47661 }
47662
47663 /*
47664 ** Change the value of the P2 operand for a specific instruction.
47665 ** This routine is useful for setting a jump destination.
47666 */
47667 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
47668   assert( p!=0 );
47669   assert( addr>=0 );
47670   if( p->nOp>addr ){
47671     p->aOp[addr].p2 = val;
47672   }
47673 }
47674
47675 /*
47676 ** Change the value of the P3 operand for a specific instruction.
47677 */
47678 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
47679   assert( p!=0 );
47680   assert( addr>=0 );
47681   if( p->nOp>addr ){
47682     p->aOp[addr].p3 = val;
47683   }
47684 }
47685
47686 /*
47687 ** Change the value of the P5 operand for the most recently
47688 ** added operation.
47689 */
47690 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
47691   assert( p!=0 );
47692   if( p->aOp ){
47693     assert( p->nOp>0 );
47694     p->aOp[p->nOp-1].p5 = val;
47695   }
47696 }
47697
47698 /*
47699 ** Change the P2 operand of instruction addr so that it points to
47700 ** the address of the next instruction to be coded.
47701 */
47702 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
47703   sqlite3VdbeChangeP2(p, addr, p->nOp);
47704 }
47705
47706
47707 /*
47708 ** If the input FuncDef structure is ephemeral, then free it.  If
47709 ** the FuncDef is not ephermal, then do nothing.
47710 */
47711 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
47712   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
47713     sqlite3DbFree(db, pDef);
47714   }
47715 }
47716
47717 /*
47718 ** Delete a P4 value if necessary.
47719 */
47720 static void freeP4(sqlite3 *db, int p4type, void *p4){
47721   if( p4 ){
47722     switch( p4type ){
47723       case P4_REAL:
47724       case P4_INT64:
47725       case P4_MPRINTF:
47726       case P4_DYNAMIC:
47727       case P4_KEYINFO:
47728       case P4_INTARRAY:
47729       case P4_KEYINFO_HANDOFF: {
47730         sqlite3DbFree(db, p4);
47731         break;
47732       }
47733       case P4_VDBEFUNC: {
47734         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
47735         freeEphemeralFunction(db, pVdbeFunc->pFunc);
47736         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
47737         sqlite3DbFree(db, pVdbeFunc);
47738         break;
47739       }
47740       case P4_FUNCDEF: {
47741         freeEphemeralFunction(db, (FuncDef*)p4);
47742         break;
47743       }
47744       case P4_MEM: {
47745         sqlite3ValueFree((sqlite3_value*)p4);
47746         break;
47747       }
47748       case P4_VTAB : {
47749         sqlite3VtabUnlock((VTable *)p4);
47750         break;
47751       }
47752       case P4_SUBPROGRAM : {
47753         sqlite3VdbeProgramDelete(db, (SubProgram *)p4, 1);
47754         break;
47755       }
47756     }
47757   }
47758 }
47759
47760 /*
47761 ** Free the space allocated for aOp and any p4 values allocated for the
47762 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
47763 ** nOp entries. 
47764 */
47765 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
47766   if( aOp ){
47767     Op *pOp;
47768     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
47769       freeP4(db, pOp->p4type, pOp->p4.p);
47770 #ifdef SQLITE_DEBUG
47771       sqlite3DbFree(db, pOp->zComment);
47772 #endif     
47773     }
47774   }
47775   sqlite3DbFree(db, aOp);
47776 }
47777
47778 /*
47779 ** Decrement the ref-count on the SubProgram structure passed as the
47780 ** second argument. If the ref-count reaches zero, free the structure.
47781 **
47782 ** The array of VDBE opcodes stored as SubProgram.aOp is freed if
47783 ** either the ref-count reaches zero or parameter freeop is non-zero.
47784 **
47785 ** Since the array of opcodes pointed to by SubProgram.aOp may directly
47786 ** or indirectly contain a reference to the SubProgram structure itself.
47787 ** By passing a non-zero freeop parameter, the caller may ensure that all
47788 ** SubProgram structures and their aOp arrays are freed, even when there
47789 ** are such circular references.
47790 */
47791 SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *db, SubProgram *p, int freeop){
47792   if( p ){
47793     assert( p->nRef>0 );
47794     if( freeop || p->nRef==1 ){
47795       Op *aOp = p->aOp;
47796       p->aOp = 0;
47797       vdbeFreeOpArray(db, aOp, p->nOp);
47798       p->nOp = 0;
47799     }
47800     p->nRef--;
47801     if( p->nRef==0 ){
47802       sqlite3DbFree(db, p);
47803     }
47804   }
47805 }
47806
47807
47808 /*
47809 ** Change N opcodes starting at addr to No-ops.
47810 */
47811 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
47812   if( p->aOp ){
47813     VdbeOp *pOp = &p->aOp[addr];
47814     sqlite3 *db = p->db;
47815     while( N-- ){
47816       freeP4(db, pOp->p4type, pOp->p4.p);
47817       memset(pOp, 0, sizeof(pOp[0]));
47818       pOp->opcode = OP_Noop;
47819       pOp++;
47820     }
47821   }
47822 }
47823
47824 /*
47825 ** Change the value of the P4 operand for a specific instruction.
47826 ** This routine is useful when a large program is loaded from a
47827 ** static array using sqlite3VdbeAddOpList but we want to make a
47828 ** few minor changes to the program.
47829 **
47830 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
47831 ** the string is made into memory obtained from sqlite3_malloc().
47832 ** A value of n==0 means copy bytes of zP4 up to and including the
47833 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
47834 **
47835 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
47836 ** A copy is made of the KeyInfo structure into memory obtained from
47837 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
47838 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
47839 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
47840 ** caller should not free the allocation, it will be freed when the Vdbe is
47841 ** finalized.
47842 ** 
47843 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
47844 ** to a string or structure that is guaranteed to exist for the lifetime of
47845 ** the Vdbe. In these cases we can just copy the pointer.
47846 **
47847 ** If addr<0 then change P4 on the most recently inserted instruction.
47848 */
47849 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
47850   Op *pOp;
47851   sqlite3 *db;
47852   assert( p!=0 );
47853   db = p->db;
47854   assert( p->magic==VDBE_MAGIC_INIT );
47855   if( p->aOp==0 || db->mallocFailed ){
47856     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
47857       freeP4(db, n, (void*)*(char**)&zP4);
47858     }
47859     return;
47860   }
47861   assert( p->nOp>0 );
47862   assert( addr<p->nOp );
47863   if( addr<0 ){
47864     addr = p->nOp - 1;
47865   }
47866   pOp = &p->aOp[addr];
47867   freeP4(db, pOp->p4type, pOp->p4.p);
47868   pOp->p4.p = 0;
47869   if( n==P4_INT32 ){
47870     /* Note: this cast is safe, because the origin data point was an int
47871     ** that was cast to a (const char *). */
47872     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
47873     pOp->p4type = P4_INT32;
47874   }else if( zP4==0 ){
47875     pOp->p4.p = 0;
47876     pOp->p4type = P4_NOTUSED;
47877   }else if( n==P4_KEYINFO ){
47878     KeyInfo *pKeyInfo;
47879     int nField, nByte;
47880
47881     nField = ((KeyInfo*)zP4)->nField;
47882     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
47883     pKeyInfo = sqlite3Malloc( nByte );
47884     pOp->p4.pKeyInfo = pKeyInfo;
47885     if( pKeyInfo ){
47886       u8 *aSortOrder;
47887       memcpy(pKeyInfo, zP4, nByte);
47888       aSortOrder = pKeyInfo->aSortOrder;
47889       if( aSortOrder ){
47890         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
47891         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
47892       }
47893       pOp->p4type = P4_KEYINFO;
47894     }else{
47895       p->db->mallocFailed = 1;
47896       pOp->p4type = P4_NOTUSED;
47897     }
47898   }else if( n==P4_KEYINFO_HANDOFF ){
47899     pOp->p4.p = (void*)zP4;
47900     pOp->p4type = P4_KEYINFO;
47901   }else if( n==P4_VTAB ){
47902     pOp->p4.p = (void*)zP4;
47903     pOp->p4type = P4_VTAB;
47904     sqlite3VtabLock((VTable *)zP4);
47905     assert( ((VTable *)zP4)->db==p->db );
47906   }else if( n<0 ){
47907     pOp->p4.p = (void*)zP4;
47908     pOp->p4type = (signed char)n;
47909   }else{
47910     if( n==0 ) n = sqlite3Strlen30(zP4);
47911     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
47912     pOp->p4type = P4_DYNAMIC;
47913   }
47914 }
47915
47916 #ifndef NDEBUG
47917 /*
47918 ** Change the comment on the the most recently coded instruction.  Or
47919 ** insert a No-op and add the comment to that new instruction.  This
47920 ** makes the code easier to read during debugging.  None of this happens
47921 ** in a production build.
47922 */
47923 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
47924   va_list ap;
47925   if( !p ) return;
47926   assert( p->nOp>0 || p->aOp==0 );
47927   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
47928   if( p->nOp ){
47929     char **pz = &p->aOp[p->nOp-1].zComment;
47930     va_start(ap, zFormat);
47931     sqlite3DbFree(p->db, *pz);
47932     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
47933     va_end(ap);
47934   }
47935 }
47936 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
47937   va_list ap;
47938   if( !p ) return;
47939   sqlite3VdbeAddOp0(p, OP_Noop);
47940   assert( p->nOp>0 || p->aOp==0 );
47941   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
47942   if( p->nOp ){
47943     char **pz = &p->aOp[p->nOp-1].zComment;
47944     va_start(ap, zFormat);
47945     sqlite3DbFree(p->db, *pz);
47946     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
47947     va_end(ap);
47948   }
47949 }
47950 #endif  /* NDEBUG */
47951
47952 /*
47953 ** Return the opcode for a given address.  If the address is -1, then
47954 ** return the most recently inserted opcode.
47955 **
47956 ** If a memory allocation error has occurred prior to the calling of this
47957 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
47958 ** is readable and writable, but it has no effect.  The return of a dummy
47959 ** opcode allows the call to continue functioning after a OOM fault without
47960 ** having to check to see if the return from this routine is a valid pointer.
47961 **
47962 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
47963 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
47964 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
47965 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
47966 ** having to double-check to make sure that the result is non-negative. But
47967 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
47968 ** check the value of p->nOp-1 before continuing.
47969 */
47970 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
47971   static VdbeOp dummy;
47972   assert( p->magic==VDBE_MAGIC_INIT );
47973   if( addr<0 ){
47974 #ifdef SQLITE_OMIT_TRACE
47975     if( p->nOp==0 ) return &dummy;
47976 #endif
47977     addr = p->nOp - 1;
47978   }
47979   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
47980   if( p->db->mallocFailed ){
47981     return &dummy;
47982   }else{
47983     return &p->aOp[addr];
47984   }
47985 }
47986
47987 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
47988      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
47989 /*
47990 ** Compute a string that describes the P4 parameter for an opcode.
47991 ** Use zTemp for any required temporary buffer space.
47992 */
47993 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
47994   char *zP4 = zTemp;
47995   assert( nTemp>=20 );
47996   switch( pOp->p4type ){
47997     case P4_KEYINFO_STATIC:
47998     case P4_KEYINFO: {
47999       int i, j;
48000       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
48001       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
48002       i = sqlite3Strlen30(zTemp);
48003       for(j=0; j<pKeyInfo->nField; j++){
48004         CollSeq *pColl = pKeyInfo->aColl[j];
48005         if( pColl ){
48006           int n = sqlite3Strlen30(pColl->zName);
48007           if( i+n>nTemp-6 ){
48008             memcpy(&zTemp[i],",...",4);
48009             break;
48010           }
48011           zTemp[i++] = ',';
48012           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
48013             zTemp[i++] = '-';
48014           }
48015           memcpy(&zTemp[i], pColl->zName,n+1);
48016           i += n;
48017         }else if( i+4<nTemp-6 ){
48018           memcpy(&zTemp[i],",nil",4);
48019           i += 4;
48020         }
48021       }
48022       zTemp[i++] = ')';
48023       zTemp[i] = 0;
48024       assert( i<nTemp );
48025       break;
48026     }
48027     case P4_COLLSEQ: {
48028       CollSeq *pColl = pOp->p4.pColl;
48029       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
48030       break;
48031     }
48032     case P4_FUNCDEF: {
48033       FuncDef *pDef = pOp->p4.pFunc;
48034       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
48035       break;
48036     }
48037     case P4_INT64: {
48038       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
48039       break;
48040     }
48041     case P4_INT32: {
48042       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
48043       break;
48044     }
48045     case P4_REAL: {
48046       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
48047       break;
48048     }
48049     case P4_MEM: {
48050       Mem *pMem = pOp->p4.pMem;
48051       assert( (pMem->flags & MEM_Null)==0 );
48052       if( pMem->flags & MEM_Str ){
48053         zP4 = pMem->z;
48054       }else if( pMem->flags & MEM_Int ){
48055         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
48056       }else if( pMem->flags & MEM_Real ){
48057         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
48058       }else{
48059         assert( pMem->flags & MEM_Blob );
48060         zP4 = "(blob)";
48061       }
48062       break;
48063     }
48064 #ifndef SQLITE_OMIT_VIRTUALTABLE
48065     case P4_VTAB: {
48066       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
48067       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
48068       break;
48069     }
48070 #endif
48071     case P4_INTARRAY: {
48072       sqlite3_snprintf(nTemp, zTemp, "intarray");
48073       break;
48074     }
48075     case P4_SUBPROGRAM: {
48076       sqlite3_snprintf(nTemp, zTemp, "program");
48077       break;
48078     }
48079     default: {
48080       zP4 = pOp->p4.z;
48081       if( zP4==0 ){
48082         zP4 = zTemp;
48083         zTemp[0] = 0;
48084       }
48085     }
48086   }
48087   assert( zP4!=0 );
48088   return zP4;
48089 }
48090 #endif
48091
48092 /*
48093 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
48094 */
48095 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
48096   int mask;
48097   assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
48098   assert( i<(int)sizeof(p->btreeMask)*8 );
48099   mask = ((u32)1)<<i;
48100   if( (p->btreeMask & mask)==0 ){
48101     p->btreeMask |= mask;
48102     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
48103   }
48104 }
48105
48106
48107 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
48108 /*
48109 ** Print a single opcode.  This routine is used for debugging only.
48110 */
48111 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
48112   char *zP4;
48113   char zPtr[50];
48114   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
48115   if( pOut==0 ) pOut = stdout;
48116   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
48117   fprintf(pOut, zFormat1, pc, 
48118       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
48119 #ifdef SQLITE_DEBUG
48120       pOp->zComment ? pOp->zComment : ""
48121 #else
48122       ""
48123 #endif
48124   );
48125   fflush(pOut);
48126 }
48127 #endif
48128
48129 /*
48130 ** Release an array of N Mem elements
48131 */
48132 static void releaseMemArray(Mem *p, int N){
48133   if( p && N ){
48134     Mem *pEnd;
48135     sqlite3 *db = p->db;
48136     u8 malloc_failed = db->mallocFailed;
48137     for(pEnd=&p[N]; p<pEnd; p++){
48138       assert( (&p[1])==pEnd || p[0].db==p[1].db );
48139
48140       /* This block is really an inlined version of sqlite3VdbeMemRelease()
48141       ** that takes advantage of the fact that the memory cell value is 
48142       ** being set to NULL after releasing any dynamic resources.
48143       **
48144       ** The justification for duplicating code is that according to 
48145       ** callgrind, this causes a certain test case to hit the CPU 4.7 
48146       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
48147       ** sqlite3MemRelease() were called from here. With -O2, this jumps
48148       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
48149       ** with no indexes using a single prepared INSERT statement, bind() 
48150       ** and reset(). Inserts are grouped into a transaction.
48151       */
48152       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
48153         sqlite3VdbeMemRelease(p);
48154       }else if( p->zMalloc ){
48155         sqlite3DbFree(db, p->zMalloc);
48156         p->zMalloc = 0;
48157       }
48158
48159       p->flags = MEM_Null;
48160     }
48161     db->mallocFailed = malloc_failed;
48162   }
48163 }
48164
48165 /*
48166 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
48167 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
48168 */
48169 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
48170   int i;
48171   Mem *aMem = VdbeFrameMem(p);
48172   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
48173   for(i=0; i<p->nChildCsr; i++){
48174     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
48175   }
48176   releaseMemArray(aMem, p->nChildMem);
48177   sqlite3DbFree(p->v->db, p);
48178 }
48179
48180 #ifndef SQLITE_OMIT_EXPLAIN
48181 /*
48182 ** Give a listing of the program in the virtual machine.
48183 **
48184 ** The interface is the same as sqlite3VdbeExec().  But instead of
48185 ** running the code, it invokes the callback once for each instruction.
48186 ** This feature is used to implement "EXPLAIN".
48187 **
48188 ** When p->explain==1, each instruction is listed.  When
48189 ** p->explain==2, only OP_Explain instructions are listed and these
48190 ** are shown in a different format.  p->explain==2 is used to implement
48191 ** EXPLAIN QUERY PLAN.
48192 **
48193 ** When p->explain==1, first the main program is listed, then each of
48194 ** the trigger subprograms are listed one by one.
48195 */
48196 SQLITE_PRIVATE int sqlite3VdbeList(
48197   Vdbe *p                   /* The VDBE */
48198 ){
48199   int nRow;                            /* Stop when row count reaches this */
48200   int nSub = 0;                        /* Number of sub-vdbes seen so far */
48201   SubProgram **apSub = 0;              /* Array of sub-vdbes */
48202   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
48203   sqlite3 *db = p->db;                 /* The database connection */
48204   int i;                               /* Loop counter */
48205   int rc = SQLITE_OK;                  /* Return code */
48206   Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
48207
48208   assert( p->explain );
48209   assert( p->magic==VDBE_MAGIC_RUN );
48210   assert( db->magic==SQLITE_MAGIC_BUSY );
48211   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
48212
48213   /* Even though this opcode does not use dynamic strings for
48214   ** the result, result columns may become dynamic if the user calls
48215   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
48216   */
48217   releaseMemArray(pMem, 8);
48218
48219   if( p->rc==SQLITE_NOMEM ){
48220     /* This happens if a malloc() inside a call to sqlite3_column_text() or
48221     ** sqlite3_column_text16() failed.  */
48222     db->mallocFailed = 1;
48223     return SQLITE_ERROR;
48224   }
48225
48226   /* When the number of output rows reaches nRow, that means the
48227   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
48228   ** nRow is the sum of the number of rows in the main program, plus
48229   ** the sum of the number of rows in all trigger subprograms encountered
48230   ** so far.  The nRow value will increase as new trigger subprograms are
48231   ** encountered, but p->pc will eventually catch up to nRow.
48232   */
48233   nRow = p->nOp;
48234   if( p->explain==1 ){
48235     /* The first 8 memory cells are used for the result set.  So we will
48236     ** commandeer the 9th cell to use as storage for an array of pointers
48237     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
48238     ** cells.  */
48239     assert( p->nMem>9 );
48240     pSub = &p->aMem[9];
48241     if( pSub->flags&MEM_Blob ){
48242       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
48243       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
48244       nSub = pSub->n/sizeof(Vdbe*);
48245       apSub = (SubProgram **)pSub->z;
48246     }
48247     for(i=0; i<nSub; i++){
48248       nRow += apSub[i]->nOp;
48249     }
48250   }
48251
48252   do{
48253     i = p->pc++;
48254   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
48255   if( i>=nRow ){
48256     p->rc = SQLITE_OK;
48257     rc = SQLITE_DONE;
48258   }else if( db->u1.isInterrupted ){
48259     p->rc = SQLITE_INTERRUPT;
48260     rc = SQLITE_ERROR;
48261     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
48262   }else{
48263     char *z;
48264     Op *pOp;
48265     if( i<p->nOp ){
48266       /* The output line number is small enough that we are still in the
48267       ** main program. */
48268       pOp = &p->aOp[i];
48269     }else{
48270       /* We are currently listing subprograms.  Figure out which one and
48271       ** pick up the appropriate opcode. */
48272       int j;
48273       i -= p->nOp;
48274       for(j=0; i>=apSub[j]->nOp; j++){
48275         i -= apSub[j]->nOp;
48276       }
48277       pOp = &apSub[j]->aOp[i];
48278     }
48279     if( p->explain==1 ){
48280       pMem->flags = MEM_Int;
48281       pMem->type = SQLITE_INTEGER;
48282       pMem->u.i = i;                                /* Program counter */
48283       pMem++;
48284   
48285       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
48286       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
48287       assert( pMem->z!=0 );
48288       pMem->n = sqlite3Strlen30(pMem->z);
48289       pMem->type = SQLITE_TEXT;
48290       pMem->enc = SQLITE_UTF8;
48291       pMem++;
48292
48293       /* When an OP_Program opcode is encounter (the only opcode that has
48294       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
48295       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
48296       ** has not already been seen.
48297       */
48298       if( pOp->p4type==P4_SUBPROGRAM ){
48299         int nByte = (nSub+1)*sizeof(SubProgram*);
48300         int j;
48301         for(j=0; j<nSub; j++){
48302           if( apSub[j]==pOp->p4.pProgram ) break;
48303         }
48304         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
48305           apSub = (SubProgram **)pSub->z;
48306           apSub[nSub++] = pOp->p4.pProgram;
48307           pSub->flags |= MEM_Blob;
48308           pSub->n = nSub*sizeof(SubProgram*);
48309         }
48310       }
48311     }
48312
48313     pMem->flags = MEM_Int;
48314     pMem->u.i = pOp->p1;                          /* P1 */
48315     pMem->type = SQLITE_INTEGER;
48316     pMem++;
48317
48318     pMem->flags = MEM_Int;
48319     pMem->u.i = pOp->p2;                          /* P2 */
48320     pMem->type = SQLITE_INTEGER;
48321     pMem++;
48322
48323     if( p->explain==1 ){
48324       pMem->flags = MEM_Int;
48325       pMem->u.i = pOp->p3;                          /* P3 */
48326       pMem->type = SQLITE_INTEGER;
48327       pMem++;
48328     }
48329
48330     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
48331       assert( p->db->mallocFailed );
48332       return SQLITE_ERROR;
48333     }
48334     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
48335     z = displayP4(pOp, pMem->z, 32);
48336     if( z!=pMem->z ){
48337       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
48338     }else{
48339       assert( pMem->z!=0 );
48340       pMem->n = sqlite3Strlen30(pMem->z);
48341       pMem->enc = SQLITE_UTF8;
48342     }
48343     pMem->type = SQLITE_TEXT;
48344     pMem++;
48345
48346     if( p->explain==1 ){
48347       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
48348         assert( p->db->mallocFailed );
48349         return SQLITE_ERROR;
48350       }
48351       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
48352       pMem->n = 2;
48353       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
48354       pMem->type = SQLITE_TEXT;
48355       pMem->enc = SQLITE_UTF8;
48356       pMem++;
48357   
48358 #ifdef SQLITE_DEBUG
48359       if( pOp->zComment ){
48360         pMem->flags = MEM_Str|MEM_Term;
48361         pMem->z = pOp->zComment;
48362         pMem->n = sqlite3Strlen30(pMem->z);
48363         pMem->enc = SQLITE_UTF8;
48364         pMem->type = SQLITE_TEXT;
48365       }else
48366 #endif
48367       {
48368         pMem->flags = MEM_Null;                       /* Comment */
48369         pMem->type = SQLITE_NULL;
48370       }
48371     }
48372
48373     p->nResColumn = 8 - 5*(p->explain-1);
48374     p->rc = SQLITE_OK;
48375     rc = SQLITE_ROW;
48376   }
48377   return rc;
48378 }
48379 #endif /* SQLITE_OMIT_EXPLAIN */
48380
48381 #ifdef SQLITE_DEBUG
48382 /*
48383 ** Print the SQL that was used to generate a VDBE program.
48384 */
48385 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
48386   int nOp = p->nOp;
48387   VdbeOp *pOp;
48388   if( nOp<1 ) return;
48389   pOp = &p->aOp[0];
48390   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
48391     const char *z = pOp->p4.z;
48392     while( sqlite3Isspace(*z) ) z++;
48393     printf("SQL: [%s]\n", z);
48394   }
48395 }
48396 #endif
48397
48398 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
48399 /*
48400 ** Print an IOTRACE message showing SQL content.
48401 */
48402 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
48403   int nOp = p->nOp;
48404   VdbeOp *pOp;
48405   if( sqlite3IoTrace==0 ) return;
48406   if( nOp<1 ) return;
48407   pOp = &p->aOp[0];
48408   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
48409     int i, j;
48410     char z[1000];
48411     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
48412     for(i=0; sqlite3Isspace(z[i]); i++){}
48413     for(j=0; z[i]; i++){
48414       if( sqlite3Isspace(z[i]) ){
48415         if( z[i-1]!=' ' ){
48416           z[j++] = ' ';
48417         }
48418       }else{
48419         z[j++] = z[i];
48420       }
48421     }
48422     z[j] = 0;
48423     sqlite3IoTrace("SQL %s\n", z);
48424   }
48425 }
48426 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
48427
48428 /*
48429 ** Allocate space from a fixed size buffer and return a pointer to
48430 ** that space.  If insufficient space is available, return NULL.
48431 **
48432 ** The pBuf parameter is the initial value of a pointer which will
48433 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
48434 ** NULL, it means that memory space has already been allocated and that
48435 ** this routine should not allocate any new memory.  When pBuf is not
48436 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
48437 ** is NULL.
48438 **
48439 ** nByte is the number of bytes of space needed.
48440 **
48441 ** *ppFrom points to available space and pEnd points to the end of the
48442 ** available space.  When space is allocated, *ppFrom is advanced past
48443 ** the end of the allocated space.
48444 **
48445 ** *pnByte is a counter of the number of bytes of space that have failed
48446 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
48447 ** request, then increment *pnByte by the amount of the request.
48448 */
48449 static void *allocSpace(
48450   void *pBuf,          /* Where return pointer will be stored */
48451   int nByte,           /* Number of bytes to allocate */
48452   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
48453   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
48454   int *pnByte          /* If allocation cannot be made, increment *pnByte */
48455 ){
48456   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
48457   if( pBuf ) return pBuf;
48458   nByte = ROUND8(nByte);
48459   if( &(*ppFrom)[nByte] <= pEnd ){
48460     pBuf = (void*)*ppFrom;
48461     *ppFrom += nByte;
48462   }else{
48463     *pnByte += nByte;
48464   }
48465   return pBuf;
48466 }
48467
48468 /*
48469 ** Prepare a virtual machine for execution.  This involves things such
48470 ** as allocating stack space and initializing the program counter.
48471 ** After the VDBE has be prepped, it can be executed by one or more
48472 ** calls to sqlite3VdbeExec().  
48473 **
48474 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
48475 ** VDBE_MAGIC_RUN.
48476 **
48477 ** This function may be called more than once on a single virtual machine.
48478 ** The first call is made while compiling the SQL statement. Subsequent
48479 ** calls are made as part of the process of resetting a statement to be
48480 ** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor 
48481 ** and isExplain parameters are only passed correct values the first time
48482 ** the function is called. On subsequent calls, from sqlite3_reset(), nVar
48483 ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
48484 */
48485 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
48486   Vdbe *p,                       /* The VDBE */
48487   int nVar,                      /* Number of '?' see in the SQL statement */
48488   int nMem,                      /* Number of memory cells to allocate */
48489   int nCursor,                   /* Number of cursors to allocate */
48490   int nArg,                      /* Maximum number of args in SubPrograms */
48491   int isExplain,                 /* True if the EXPLAIN keywords is present */
48492   int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
48493 ){
48494   int n;
48495   sqlite3 *db = p->db;
48496
48497   assert( p!=0 );
48498   assert( p->magic==VDBE_MAGIC_INIT );
48499
48500   /* There should be at least one opcode.
48501   */
48502   assert( p->nOp>0 );
48503
48504   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
48505   p->magic = VDBE_MAGIC_RUN;
48506
48507   /* For each cursor required, also allocate a memory cell. Memory
48508   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
48509   ** the vdbe program. Instead they are used to allocate space for
48510   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
48511   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
48512   ** stores the blob of memory associated with cursor 1, etc.
48513   **
48514   ** See also: allocateCursor().
48515   */
48516   nMem += nCursor;
48517
48518   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
48519   ** an array to marshal SQL function arguments in. This is only done the
48520   ** first time this function is called for a given VDBE, not when it is
48521   ** being called from sqlite3_reset() to reset the virtual machine.
48522   */
48523   if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
48524     u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
48525     u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
48526     int nByte;                              /* How much extra memory needed */
48527
48528     resolveP2Values(p, &nArg);
48529     p->usesStmtJournal = (u8)usesStmtJournal;
48530     if( isExplain && nMem<10 ){
48531       nMem = 10;
48532     }
48533     memset(zCsr, 0, zEnd-zCsr);
48534     zCsr += (zCsr - (u8*)0)&7;
48535     assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
48536
48537     /* Memory for registers, parameters, cursor, etc, is allocated in two
48538     ** passes.  On the first pass, we try to reuse unused space at the 
48539     ** end of the opcode array.  If we are unable to satisfy all memory
48540     ** requirements by reusing the opcode array tail, then the second
48541     ** pass will fill in the rest using a fresh allocation.  
48542     **
48543     ** This two-pass approach that reuses as much memory as possible from
48544     ** the leftover space at the end of the opcode array can significantly
48545     ** reduce the amount of memory held by a prepared statement.
48546     */
48547     do {
48548       nByte = 0;
48549       p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
48550       p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
48551       p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
48552       p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
48553       p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
48554                             &zCsr, zEnd, &nByte);
48555       if( nByte ){
48556         p->pFree = sqlite3DbMallocZero(db, nByte);
48557       }
48558       zCsr = p->pFree;
48559       zEnd = &zCsr[nByte];
48560     }while( nByte && !db->mallocFailed );
48561
48562     p->nCursor = (u16)nCursor;
48563     if( p->aVar ){
48564       p->nVar = (ynVar)nVar;
48565       for(n=0; n<nVar; n++){
48566         p->aVar[n].flags = MEM_Null;
48567         p->aVar[n].db = db;
48568       }
48569     }
48570     if( p->aMem ){
48571       p->aMem--;                      /* aMem[] goes from 1..nMem */
48572       p->nMem = nMem;                 /*       not from 0..nMem-1 */
48573       for(n=1; n<=nMem; n++){
48574         p->aMem[n].flags = MEM_Null;
48575         p->aMem[n].db = db;
48576       }
48577     }
48578   }
48579 #ifdef SQLITE_DEBUG
48580   for(n=1; n<p->nMem; n++){
48581     assert( p->aMem[n].db==db );
48582   }
48583 #endif
48584
48585   p->pc = -1;
48586   p->rc = SQLITE_OK;
48587   p->errorAction = OE_Abort;
48588   p->explain |= isExplain;
48589   p->magic = VDBE_MAGIC_RUN;
48590   p->nChange = 0;
48591   p->cacheCtr = 1;
48592   p->minWriteFileFormat = 255;
48593   p->iStatement = 0;
48594 #ifdef VDBE_PROFILE
48595   {
48596     int i;
48597     for(i=0; i<p->nOp; i++){
48598       p->aOp[i].cnt = 0;
48599       p->aOp[i].cycles = 0;
48600     }
48601   }
48602 #endif
48603 }
48604
48605 /*
48606 ** Close a VDBE cursor and release all the resources that cursor 
48607 ** happens to hold.
48608 */
48609 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
48610   if( pCx==0 ){
48611     return;
48612   }
48613   if( pCx->pBt ){
48614     sqlite3BtreeClose(pCx->pBt);
48615     /* The pCx->pCursor will be close automatically, if it exists, by
48616     ** the call above. */
48617   }else if( pCx->pCursor ){
48618     sqlite3BtreeCloseCursor(pCx->pCursor);
48619   }
48620 #ifndef SQLITE_OMIT_VIRTUALTABLE
48621   if( pCx->pVtabCursor ){
48622     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
48623     const sqlite3_module *pModule = pCx->pModule;
48624     p->inVtabMethod = 1;
48625     (void)sqlite3SafetyOff(p->db);
48626     pModule->xClose(pVtabCursor);
48627     (void)sqlite3SafetyOn(p->db);
48628     p->inVtabMethod = 0;
48629   }
48630 #endif
48631 }
48632
48633 /*
48634 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
48635 ** is used, for example, when a trigger sub-program is halted to restore
48636 ** control to the main program.
48637 */
48638 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
48639   Vdbe *v = pFrame->v;
48640   v->aOp = pFrame->aOp;
48641   v->nOp = pFrame->nOp;
48642   v->aMem = pFrame->aMem;
48643   v->nMem = pFrame->nMem;
48644   v->apCsr = pFrame->apCsr;
48645   v->nCursor = pFrame->nCursor;
48646   v->db->lastRowid = pFrame->lastRowid;
48647   v->nChange = pFrame->nChange;
48648   return pFrame->pc;
48649 }
48650
48651 /*
48652 ** Close all cursors.
48653 **
48654 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
48655 ** cell array. This is necessary as the memory cell array may contain
48656 ** pointers to VdbeFrame objects, which may in turn contain pointers to
48657 ** open cursors.
48658 */
48659 static void closeAllCursors(Vdbe *p){
48660   if( p->pFrame ){
48661     VdbeFrame *pFrame = p->pFrame;
48662     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
48663     sqlite3VdbeFrameRestore(pFrame);
48664   }
48665   p->pFrame = 0;
48666   p->nFrame = 0;
48667
48668   if( p->apCsr ){
48669     int i;
48670     for(i=0; i<p->nCursor; i++){
48671       VdbeCursor *pC = p->apCsr[i];
48672       if( pC ){
48673         sqlite3VdbeFreeCursor(p, pC);
48674         p->apCsr[i] = 0;
48675       }
48676     }
48677   }
48678   if( p->aMem ){
48679     releaseMemArray(&p->aMem[1], p->nMem);
48680   }
48681 }
48682
48683 /*
48684 ** Clean up the VM after execution.
48685 **
48686 ** This routine will automatically close any cursors, lists, and/or
48687 ** sorters that were left open.  It also deletes the values of
48688 ** variables in the aVar[] array.
48689 */
48690 static void Cleanup(Vdbe *p){
48691   sqlite3 *db = p->db;
48692
48693 #ifdef SQLITE_DEBUG
48694   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
48695   ** Vdbe.aMem[] arrays have already been cleaned up.  */
48696   int i;
48697   for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
48698   for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
48699 #endif
48700
48701   sqlite3DbFree(db, p->zErrMsg);
48702   p->zErrMsg = 0;
48703   p->pResultSet = 0;
48704 }
48705
48706 /*
48707 ** Set the number of result columns that will be returned by this SQL
48708 ** statement. This is now set at compile time, rather than during
48709 ** execution of the vdbe program so that sqlite3_column_count() can
48710 ** be called on an SQL statement before sqlite3_step().
48711 */
48712 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
48713   Mem *pColName;
48714   int n;
48715   sqlite3 *db = p->db;
48716
48717   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
48718   sqlite3DbFree(db, p->aColName);
48719   n = nResColumn*COLNAME_N;
48720   p->nResColumn = (u16)nResColumn;
48721   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
48722   if( p->aColName==0 ) return;
48723   while( n-- > 0 ){
48724     pColName->flags = MEM_Null;
48725     pColName->db = p->db;
48726     pColName++;
48727   }
48728 }
48729
48730 /*
48731 ** Set the name of the idx'th column to be returned by the SQL statement.
48732 ** zName must be a pointer to a nul terminated string.
48733 **
48734 ** This call must be made after a call to sqlite3VdbeSetNumCols().
48735 **
48736 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
48737 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
48738 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
48739 */
48740 SQLITE_PRIVATE int sqlite3VdbeSetColName(
48741   Vdbe *p,                         /* Vdbe being configured */
48742   int idx,                         /* Index of column zName applies to */
48743   int var,                         /* One of the COLNAME_* constants */
48744   const char *zName,               /* Pointer to buffer containing name */
48745   void (*xDel)(void*)              /* Memory management strategy for zName */
48746 ){
48747   int rc;
48748   Mem *pColName;
48749   assert( idx<p->nResColumn );
48750   assert( var<COLNAME_N );
48751   if( p->db->mallocFailed ){
48752     assert( !zName || xDel!=SQLITE_DYNAMIC );
48753     return SQLITE_NOMEM;
48754   }
48755   assert( p->aColName!=0 );
48756   pColName = &(p->aColName[idx+var*p->nResColumn]);
48757   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
48758   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
48759   return rc;
48760 }
48761
48762 /*
48763 ** A read or write transaction may or may not be active on database handle
48764 ** db. If a transaction is active, commit it. If there is a
48765 ** write-transaction spanning more than one database file, this routine
48766 ** takes care of the master journal trickery.
48767 */
48768 static int vdbeCommit(sqlite3 *db, Vdbe *p){
48769   int i;
48770   int nTrans = 0;  /* Number of databases with an active write-transaction */
48771   int rc = SQLITE_OK;
48772   int needXcommit = 0;
48773
48774 #ifdef SQLITE_OMIT_VIRTUALTABLE
48775   /* With this option, sqlite3VtabSync() is defined to be simply 
48776   ** SQLITE_OK so p is not used. 
48777   */
48778   UNUSED_PARAMETER(p);
48779 #endif
48780
48781   /* Before doing anything else, call the xSync() callback for any
48782   ** virtual module tables written in this transaction. This has to
48783   ** be done before determining whether a master journal file is 
48784   ** required, as an xSync() callback may add an attached database
48785   ** to the transaction.
48786   */
48787   rc = sqlite3VtabSync(db, &p->zErrMsg);
48788   if( rc!=SQLITE_OK ){
48789     return rc;
48790   }
48791
48792   /* This loop determines (a) if the commit hook should be invoked and
48793   ** (b) how many database files have open write transactions, not 
48794   ** including the temp database. (b) is important because if more than 
48795   ** one database file has an open write transaction, a master journal
48796   ** file is required for an atomic commit.
48797   */ 
48798   for(i=0; i<db->nDb; i++){ 
48799     Btree *pBt = db->aDb[i].pBt;
48800     if( sqlite3BtreeIsInTrans(pBt) ){
48801       needXcommit = 1;
48802       if( i!=1 ) nTrans++;
48803     }
48804   }
48805
48806   /* If there are any write-transactions at all, invoke the commit hook */
48807   if( needXcommit && db->xCommitCallback ){
48808     (void)sqlite3SafetyOff(db);
48809     rc = db->xCommitCallback(db->pCommitArg);
48810     (void)sqlite3SafetyOn(db);
48811     if( rc ){
48812       return SQLITE_CONSTRAINT;
48813     }
48814   }
48815
48816   /* The simple case - no more than one database file (not counting the
48817   ** TEMP database) has a transaction active.   There is no need for the
48818   ** master-journal.
48819   **
48820   ** If the return value of sqlite3BtreeGetFilename() is a zero length
48821   ** string, it means the main database is :memory: or a temp file.  In 
48822   ** that case we do not support atomic multi-file commits, so use the 
48823   ** simple case then too.
48824   */
48825   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
48826    || nTrans<=1
48827   ){
48828     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
48829       Btree *pBt = db->aDb[i].pBt;
48830       if( pBt ){
48831         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
48832       }
48833     }
48834
48835     /* Do the commit only if all databases successfully complete phase 1. 
48836     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
48837     ** IO error while deleting or truncating a journal file. It is unlikely,
48838     ** but could happen. In this case abandon processing and return the error.
48839     */
48840     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
48841       Btree *pBt = db->aDb[i].pBt;
48842       if( pBt ){
48843         rc = sqlite3BtreeCommitPhaseTwo(pBt);
48844       }
48845     }
48846     if( rc==SQLITE_OK ){
48847       sqlite3VtabCommit(db);
48848     }
48849   }
48850
48851   /* The complex case - There is a multi-file write-transaction active.
48852   ** This requires a master journal file to ensure the transaction is
48853   ** committed atomicly.
48854   */
48855 #ifndef SQLITE_OMIT_DISKIO
48856   else{
48857     sqlite3_vfs *pVfs = db->pVfs;
48858     int needSync = 0;
48859     char *zMaster = 0;   /* File-name for the master journal */
48860     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
48861     sqlite3_file *pMaster = 0;
48862     i64 offset = 0;
48863     int res;
48864
48865     /* Select a master journal file name */
48866     do {
48867       u32 iRandom;
48868       sqlite3DbFree(db, zMaster);
48869       sqlite3_randomness(sizeof(iRandom), &iRandom);
48870       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
48871       if( !zMaster ){
48872         return SQLITE_NOMEM;
48873       }
48874       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
48875     }while( rc==SQLITE_OK && res );
48876     if( rc==SQLITE_OK ){
48877       /* Open the master journal. */
48878       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
48879           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
48880           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
48881       );
48882     }
48883     if( rc!=SQLITE_OK ){
48884       sqlite3DbFree(db, zMaster);
48885       return rc;
48886     }
48887  
48888     /* Write the name of each database file in the transaction into the new
48889     ** master journal file. If an error occurs at this point close
48890     ** and delete the master journal file. All the individual journal files
48891     ** still have 'null' as the master journal pointer, so they will roll
48892     ** back independently if a failure occurs.
48893     */
48894     for(i=0; i<db->nDb; i++){
48895       Btree *pBt = db->aDb[i].pBt;
48896       if( sqlite3BtreeIsInTrans(pBt) ){
48897         char const *zFile = sqlite3BtreeGetJournalname(pBt);
48898         if( zFile==0 || zFile[0]==0 ){
48899           continue;  /* Ignore TEMP and :memory: databases */
48900         }
48901         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
48902           needSync = 1;
48903         }
48904         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
48905         offset += sqlite3Strlen30(zFile)+1;
48906         if( rc!=SQLITE_OK ){
48907           sqlite3OsCloseFree(pMaster);
48908           sqlite3OsDelete(pVfs, zMaster, 0);
48909           sqlite3DbFree(db, zMaster);
48910           return rc;
48911         }
48912       }
48913     }
48914
48915     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
48916     ** flag is set this is not required.
48917     */
48918     if( needSync 
48919      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
48920      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
48921     ){
48922       sqlite3OsCloseFree(pMaster);
48923       sqlite3OsDelete(pVfs, zMaster, 0);
48924       sqlite3DbFree(db, zMaster);
48925       return rc;
48926     }
48927
48928     /* Sync all the db files involved in the transaction. The same call
48929     ** sets the master journal pointer in each individual journal. If
48930     ** an error occurs here, do not delete the master journal file.
48931     **
48932     ** If the error occurs during the first call to
48933     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
48934     ** master journal file will be orphaned. But we cannot delete it,
48935     ** in case the master journal file name was written into the journal
48936     ** file before the failure occurred.
48937     */
48938     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
48939       Btree *pBt = db->aDb[i].pBt;
48940       if( pBt ){
48941         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
48942       }
48943     }
48944     sqlite3OsCloseFree(pMaster);
48945     if( rc!=SQLITE_OK ){
48946       sqlite3DbFree(db, zMaster);
48947       return rc;
48948     }
48949
48950     /* Delete the master journal file. This commits the transaction. After
48951     ** doing this the directory is synced again before any individual
48952     ** transaction files are deleted.
48953     */
48954     rc = sqlite3OsDelete(pVfs, zMaster, 1);
48955     sqlite3DbFree(db, zMaster);
48956     zMaster = 0;
48957     if( rc ){
48958       return rc;
48959     }
48960
48961     /* All files and directories have already been synced, so the following
48962     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
48963     ** deleting or truncating journals. If something goes wrong while
48964     ** this is happening we don't really care. The integrity of the
48965     ** transaction is already guaranteed, but some stray 'cold' journals
48966     ** may be lying around. Returning an error code won't help matters.
48967     */
48968     disable_simulated_io_errors();
48969     sqlite3BeginBenignMalloc();
48970     for(i=0; i<db->nDb; i++){ 
48971       Btree *pBt = db->aDb[i].pBt;
48972       if( pBt ){
48973         sqlite3BtreeCommitPhaseTwo(pBt);
48974       }
48975     }
48976     sqlite3EndBenignMalloc();
48977     enable_simulated_io_errors();
48978
48979     sqlite3VtabCommit(db);
48980   }
48981 #endif
48982
48983   return rc;
48984 }
48985
48986 /* 
48987 ** This routine checks that the sqlite3.activeVdbeCnt count variable
48988 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
48989 ** currently active. An assertion fails if the two counts do not match.
48990 ** This is an internal self-check only - it is not an essential processing
48991 ** step.
48992 **
48993 ** This is a no-op if NDEBUG is defined.
48994 */
48995 #ifndef NDEBUG
48996 static void checkActiveVdbeCnt(sqlite3 *db){
48997   Vdbe *p;
48998   int cnt = 0;
48999   int nWrite = 0;
49000   p = db->pVdbe;
49001   while( p ){
49002     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
49003       cnt++;
49004       if( p->readOnly==0 ) nWrite++;
49005     }
49006     p = p->pNext;
49007   }
49008   assert( cnt==db->activeVdbeCnt );
49009   assert( nWrite==db->writeVdbeCnt );
49010 }
49011 #else
49012 #define checkActiveVdbeCnt(x)
49013 #endif
49014
49015 /*
49016 ** For every Btree that in database connection db which 
49017 ** has been modified, "trip" or invalidate each cursor in
49018 ** that Btree might have been modified so that the cursor
49019 ** can never be used again.  This happens when a rollback
49020 *** occurs.  We have to trip all the other cursors, even
49021 ** cursor from other VMs in different database connections,
49022 ** so that none of them try to use the data at which they
49023 ** were pointing and which now may have been changed due
49024 ** to the rollback.
49025 **
49026 ** Remember that a rollback can delete tables complete and
49027 ** reorder rootpages.  So it is not sufficient just to save
49028 ** the state of the cursor.  We have to invalidate the cursor
49029 ** so that it is never used again.
49030 */
49031 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
49032   int i;
49033   for(i=0; i<db->nDb; i++){
49034     Btree *p = db->aDb[i].pBt;
49035     if( p && sqlite3BtreeIsInTrans(p) ){
49036       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
49037     }
49038   }
49039 }
49040
49041 /*
49042 ** If the Vdbe passed as the first argument opened a statement-transaction,
49043 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
49044 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
49045 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
49046 ** statement transaction is commtted.
49047 **
49048 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
49049 ** Otherwise SQLITE_OK.
49050 */
49051 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
49052   sqlite3 *const db = p->db;
49053   int rc = SQLITE_OK;
49054
49055   /* If p->iStatement is greater than zero, then this Vdbe opened a 
49056   ** statement transaction that should be closed here. The only exception
49057   ** is that an IO error may have occured, causing an emergency rollback.
49058   ** In this case (db->nStatement==0), and there is nothing to do.
49059   */
49060   if( db->nStatement && p->iStatement ){
49061     int i;
49062     const int iSavepoint = p->iStatement-1;
49063
49064     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
49065     assert( db->nStatement>0 );
49066     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
49067
49068     for(i=0; i<db->nDb; i++){ 
49069       int rc2 = SQLITE_OK;
49070       Btree *pBt = db->aDb[i].pBt;
49071       if( pBt ){
49072         if( eOp==SAVEPOINT_ROLLBACK ){
49073           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
49074         }
49075         if( rc2==SQLITE_OK ){
49076           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
49077         }
49078         if( rc==SQLITE_OK ){
49079           rc = rc2;
49080         }
49081       }
49082     }
49083     db->nStatement--;
49084     p->iStatement = 0;
49085
49086     /* If the statement transaction is being rolled back, also restore the 
49087     ** database handles deferred constraint counter to the value it had when 
49088     ** the statement transaction was opened.  */
49089     if( eOp==SAVEPOINT_ROLLBACK ){
49090       db->nDeferredCons = p->nStmtDefCons;
49091     }
49092   }
49093   return rc;
49094 }
49095
49096 /*
49097 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
49098 ** this routine obtains the mutex associated with each BtShared structure
49099 ** that may be accessed by the VM passed as an argument. In doing so it
49100 ** sets the BtShared.db member of each of the BtShared structures, ensuring
49101 ** that the correct busy-handler callback is invoked if required.
49102 **
49103 ** If SQLite is not threadsafe but does support shared-cache mode, then
49104 ** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
49105 ** of all of BtShared structures accessible via the database handle 
49106 ** associated with the VM. Of course only a subset of these structures
49107 ** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
49108 ** that subset out, but there is no advantage to doing so.
49109 **
49110 ** If SQLite is not threadsafe and does not support shared-cache mode, this
49111 ** function is a no-op.
49112 */
49113 #ifndef SQLITE_OMIT_SHARED_CACHE
49114 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p){
49115 #if SQLITE_THREADSAFE
49116   sqlite3BtreeMutexArrayEnter(&p->aMutex);
49117 #else
49118   sqlite3BtreeEnterAll(p->db);
49119 #endif
49120 }
49121 #endif
49122
49123 /*
49124 ** This function is called when a transaction opened by the database 
49125 ** handle associated with the VM passed as an argument is about to be 
49126 ** committed. If there are outstanding deferred foreign key constraint
49127 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
49128 **
49129 ** If there are outstanding FK violations and this function returns 
49130 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
49131 ** an error message to it. Then return SQLITE_ERROR.
49132 */
49133 #ifndef SQLITE_OMIT_FOREIGN_KEY
49134 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
49135   sqlite3 *db = p->db;
49136   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
49137     p->rc = SQLITE_CONSTRAINT;
49138     p->errorAction = OE_Abort;
49139     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
49140     return SQLITE_ERROR;
49141   }
49142   return SQLITE_OK;
49143 }
49144 #endif
49145
49146 /*
49147 ** This routine is called the when a VDBE tries to halt.  If the VDBE
49148 ** has made changes and is in autocommit mode, then commit those
49149 ** changes.  If a rollback is needed, then do the rollback.
49150 **
49151 ** This routine is the only way to move the state of a VM from
49152 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
49153 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
49154 **
49155 ** Return an error code.  If the commit could not complete because of
49156 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
49157 ** means the close did not happen and needs to be repeated.
49158 */
49159 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
49160   int rc;                         /* Used to store transient return codes */
49161   sqlite3 *db = p->db;
49162
49163   /* This function contains the logic that determines if a statement or
49164   ** transaction will be committed or rolled back as a result of the
49165   ** execution of this virtual machine. 
49166   **
49167   ** If any of the following errors occur:
49168   **
49169   **     SQLITE_NOMEM
49170   **     SQLITE_IOERR
49171   **     SQLITE_FULL
49172   **     SQLITE_INTERRUPT
49173   **
49174   ** Then the internal cache might have been left in an inconsistent
49175   ** state.  We need to rollback the statement transaction, if there is
49176   ** one, or the complete transaction if there is no statement transaction.
49177   */
49178
49179   if( p->db->mallocFailed ){
49180     p->rc = SQLITE_NOMEM;
49181   }
49182   closeAllCursors(p);
49183   if( p->magic!=VDBE_MAGIC_RUN ){
49184     return SQLITE_OK;
49185   }
49186   checkActiveVdbeCnt(db);
49187
49188   /* No commit or rollback needed if the program never started */
49189   if( p->pc>=0 ){
49190     int mrc;   /* Primary error code from p->rc */
49191     int eStatementOp = 0;
49192     int isSpecialError;            /* Set to true if a 'special' error */
49193
49194     /* Lock all btrees used by the statement */
49195     sqlite3VdbeMutexArrayEnter(p);
49196
49197     /* Check for one of the special errors */
49198     mrc = p->rc & 0xff;
49199     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
49200     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
49201                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
49202     if( isSpecialError ){
49203       /* If the query was read-only, we need do no rollback at all. Otherwise,
49204       ** proceed with the special handling.
49205       */
49206       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
49207         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
49208           eStatementOp = SAVEPOINT_ROLLBACK;
49209         }else{
49210           /* We are forced to roll back the active transaction. Before doing
49211           ** so, abort any other statements this handle currently has active.
49212           */
49213           invalidateCursorsOnModifiedBtrees(db);
49214           sqlite3RollbackAll(db);
49215           sqlite3CloseSavepoints(db);
49216           db->autoCommit = 1;
49217         }
49218       }
49219     }
49220
49221     /* Check for immediate foreign key violations. */
49222     if( p->rc==SQLITE_OK ){
49223       sqlite3VdbeCheckFk(p, 0);
49224     }
49225   
49226     /* If the auto-commit flag is set and this is the only active writer 
49227     ** VM, then we do either a commit or rollback of the current transaction. 
49228     **
49229     ** Note: This block also runs if one of the special errors handled 
49230     ** above has occurred. 
49231     */
49232     if( !sqlite3VtabInSync(db) 
49233      && db->autoCommit 
49234      && db->writeVdbeCnt==(p->readOnly==0) 
49235     ){
49236       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
49237         if( sqlite3VdbeCheckFk(p, 1) ){
49238           sqlite3BtreeMutexArrayLeave(&p->aMutex);
49239           return SQLITE_ERROR;
49240         }
49241         /* The auto-commit flag is true, the vdbe program was successful 
49242         ** or hit an 'OR FAIL' constraint and there are no deferred foreign
49243         ** key constraints to hold up the transaction. This means a commit 
49244         ** is required.  */
49245         rc = vdbeCommit(db, p);
49246         if( rc==SQLITE_BUSY ){
49247           sqlite3BtreeMutexArrayLeave(&p->aMutex);
49248           return SQLITE_BUSY;
49249         }else if( rc!=SQLITE_OK ){
49250           p->rc = rc;
49251           sqlite3RollbackAll(db);
49252         }else{
49253           db->nDeferredCons = 0;
49254           sqlite3CommitInternalChanges(db);
49255         }
49256       }else{
49257         sqlite3RollbackAll(db);
49258       }
49259       db->nStatement = 0;
49260     }else if( eStatementOp==0 ){
49261       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
49262         eStatementOp = SAVEPOINT_RELEASE;
49263       }else if( p->errorAction==OE_Abort ){
49264         eStatementOp = SAVEPOINT_ROLLBACK;
49265       }else{
49266         invalidateCursorsOnModifiedBtrees(db);
49267         sqlite3RollbackAll(db);
49268         sqlite3CloseSavepoints(db);
49269         db->autoCommit = 1;
49270       }
49271     }
49272   
49273     /* If eStatementOp is non-zero, then a statement transaction needs to
49274     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
49275     ** do so. If this operation returns an error, and the current statement
49276     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then set the error
49277     ** code to the new value.
49278     */
49279     if( eStatementOp ){
49280       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
49281       if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
49282         p->rc = rc;
49283         sqlite3DbFree(db, p->zErrMsg);
49284         p->zErrMsg = 0;
49285       }
49286     }
49287   
49288     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
49289     ** has been rolled back, update the database connection change-counter. 
49290     */
49291     if( p->changeCntOn ){
49292       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
49293         sqlite3VdbeSetChanges(db, p->nChange);
49294       }else{
49295         sqlite3VdbeSetChanges(db, 0);
49296       }
49297       p->nChange = 0;
49298     }
49299   
49300     /* Rollback or commit any schema changes that occurred. */
49301     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
49302       sqlite3ResetInternalSchema(db, 0);
49303       db->flags = (db->flags | SQLITE_InternChanges);
49304     }
49305
49306     /* Release the locks */
49307     sqlite3BtreeMutexArrayLeave(&p->aMutex);
49308   }
49309
49310   /* We have successfully halted and closed the VM.  Record this fact. */
49311   if( p->pc>=0 ){
49312     db->activeVdbeCnt--;
49313     if( !p->readOnly ){
49314       db->writeVdbeCnt--;
49315     }
49316     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
49317   }
49318   p->magic = VDBE_MAGIC_HALT;
49319   checkActiveVdbeCnt(db);
49320   if( p->db->mallocFailed ){
49321     p->rc = SQLITE_NOMEM;
49322   }
49323
49324   /* If the auto-commit flag is set to true, then any locks that were held
49325   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
49326   ** to invoke any required unlock-notify callbacks.
49327   */
49328   if( db->autoCommit ){
49329     sqlite3ConnectionUnlocked(db);
49330   }
49331
49332   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
49333   return SQLITE_OK;
49334 }
49335
49336
49337 /*
49338 ** Each VDBE holds the result of the most recent sqlite3_step() call
49339 ** in p->rc.  This routine sets that result back to SQLITE_OK.
49340 */
49341 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
49342   p->rc = SQLITE_OK;
49343 }
49344
49345 /*
49346 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
49347 ** Write any error messages into *pzErrMsg.  Return the result code.
49348 **
49349 ** After this routine is run, the VDBE should be ready to be executed
49350 ** again.
49351 **
49352 ** To look at it another way, this routine resets the state of the
49353 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
49354 ** VDBE_MAGIC_INIT.
49355 */
49356 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
49357   sqlite3 *db;
49358   db = p->db;
49359
49360   /* If the VM did not run to completion or if it encountered an
49361   ** error, then it might not have been halted properly.  So halt
49362   ** it now.
49363   */
49364   (void)sqlite3SafetyOn(db);
49365   sqlite3VdbeHalt(p);
49366   (void)sqlite3SafetyOff(db);
49367
49368   /* If the VDBE has be run even partially, then transfer the error code
49369   ** and error message from the VDBE into the main database structure.  But
49370   ** if the VDBE has just been set to run but has not actually executed any
49371   ** instructions yet, leave the main database error information unchanged.
49372   */
49373   if( p->pc>=0 ){
49374     if( p->zErrMsg ){
49375       sqlite3BeginBenignMalloc();
49376       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
49377       sqlite3EndBenignMalloc();
49378       db->errCode = p->rc;
49379       sqlite3DbFree(db, p->zErrMsg);
49380       p->zErrMsg = 0;
49381     }else if( p->rc ){
49382       sqlite3Error(db, p->rc, 0);
49383     }else{
49384       sqlite3Error(db, SQLITE_OK, 0);
49385     }
49386   }else if( p->rc && p->expired ){
49387     /* The expired flag was set on the VDBE before the first call
49388     ** to sqlite3_step(). For consistency (since sqlite3_step() was
49389     ** called), set the database error in this case as well.
49390     */
49391     sqlite3Error(db, p->rc, 0);
49392     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
49393     sqlite3DbFree(db, p->zErrMsg);
49394     p->zErrMsg = 0;
49395   }
49396
49397   /* Reclaim all memory used by the VDBE
49398   */
49399   Cleanup(p);
49400
49401   /* Save profiling information from this VDBE run.
49402   */
49403 #ifdef VDBE_PROFILE
49404   {
49405     FILE *out = fopen("vdbe_profile.out", "a");
49406     if( out ){
49407       int i;
49408       fprintf(out, "---- ");
49409       for(i=0; i<p->nOp; i++){
49410         fprintf(out, "%02x", p->aOp[i].opcode);
49411       }
49412       fprintf(out, "\n");
49413       for(i=0; i<p->nOp; i++){
49414         fprintf(out, "%6d %10lld %8lld ",
49415            p->aOp[i].cnt,
49416            p->aOp[i].cycles,
49417            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
49418         );
49419         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
49420       }
49421       fclose(out);
49422     }
49423   }
49424 #endif
49425   p->magic = VDBE_MAGIC_INIT;
49426   return p->rc & db->errMask;
49427 }
49428  
49429 /*
49430 ** Clean up and delete a VDBE after execution.  Return an integer which is
49431 ** the result code.  Write any error message text into *pzErrMsg.
49432 */
49433 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
49434   int rc = SQLITE_OK;
49435   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
49436     rc = sqlite3VdbeReset(p);
49437     assert( (rc & p->db->errMask)==rc );
49438   }
49439   sqlite3VdbeDelete(p);
49440   return rc;
49441 }
49442
49443 /*
49444 ** Call the destructor for each auxdata entry in pVdbeFunc for which
49445 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
49446 ** are always destroyed.  To destroy all auxdata entries, call this
49447 ** routine with mask==0.
49448 */
49449 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
49450   int i;
49451   for(i=0; i<pVdbeFunc->nAux; i++){
49452     struct AuxData *pAux = &pVdbeFunc->apAux[i];
49453     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
49454       if( pAux->xDelete ){
49455         pAux->xDelete(pAux->pAux);
49456       }
49457       pAux->pAux = 0;
49458     }
49459   }
49460 }
49461
49462 /*
49463 ** Delete an entire VDBE.
49464 */
49465 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
49466   sqlite3 *db;
49467
49468   if( NEVER(p==0) ) return;
49469   db = p->db;
49470   if( p->pPrev ){
49471     p->pPrev->pNext = p->pNext;
49472   }else{
49473     assert( db->pVdbe==p );
49474     db->pVdbe = p->pNext;
49475   }
49476   if( p->pNext ){
49477     p->pNext->pPrev = p->pPrev;
49478   }
49479   releaseMemArray(p->aVar, p->nVar);
49480   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
49481   vdbeFreeOpArray(db, p->aOp, p->nOp);
49482   sqlite3DbFree(db, p->aLabel);
49483   sqlite3DbFree(db, p->aColName);
49484   sqlite3DbFree(db, p->zSql);
49485   p->magic = VDBE_MAGIC_DEAD;
49486   sqlite3DbFree(db, p->pFree);
49487   sqlite3DbFree(db, p);
49488 }
49489
49490 /*
49491 ** Make sure the cursor p is ready to read or write the row to which it
49492 ** was last positioned.  Return an error code if an OOM fault or I/O error
49493 ** prevents us from positioning the cursor to its correct position.
49494 **
49495 ** If a MoveTo operation is pending on the given cursor, then do that
49496 ** MoveTo now.  If no move is pending, check to see if the row has been
49497 ** deleted out from under the cursor and if it has, mark the row as
49498 ** a NULL row.
49499 **
49500 ** If the cursor is already pointing to the correct row and that row has
49501 ** not been deleted out from under the cursor, then this routine is a no-op.
49502 */
49503 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
49504   if( p->deferredMoveto ){
49505     int res, rc;
49506 #ifdef SQLITE_TEST
49507     extern int sqlite3_search_count;
49508 #endif
49509     assert( p->isTable );
49510     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
49511     if( rc ) return rc;
49512     p->lastRowid = p->movetoTarget;
49513     p->rowidIsValid = ALWAYS(res==0) ?1:0;
49514     if( NEVER(res<0) ){
49515       rc = sqlite3BtreeNext(p->pCursor, &res);
49516       if( rc ) return rc;
49517     }
49518 #ifdef SQLITE_TEST
49519     sqlite3_search_count++;
49520 #endif
49521     p->deferredMoveto = 0;
49522     p->cacheStatus = CACHE_STALE;
49523   }else if( ALWAYS(p->pCursor) ){
49524     int hasMoved;
49525     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
49526     if( rc ) return rc;
49527     if( hasMoved ){
49528       p->cacheStatus = CACHE_STALE;
49529       p->nullRow = 1;
49530     }
49531   }
49532   return SQLITE_OK;
49533 }
49534
49535 /*
49536 ** The following functions:
49537 **
49538 ** sqlite3VdbeSerialType()
49539 ** sqlite3VdbeSerialTypeLen()
49540 ** sqlite3VdbeSerialLen()
49541 ** sqlite3VdbeSerialPut()
49542 ** sqlite3VdbeSerialGet()
49543 **
49544 ** encapsulate the code that serializes values for storage in SQLite
49545 ** data and index records. Each serialized value consists of a
49546 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
49547 ** integer, stored as a varint.
49548 **
49549 ** In an SQLite index record, the serial type is stored directly before
49550 ** the blob of data that it corresponds to. In a table record, all serial
49551 ** types are stored at the start of the record, and the blobs of data at
49552 ** the end. Hence these functions allow the caller to handle the
49553 ** serial-type and data blob seperately.
49554 **
49555 ** The following table describes the various storage classes for data:
49556 **
49557 **   serial type        bytes of data      type
49558 **   --------------     ---------------    ---------------
49559 **      0                     0            NULL
49560 **      1                     1            signed integer
49561 **      2                     2            signed integer
49562 **      3                     3            signed integer
49563 **      4                     4            signed integer
49564 **      5                     6            signed integer
49565 **      6                     8            signed integer
49566 **      7                     8            IEEE float
49567 **      8                     0            Integer constant 0
49568 **      9                     0            Integer constant 1
49569 **     10,11                               reserved for expansion
49570 **    N>=12 and even       (N-12)/2        BLOB
49571 **    N>=13 and odd        (N-13)/2        text
49572 **
49573 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
49574 ** of SQLite will not understand those serial types.
49575 */
49576
49577 /*
49578 ** Return the serial-type for the value stored in pMem.
49579 */
49580 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
49581   int flags = pMem->flags;
49582   int n;
49583
49584   if( flags&MEM_Null ){
49585     return 0;
49586   }
49587   if( flags&MEM_Int ){
49588     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
49589 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
49590     i64 i = pMem->u.i;
49591     u64 u;
49592     if( file_format>=4 && (i&1)==i ){
49593       return 8+(u32)i;
49594     }
49595     u = i<0 ? -i : i;
49596     if( u<=127 ) return 1;
49597     if( u<=32767 ) return 2;
49598     if( u<=8388607 ) return 3;
49599     if( u<=2147483647 ) return 4;
49600     if( u<=MAX_6BYTE ) return 5;
49601     return 6;
49602   }
49603   if( flags&MEM_Real ){
49604     return 7;
49605   }
49606   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
49607   n = pMem->n;
49608   if( flags & MEM_Zero ){
49609     n += pMem->u.nZero;
49610   }
49611   assert( n>=0 );
49612   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
49613 }
49614
49615 /*
49616 ** Return the length of the data corresponding to the supplied serial-type.
49617 */
49618 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
49619   if( serial_type>=12 ){
49620     return (serial_type-12)/2;
49621   }else{
49622     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
49623     return aSize[serial_type];
49624   }
49625 }
49626
49627 /*
49628 ** If we are on an architecture with mixed-endian floating 
49629 ** points (ex: ARM7) then swap the lower 4 bytes with the 
49630 ** upper 4 bytes.  Return the result.
49631 **
49632 ** For most architectures, this is a no-op.
49633 **
49634 ** (later):  It is reported to me that the mixed-endian problem
49635 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
49636 ** that early versions of GCC stored the two words of a 64-bit
49637 ** float in the wrong order.  And that error has been propagated
49638 ** ever since.  The blame is not necessarily with GCC, though.
49639 ** GCC might have just copying the problem from a prior compiler.
49640 ** I am also told that newer versions of GCC that follow a different
49641 ** ABI get the byte order right.
49642 **
49643 ** Developers using SQLite on an ARM7 should compile and run their
49644 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
49645 ** enabled, some asserts below will ensure that the byte order of
49646 ** floating point values is correct.
49647 **
49648 ** (2007-08-30)  Frank van Vugt has studied this problem closely
49649 ** and has send his findings to the SQLite developers.  Frank
49650 ** writes that some Linux kernels offer floating point hardware
49651 ** emulation that uses only 32-bit mantissas instead of a full 
49652 ** 48-bits as required by the IEEE standard.  (This is the
49653 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
49654 ** byte swapping becomes very complicated.  To avoid problems,
49655 ** the necessary byte swapping is carried out using a 64-bit integer
49656 ** rather than a 64-bit float.  Frank assures us that the code here
49657 ** works for him.  We, the developers, have no way to independently
49658 ** verify this, but Frank seems to know what he is talking about
49659 ** so we trust him.
49660 */
49661 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
49662 static u64 floatSwap(u64 in){
49663   union {
49664     u64 r;
49665     u32 i[2];
49666   } u;
49667   u32 t;
49668
49669   u.r = in;
49670   t = u.i[0];
49671   u.i[0] = u.i[1];
49672   u.i[1] = t;
49673   return u.r;
49674 }
49675 # define swapMixedEndianFloat(X)  X = floatSwap(X)
49676 #else
49677 # define swapMixedEndianFloat(X)
49678 #endif
49679
49680 /*
49681 ** Write the serialized data blob for the value stored in pMem into 
49682 ** buf. It is assumed that the caller has allocated sufficient space.
49683 ** Return the number of bytes written.
49684 **
49685 ** nBuf is the amount of space left in buf[].  nBuf must always be
49686 ** large enough to hold the entire field.  Except, if the field is
49687 ** a blob with a zero-filled tail, then buf[] might be just the right
49688 ** size to hold everything except for the zero-filled tail.  If buf[]
49689 ** is only big enough to hold the non-zero prefix, then only write that
49690 ** prefix into buf[].  But if buf[] is large enough to hold both the
49691 ** prefix and the tail then write the prefix and set the tail to all
49692 ** zeros.
49693 **
49694 ** Return the number of bytes actually written into buf[].  The number
49695 ** of bytes in the zero-filled tail is included in the return value only
49696 ** if those bytes were zeroed in buf[].
49697 */ 
49698 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
49699   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
49700   u32 len;
49701
49702   /* Integer and Real */
49703   if( serial_type<=7 && serial_type>0 ){
49704     u64 v;
49705     u32 i;
49706     if( serial_type==7 ){
49707       assert( sizeof(v)==sizeof(pMem->r) );
49708       memcpy(&v, &pMem->r, sizeof(v));
49709       swapMixedEndianFloat(v);
49710     }else{
49711       v = pMem->u.i;
49712     }
49713     len = i = sqlite3VdbeSerialTypeLen(serial_type);
49714     assert( len<=(u32)nBuf );
49715     while( i-- ){
49716       buf[i] = (u8)(v&0xFF);
49717       v >>= 8;
49718     }
49719     return len;
49720   }
49721
49722   /* String or blob */
49723   if( serial_type>=12 ){
49724     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
49725              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
49726     assert( pMem->n<=nBuf );
49727     len = pMem->n;
49728     memcpy(buf, pMem->z, len);
49729     if( pMem->flags & MEM_Zero ){
49730       len += pMem->u.nZero;
49731       assert( nBuf>=0 );
49732       if( len > (u32)nBuf ){
49733         len = (u32)nBuf;
49734       }
49735       memset(&buf[pMem->n], 0, len-pMem->n);
49736     }
49737     return len;
49738   }
49739
49740   /* NULL or constants 0 or 1 */
49741   return 0;
49742 }
49743
49744 /*
49745 ** Deserialize the data blob pointed to by buf as serial type serial_type
49746 ** and store the result in pMem.  Return the number of bytes read.
49747 */ 
49748 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
49749   const unsigned char *buf,     /* Buffer to deserialize from */
49750   u32 serial_type,              /* Serial type to deserialize */
49751   Mem *pMem                     /* Memory cell to write value into */
49752 ){
49753   switch( serial_type ){
49754     case 10:   /* Reserved for future use */
49755     case 11:   /* Reserved for future use */
49756     case 0: {  /* NULL */
49757       pMem->flags = MEM_Null;
49758       break;
49759     }
49760     case 1: { /* 1-byte signed integer */
49761       pMem->u.i = (signed char)buf[0];
49762       pMem->flags = MEM_Int;
49763       return 1;
49764     }
49765     case 2: { /* 2-byte signed integer */
49766       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
49767       pMem->flags = MEM_Int;
49768       return 2;
49769     }
49770     case 3: { /* 3-byte signed integer */
49771       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
49772       pMem->flags = MEM_Int;
49773       return 3;
49774     }
49775     case 4: { /* 4-byte signed integer */
49776       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
49777       pMem->flags = MEM_Int;
49778       return 4;
49779     }
49780     case 5: { /* 6-byte signed integer */
49781       u64 x = (((signed char)buf[0])<<8) | buf[1];
49782       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
49783       x = (x<<32) | y;
49784       pMem->u.i = *(i64*)&x;
49785       pMem->flags = MEM_Int;
49786       return 6;
49787     }
49788     case 6:   /* 8-byte signed integer */
49789     case 7: { /* IEEE floating point */
49790       u64 x;
49791       u32 y;
49792 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
49793       /* Verify that integers and floating point values use the same
49794       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
49795       ** defined that 64-bit floating point values really are mixed
49796       ** endian.
49797       */
49798       static const u64 t1 = ((u64)0x3ff00000)<<32;
49799       static const double r1 = 1.0;
49800       u64 t2 = t1;
49801       swapMixedEndianFloat(t2);
49802       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
49803 #endif
49804
49805       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
49806       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
49807       x = (x<<32) | y;
49808       if( serial_type==6 ){
49809         pMem->u.i = *(i64*)&x;
49810         pMem->flags = MEM_Int;
49811       }else{
49812         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
49813         swapMixedEndianFloat(x);
49814         memcpy(&pMem->r, &x, sizeof(x));
49815         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
49816       }
49817       return 8;
49818     }
49819     case 8:    /* Integer 0 */
49820     case 9: {  /* Integer 1 */
49821       pMem->u.i = serial_type-8;
49822       pMem->flags = MEM_Int;
49823       return 0;
49824     }
49825     default: {
49826       u32 len = (serial_type-12)/2;
49827       pMem->z = (char *)buf;
49828       pMem->n = len;
49829       pMem->xDel = 0;
49830       if( serial_type&0x01 ){
49831         pMem->flags = MEM_Str | MEM_Ephem;
49832       }else{
49833         pMem->flags = MEM_Blob | MEM_Ephem;
49834       }
49835       return len;
49836     }
49837   }
49838   return 0;
49839 }
49840
49841
49842 /*
49843 ** Given the nKey-byte encoding of a record in pKey[], parse the
49844 ** record into a UnpackedRecord structure.  Return a pointer to
49845 ** that structure.
49846 **
49847 ** The calling function might provide szSpace bytes of memory
49848 ** space at pSpace.  This space can be used to hold the returned
49849 ** VDbeParsedRecord structure if it is large enough.  If it is
49850 ** not big enough, space is obtained from sqlite3_malloc().
49851 **
49852 ** The returned structure should be closed by a call to
49853 ** sqlite3VdbeDeleteUnpackedRecord().
49854 */ 
49855 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
49856   KeyInfo *pKeyInfo,     /* Information about the record format */
49857   int nKey,              /* Size of the binary record */
49858   const void *pKey,      /* The binary record */
49859   char *pSpace,          /* Unaligned space available to hold the object */
49860   int szSpace            /* Size of pSpace[] in bytes */
49861 ){
49862   const unsigned char *aKey = (const unsigned char *)pKey;
49863   UnpackedRecord *p;  /* The unpacked record that we will return */
49864   int nByte;          /* Memory space needed to hold p, in bytes */
49865   int d;
49866   u32 idx;
49867   u16 u;              /* Unsigned loop counter */
49868   u32 szHdr;
49869   Mem *pMem;
49870   int nOff;           /* Increase pSpace by this much to 8-byte align it */
49871   
49872   /*
49873   ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
49874   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
49875   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
49876   */
49877   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
49878   pSpace += nOff;
49879   szSpace -= nOff;
49880   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
49881   if( nByte>szSpace ){
49882     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
49883     if( p==0 ) return 0;
49884     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
49885   }else{
49886     p = (UnpackedRecord*)pSpace;
49887     p->flags = UNPACKED_NEED_DESTROY;
49888   }
49889   p->pKeyInfo = pKeyInfo;
49890   p->nField = pKeyInfo->nField + 1;
49891   p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
49892   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
49893   idx = getVarint32(aKey, szHdr);
49894   d = szHdr;
49895   u = 0;
49896   while( idx<szHdr && u<p->nField && d<=nKey ){
49897     u32 serial_type;
49898
49899     idx += getVarint32(&aKey[idx], serial_type);
49900     pMem->enc = pKeyInfo->enc;
49901     pMem->db = pKeyInfo->db;
49902     pMem->flags = 0;
49903     pMem->zMalloc = 0;
49904     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
49905     pMem++;
49906     u++;
49907   }
49908   assert( u<=pKeyInfo->nField + 1 );
49909   p->nField = u;
49910   return (void*)p;
49911 }
49912
49913 /*
49914 ** This routine destroys a UnpackedRecord object.
49915 */
49916 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
49917   int i;
49918   Mem *pMem;
49919
49920   assert( p!=0 );
49921   assert( p->flags & UNPACKED_NEED_DESTROY );
49922   for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
49923     /* The unpacked record is always constructed by the
49924     ** sqlite3VdbeUnpackRecord() function above, which makes all
49925     ** strings and blobs static.  And none of the elements are
49926     ** ever transformed, so there is never anything to delete.
49927     */
49928     if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
49929   }
49930   if( p->flags & UNPACKED_NEED_FREE ){
49931     sqlite3DbFree(p->pKeyInfo->db, p);
49932   }
49933 }
49934
49935 /*
49936 ** This function compares the two table rows or index records
49937 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
49938 ** or positive integer if key1 is less than, equal to or 
49939 ** greater than key2.  The {nKey1, pKey1} key must be a blob
49940 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
49941 ** key must be a parsed key such as obtained from
49942 ** sqlite3VdbeParseRecord.
49943 **
49944 ** Key1 and Key2 do not have to contain the same number of fields.
49945 ** The key with fewer fields is usually compares less than the 
49946 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
49947 ** and the common prefixes are equal, then key1 is less than key2.
49948 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
49949 ** equal, then the keys are considered to be equal and
49950 ** the parts beyond the common prefix are ignored.
49951 **
49952 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
49953 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
49954 ** an index key, and thus ends with a rowid value.  The last byte
49955 ** of the header will therefore be the serial type of the rowid:
49956 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
49957 ** The serial type of the final rowid will always be a single byte.
49958 ** By ignoring this last byte of the header, we force the comparison
49959 ** to ignore the rowid at the end of key1.
49960 */
49961 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
49962   int nKey1, const void *pKey1, /* Left key */
49963   UnpackedRecord *pPKey2        /* Right key */
49964 ){
49965   int d1;            /* Offset into aKey[] of next data element */
49966   u32 idx1;          /* Offset into aKey[] of next header element */
49967   u32 szHdr1;        /* Number of bytes in header */
49968   int i = 0;
49969   int nField;
49970   int rc = 0;
49971   const unsigned char *aKey1 = (const unsigned char *)pKey1;
49972   KeyInfo *pKeyInfo;
49973   Mem mem1;
49974
49975   pKeyInfo = pPKey2->pKeyInfo;
49976   mem1.enc = pKeyInfo->enc;
49977   mem1.db = pKeyInfo->db;
49978   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
49979   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
49980
49981   /* Compilers may complain that mem1.u.i is potentially uninitialized.
49982   ** We could initialize it, as shown here, to silence those complaints.
49983   ** But in fact, mem1.u.i will never actually be used initialized, and doing 
49984   ** the unnecessary initialization has a measurable negative performance
49985   ** impact, since this routine is a very high runner.  And so, we choose
49986   ** to ignore the compiler warnings and leave this variable uninitialized.
49987   */
49988   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
49989   
49990   idx1 = getVarint32(aKey1, szHdr1);
49991   d1 = szHdr1;
49992   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
49993     szHdr1--;
49994   }
49995   nField = pKeyInfo->nField;
49996   while( idx1<szHdr1 && i<pPKey2->nField ){
49997     u32 serial_type1;
49998
49999     /* Read the serial types for the next element in each key. */
50000     idx1 += getVarint32( aKey1+idx1, serial_type1 );
50001     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
50002
50003     /* Extract the values to be compared.
50004     */
50005     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
50006
50007     /* Do the comparison
50008     */
50009     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
50010                            i<nField ? pKeyInfo->aColl[i] : 0);
50011     if( rc!=0 ){
50012       assert( mem1.zMalloc==0 );  /* See comment below */
50013
50014       /* Invert the result if we are using DESC sort order. */
50015       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
50016         rc = -rc;
50017       }
50018     
50019       /* If the PREFIX_SEARCH flag is set and all fields except the final
50020       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
50021       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
50022       ** This is used by the OP_IsUnique opcode.
50023       */
50024       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
50025         assert( idx1==szHdr1 && rc );
50026         assert( mem1.flags & MEM_Int );
50027         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
50028         pPKey2->rowid = mem1.u.i;
50029       }
50030     
50031       return rc;
50032     }
50033     i++;
50034   }
50035
50036   /* No memory allocation is ever used on mem1.  Prove this using
50037   ** the following assert().  If the assert() fails, it indicates a
50038   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
50039   */
50040   assert( mem1.zMalloc==0 );
50041
50042   /* rc==0 here means that one of the keys ran out of fields and
50043   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
50044   ** flag is set, then break the tie by treating key2 as larger.
50045   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
50046   ** are considered to be equal.  Otherwise, the longer key is the 
50047   ** larger.  As it happens, the pPKey2 will always be the longer
50048   ** if there is a difference.
50049   */
50050   assert( rc==0 );
50051   if( pPKey2->flags & UNPACKED_INCRKEY ){
50052     rc = -1;
50053   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
50054     /* Leave rc==0 */
50055   }else if( idx1<szHdr1 ){
50056     rc = 1;
50057   }
50058   return rc;
50059 }
50060  
50061
50062 /*
50063 ** pCur points at an index entry created using the OP_MakeRecord opcode.
50064 ** Read the rowid (the last field in the record) and store it in *rowid.
50065 ** Return SQLITE_OK if everything works, or an error code otherwise.
50066 **
50067 ** pCur might be pointing to text obtained from a corrupt database file.
50068 ** So the content cannot be trusted.  Do appropriate checks on the content.
50069 */
50070 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
50071   i64 nCellKey = 0;
50072   int rc;
50073   u32 szHdr;        /* Size of the header */
50074   u32 typeRowid;    /* Serial type of the rowid */
50075   u32 lenRowid;     /* Size of the rowid */
50076   Mem m, v;
50077
50078   UNUSED_PARAMETER(db);
50079
50080   /* Get the size of the index entry.  Only indices entries of less
50081   ** than 2GiB are support - anything large must be database corruption.
50082   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
50083   ** this code can safely assume that nCellKey is 32-bits  
50084   */
50085   assert( sqlite3BtreeCursorIsValid(pCur) );
50086   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
50087   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
50088   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
50089
50090   /* Read in the complete content of the index entry */
50091   memset(&m, 0, sizeof(m));
50092   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
50093   if( rc ){
50094     return rc;
50095   }
50096
50097   /* The index entry must begin with a header size */
50098   (void)getVarint32((u8*)m.z, szHdr);
50099   testcase( szHdr==3 );
50100   testcase( szHdr==m.n );
50101   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
50102     goto idx_rowid_corruption;
50103   }
50104
50105   /* The last field of the index should be an integer - the ROWID.
50106   ** Verify that the last entry really is an integer. */
50107   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
50108   testcase( typeRowid==1 );
50109   testcase( typeRowid==2 );
50110   testcase( typeRowid==3 );
50111   testcase( typeRowid==4 );
50112   testcase( typeRowid==5 );
50113   testcase( typeRowid==6 );
50114   testcase( typeRowid==8 );
50115   testcase( typeRowid==9 );
50116   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
50117     goto idx_rowid_corruption;
50118   }
50119   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
50120   testcase( (u32)m.n==szHdr+lenRowid );
50121   if( unlikely((u32)m.n<szHdr+lenRowid) ){
50122     goto idx_rowid_corruption;
50123   }
50124
50125   /* Fetch the integer off the end of the index record */
50126   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
50127   *rowid = v.u.i;
50128   sqlite3VdbeMemRelease(&m);
50129   return SQLITE_OK;
50130
50131   /* Jump here if database corruption is detected after m has been
50132   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
50133 idx_rowid_corruption:
50134   testcase( m.zMalloc!=0 );
50135   sqlite3VdbeMemRelease(&m);
50136   return SQLITE_CORRUPT_BKPT;
50137 }
50138
50139 /*
50140 ** Compare the key of the index entry that cursor pC is pointing to against
50141 ** the key string in pUnpacked.  Write into *pRes a number
50142 ** that is negative, zero, or positive if pC is less than, equal to,
50143 ** or greater than pUnpacked.  Return SQLITE_OK on success.
50144 **
50145 ** pUnpacked is either created without a rowid or is truncated so that it
50146 ** omits the rowid at the end.  The rowid at the end of the index entry
50147 ** is ignored as well.  Hence, this routine only compares the prefixes 
50148 ** of the keys prior to the final rowid, not the entire key.
50149 */
50150 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
50151   VdbeCursor *pC,             /* The cursor to compare against */
50152   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
50153   int *res                    /* Write the comparison result here */
50154 ){
50155   i64 nCellKey = 0;
50156   int rc;
50157   BtCursor *pCur = pC->pCursor;
50158   Mem m;
50159
50160   assert( sqlite3BtreeCursorIsValid(pCur) );
50161   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
50162   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
50163   /* nCellKey will always be between 0 and 0xffffffff because of the say
50164   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
50165   if( nCellKey<=0 || nCellKey>0x7fffffff ){
50166     *res = 0;
50167     return SQLITE_CORRUPT;
50168   }
50169   memset(&m, 0, sizeof(m));
50170   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
50171   if( rc ){
50172     return rc;
50173   }
50174   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
50175   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
50176   sqlite3VdbeMemRelease(&m);
50177   return SQLITE_OK;
50178 }
50179
50180 /*
50181 ** This routine sets the value to be returned by subsequent calls to
50182 ** sqlite3_changes() on the database handle 'db'. 
50183 */
50184 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
50185   assert( sqlite3_mutex_held(db->mutex) );
50186   db->nChange = nChange;
50187   db->nTotalChange += nChange;
50188 }
50189
50190 /*
50191 ** Set a flag in the vdbe to update the change counter when it is finalised
50192 ** or reset.
50193 */
50194 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
50195   v->changeCntOn = 1;
50196 }
50197
50198 /*
50199 ** Mark every prepared statement associated with a database connection
50200 ** as expired.
50201 **
50202 ** An expired statement means that recompilation of the statement is
50203 ** recommend.  Statements expire when things happen that make their
50204 ** programs obsolete.  Removing user-defined functions or collating
50205 ** sequences, or changing an authorization function are the types of
50206 ** things that make prepared statements obsolete.
50207 */
50208 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
50209   Vdbe *p;
50210   for(p = db->pVdbe; p; p=p->pNext){
50211     p->expired = 1;
50212   }
50213 }
50214
50215 /*
50216 ** Return the database associated with the Vdbe.
50217 */
50218 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
50219   return v->db;
50220 }
50221
50222 /*
50223 ** Return a pointer to an sqlite3_value structure containing the value bound
50224 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
50225 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
50226 ** constants) to the value before returning it.
50227 **
50228 ** The returned value must be freed by the caller using sqlite3ValueFree().
50229 */
50230 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
50231   assert( iVar>0 );
50232   if( v ){
50233     Mem *pMem = &v->aVar[iVar-1];
50234     if( 0==(pMem->flags & MEM_Null) ){
50235       sqlite3_value *pRet = sqlite3ValueNew(v->db);
50236       if( pRet ){
50237         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
50238         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
50239         sqlite3VdbeMemStoreType((Mem *)pRet);
50240       }
50241       return pRet;
50242     }
50243   }
50244   return 0;
50245 }
50246
50247 /*
50248 ** Configure SQL variable iVar so that binding a new value to it signals
50249 ** to sqlite3_reoptimize() that re-preparing the statement may result
50250 ** in a better query plan.
50251 */
50252 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
50253   assert( iVar>0 );
50254   if( iVar>32 ){
50255     v->expmask = 0xffffffff;
50256   }else{
50257     v->expmask |= ((u32)1 << (iVar-1));
50258   }
50259 }
50260
50261 /************** End of vdbeaux.c *********************************************/
50262 /************** Begin file vdbeapi.c *****************************************/
50263 /*
50264 ** 2004 May 26
50265 **
50266 ** The author disclaims copyright to this source code.  In place of
50267 ** a legal notice, here is a blessing:
50268 **
50269 **    May you do good and not evil.
50270 **    May you find forgiveness for yourself and forgive others.
50271 **    May you share freely, never taking more than you give.
50272 **
50273 *************************************************************************
50274 **
50275 ** This file contains code use to implement APIs that are part of the
50276 ** VDBE.
50277 */
50278
50279 #ifndef SQLITE_OMIT_DEPRECATED
50280 /*
50281 ** Return TRUE (non-zero) of the statement supplied as an argument needs
50282 ** to be recompiled.  A statement needs to be recompiled whenever the
50283 ** execution environment changes in a way that would alter the program
50284 ** that sqlite3_prepare() generates.  For example, if new functions or
50285 ** collating sequences are registered or if an authorizer function is
50286 ** added or changed.
50287 */
50288 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
50289   Vdbe *p = (Vdbe*)pStmt;
50290   return p==0 || p->expired;
50291 }
50292 #endif
50293
50294 /*
50295 ** The following routine destroys a virtual machine that is created by
50296 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
50297 ** success/failure code that describes the result of executing the virtual
50298 ** machine.
50299 **
50300 ** This routine sets the error code and string returned by
50301 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
50302 */
50303 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
50304   int rc;
50305   if( pStmt==0 ){
50306     rc = SQLITE_OK;
50307   }else{
50308     Vdbe *v = (Vdbe*)pStmt;
50309     sqlite3 *db = v->db;
50310 #if SQLITE_THREADSAFE
50311     sqlite3_mutex *mutex = v->db->mutex;
50312 #endif
50313     sqlite3_mutex_enter(mutex);
50314     rc = sqlite3VdbeFinalize(v);
50315     rc = sqlite3ApiExit(db, rc);
50316     sqlite3_mutex_leave(mutex);
50317   }
50318   return rc;
50319 }
50320
50321 /*
50322 ** Terminate the current execution of an SQL statement and reset it
50323 ** back to its starting state so that it can be reused. A success code from
50324 ** the prior execution is returned.
50325 **
50326 ** This routine sets the error code and string returned by
50327 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
50328 */
50329 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
50330   int rc;
50331   if( pStmt==0 ){
50332     rc = SQLITE_OK;
50333   }else{
50334     Vdbe *v = (Vdbe*)pStmt;
50335     sqlite3_mutex_enter(v->db->mutex);
50336     rc = sqlite3VdbeReset(v);
50337     sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
50338     assert( (rc & (v->db->errMask))==rc );
50339     rc = sqlite3ApiExit(v->db, rc);
50340     sqlite3_mutex_leave(v->db->mutex);
50341   }
50342   return rc;
50343 }
50344
50345 /*
50346 ** Set all the parameters in the compiled SQL statement to NULL.
50347 */
50348 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
50349   int i;
50350   int rc = SQLITE_OK;
50351   Vdbe *p = (Vdbe*)pStmt;
50352 #if SQLITE_THREADSAFE
50353   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
50354 #endif
50355   sqlite3_mutex_enter(mutex);
50356   for(i=0; i<p->nVar; i++){
50357     sqlite3VdbeMemRelease(&p->aVar[i]);
50358     p->aVar[i].flags = MEM_Null;
50359   }
50360   if( p->isPrepareV2 && p->expmask ){
50361     p->expired = 1;
50362   }
50363   sqlite3_mutex_leave(mutex);
50364   return rc;
50365 }
50366
50367
50368 /**************************** sqlite3_value_  *******************************
50369 ** The following routines extract information from a Mem or sqlite3_value
50370 ** structure.
50371 */
50372 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
50373   Mem *p = (Mem*)pVal;
50374   if( p->flags & (MEM_Blob|MEM_Str) ){
50375     sqlite3VdbeMemExpandBlob(p);
50376     p->flags &= ~MEM_Str;
50377     p->flags |= MEM_Blob;
50378     return p->z;
50379   }else{
50380     return sqlite3_value_text(pVal);
50381   }
50382 }
50383 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
50384   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
50385 }
50386 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
50387   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
50388 }
50389 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
50390   return sqlite3VdbeRealValue((Mem*)pVal);
50391 }
50392 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
50393   return (int)sqlite3VdbeIntValue((Mem*)pVal);
50394 }
50395 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
50396   return sqlite3VdbeIntValue((Mem*)pVal);
50397 }
50398 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
50399   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
50400 }
50401 #ifndef SQLITE_OMIT_UTF16
50402 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
50403   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
50404 }
50405 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
50406   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
50407 }
50408 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
50409   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
50410 }
50411 #endif /* SQLITE_OMIT_UTF16 */
50412 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
50413   return pVal->type;
50414 }
50415
50416 /**************************** sqlite3_result_  *******************************
50417 ** The following routines are used by user-defined functions to specify
50418 ** the function result.
50419 **
50420 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
50421 ** result as a string or blob but if the string or blob is too large, it
50422 ** then sets the error code to SQLITE_TOOBIG
50423 */
50424 static void setResultStrOrError(
50425   sqlite3_context *pCtx,  /* Function context */
50426   const char *z,          /* String pointer */
50427   int n,                  /* Bytes in string, or negative */
50428   u8 enc,                 /* Encoding of z.  0 for BLOBs */
50429   void (*xDel)(void*)     /* Destructor function */
50430 ){
50431   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
50432     sqlite3_result_error_toobig(pCtx);
50433   }
50434 }
50435 SQLITE_API void sqlite3_result_blob(
50436   sqlite3_context *pCtx, 
50437   const void *z, 
50438   int n, 
50439   void (*xDel)(void *)
50440 ){
50441   assert( n>=0 );
50442   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50443   setResultStrOrError(pCtx, z, n, 0, xDel);
50444 }
50445 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
50446   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50447   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
50448 }
50449 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
50450   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50451   pCtx->isError = SQLITE_ERROR;
50452   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
50453 }
50454 #ifndef SQLITE_OMIT_UTF16
50455 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
50456   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50457   pCtx->isError = SQLITE_ERROR;
50458   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
50459 }
50460 #endif
50461 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
50462   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50463   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
50464 }
50465 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
50466   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50467   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
50468 }
50469 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
50470   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50471   sqlite3VdbeMemSetNull(&pCtx->s);
50472 }
50473 SQLITE_API void sqlite3_result_text(
50474   sqlite3_context *pCtx, 
50475   const char *z, 
50476   int n,
50477   void (*xDel)(void *)
50478 ){
50479   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50480   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
50481 }
50482 #ifndef SQLITE_OMIT_UTF16
50483 SQLITE_API void sqlite3_result_text16(
50484   sqlite3_context *pCtx, 
50485   const void *z, 
50486   int n, 
50487   void (*xDel)(void *)
50488 ){
50489   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50490   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
50491 }
50492 SQLITE_API void sqlite3_result_text16be(
50493   sqlite3_context *pCtx, 
50494   const void *z, 
50495   int n, 
50496   void (*xDel)(void *)
50497 ){
50498   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50499   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
50500 }
50501 SQLITE_API void sqlite3_result_text16le(
50502   sqlite3_context *pCtx, 
50503   const void *z, 
50504   int n, 
50505   void (*xDel)(void *)
50506 ){
50507   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50508   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
50509 }
50510 #endif /* SQLITE_OMIT_UTF16 */
50511 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
50512   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50513   sqlite3VdbeMemCopy(&pCtx->s, pValue);
50514 }
50515 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
50516   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50517   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
50518 }
50519 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
50520   pCtx->isError = errCode;
50521   if( pCtx->s.flags & MEM_Null ){
50522     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
50523                          SQLITE_UTF8, SQLITE_STATIC);
50524   }
50525 }
50526
50527 /* Force an SQLITE_TOOBIG error. */
50528 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
50529   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50530   pCtx->isError = SQLITE_TOOBIG;
50531   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
50532                        SQLITE_UTF8, SQLITE_STATIC);
50533 }
50534
50535 /* An SQLITE_NOMEM error. */
50536 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
50537   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50538   sqlite3VdbeMemSetNull(&pCtx->s);
50539   pCtx->isError = SQLITE_NOMEM;
50540   pCtx->s.db->mallocFailed = 1;
50541 }
50542
50543 /*
50544 ** Execute the statement pStmt, either until a row of data is ready, the
50545 ** statement is completely executed or an error occurs.
50546 **
50547 ** This routine implements the bulk of the logic behind the sqlite_step()
50548 ** API.  The only thing omitted is the automatic recompile if a 
50549 ** schema change has occurred.  That detail is handled by the
50550 ** outer sqlite3_step() wrapper procedure.
50551 */
50552 static int sqlite3Step(Vdbe *p){
50553   sqlite3 *db;
50554   int rc;
50555
50556   assert(p);
50557   if( p->magic!=VDBE_MAGIC_RUN ){
50558     return SQLITE_MISUSE;
50559   }
50560
50561   /* Assert that malloc() has not failed */
50562   db = p->db;
50563   if( db->mallocFailed ){
50564     return SQLITE_NOMEM;
50565   }
50566
50567   if( p->pc<=0 && p->expired ){
50568     if( ALWAYS(p->rc==SQLITE_OK || p->rc==SQLITE_SCHEMA) ){
50569       p->rc = SQLITE_SCHEMA;
50570     }
50571     rc = SQLITE_ERROR;
50572     goto end_of_step;
50573   }
50574   if( sqlite3SafetyOn(db) ){
50575     p->rc = SQLITE_MISUSE;
50576     return SQLITE_MISUSE;
50577   }
50578   if( p->pc<0 ){
50579     /* If there are no other statements currently running, then
50580     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
50581     ** from interrupting a statement that has not yet started.
50582     */
50583     if( db->activeVdbeCnt==0 ){
50584       db->u1.isInterrupted = 0;
50585     }
50586
50587     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
50588
50589 #ifndef SQLITE_OMIT_TRACE
50590     if( db->xProfile && !db->init.busy ){
50591       double rNow;
50592       sqlite3OsCurrentTime(db->pVfs, &rNow);
50593       p->startTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
50594     }
50595 #endif
50596
50597     db->activeVdbeCnt++;
50598     if( p->readOnly==0 ) db->writeVdbeCnt++;
50599     p->pc = 0;
50600   }
50601 #ifndef SQLITE_OMIT_EXPLAIN
50602   if( p->explain ){
50603     rc = sqlite3VdbeList(p);
50604   }else
50605 #endif /* SQLITE_OMIT_EXPLAIN */
50606   {
50607     rc = sqlite3VdbeExec(p);
50608   }
50609
50610   if( sqlite3SafetyOff(db) ){
50611     rc = SQLITE_MISUSE;
50612   }
50613
50614 #ifndef SQLITE_OMIT_TRACE
50615   /* Invoke the profile callback if there is one
50616   */
50617   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
50618     double rNow;
50619     u64 elapseTime;
50620
50621     sqlite3OsCurrentTime(db->pVfs, &rNow);
50622     elapseTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
50623     elapseTime -= p->startTime;
50624     db->xProfile(db->pProfileArg, p->zSql, elapseTime);
50625   }
50626 #endif
50627
50628   db->errCode = rc;
50629   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
50630     p->rc = SQLITE_NOMEM;
50631   }
50632 end_of_step:
50633   /* At this point local variable rc holds the value that should be 
50634   ** returned if this statement was compiled using the legacy 
50635   ** sqlite3_prepare() interface. According to the docs, this can only
50636   ** be one of the values in the first assert() below. Variable p->rc 
50637   ** contains the value that would be returned if sqlite3_finalize() 
50638   ** were called on statement p.
50639   */
50640   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
50641        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
50642   );
50643   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
50644   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
50645     /* If this statement was prepared using sqlite3_prepare_v2(), and an
50646     ** error has occured, then return the error code in p->rc to the
50647     ** caller. Set the error code in the database handle to the same value.
50648     */ 
50649     rc = db->errCode = p->rc;
50650   }
50651   return (rc&db->errMask);
50652 }
50653
50654 /*
50655 ** This is the top-level implementation of sqlite3_step().  Call
50656 ** sqlite3Step() to do most of the work.  If a schema error occurs,
50657 ** call sqlite3Reprepare() and try again.
50658 */
50659 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
50660   int rc = SQLITE_MISUSE;
50661   if( pStmt ){
50662     int cnt = 0;
50663     Vdbe *v = (Vdbe*)pStmt;
50664     sqlite3 *db = v->db;
50665     sqlite3_mutex_enter(db->mutex);
50666     while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
50667            && cnt++ < 5
50668            && (rc = sqlite3Reprepare(v))==SQLITE_OK ){
50669       sqlite3_reset(pStmt);
50670       v->expired = 0;
50671     }
50672     if( rc==SQLITE_SCHEMA && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
50673       /* This case occurs after failing to recompile an sql statement. 
50674       ** The error message from the SQL compiler has already been loaded 
50675       ** into the database handle. This block copies the error message 
50676       ** from the database handle into the statement and sets the statement
50677       ** program counter to 0 to ensure that when the statement is 
50678       ** finalized or reset the parser error message is available via
50679       ** sqlite3_errmsg() and sqlite3_errcode().
50680       */
50681       const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
50682       sqlite3DbFree(db, v->zErrMsg);
50683       if( !db->mallocFailed ){
50684         v->zErrMsg = sqlite3DbStrDup(db, zErr);
50685       } else {
50686         v->zErrMsg = 0;
50687         v->rc = SQLITE_NOMEM;
50688       }
50689     }
50690     rc = sqlite3ApiExit(db, rc);
50691     sqlite3_mutex_leave(db->mutex);
50692   }
50693   return rc;
50694 }
50695
50696 /*
50697 ** Extract the user data from a sqlite3_context structure and return a
50698 ** pointer to it.
50699 */
50700 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
50701   assert( p && p->pFunc );
50702   return p->pFunc->pUserData;
50703 }
50704
50705 /*
50706 ** Extract the user data from a sqlite3_context structure and return a
50707 ** pointer to it.
50708 */
50709 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
50710   assert( p && p->pFunc );
50711   return p->s.db;
50712 }
50713
50714 /*
50715 ** The following is the implementation of an SQL function that always
50716 ** fails with an error message stating that the function is used in the
50717 ** wrong context.  The sqlite3_overload_function() API might construct
50718 ** SQL function that use this routine so that the functions will exist
50719 ** for name resolution but are actually overloaded by the xFindFunction
50720 ** method of virtual tables.
50721 */
50722 SQLITE_PRIVATE void sqlite3InvalidFunction(
50723   sqlite3_context *context,  /* The function calling context */
50724   int NotUsed,               /* Number of arguments to the function */
50725   sqlite3_value **NotUsed2   /* Value of each argument */
50726 ){
50727   const char *zName = context->pFunc->zName;
50728   char *zErr;
50729   UNUSED_PARAMETER2(NotUsed, NotUsed2);
50730   zErr = sqlite3_mprintf(
50731       "unable to use function %s in the requested context", zName);
50732   sqlite3_result_error(context, zErr, -1);
50733   sqlite3_free(zErr);
50734 }
50735
50736 /*
50737 ** Allocate or return the aggregate context for a user function.  A new
50738 ** context is allocated on the first call.  Subsequent calls return the
50739 ** same context that was returned on prior calls.
50740 */
50741 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
50742   Mem *pMem;
50743   assert( p && p->pFunc && p->pFunc->xStep );
50744   assert( sqlite3_mutex_held(p->s.db->mutex) );
50745   pMem = p->pMem;
50746   testcase( nByte<0 );
50747   if( (pMem->flags & MEM_Agg)==0 ){
50748     if( nByte<=0 ){
50749       sqlite3VdbeMemReleaseExternal(pMem);
50750       pMem->flags = MEM_Null;
50751       pMem->z = 0;
50752     }else{
50753       sqlite3VdbeMemGrow(pMem, nByte, 0);
50754       pMem->flags = MEM_Agg;
50755       pMem->u.pDef = p->pFunc;
50756       if( pMem->z ){
50757         memset(pMem->z, 0, nByte);
50758       }
50759     }
50760   }
50761   return (void*)pMem->z;
50762 }
50763
50764 /*
50765 ** Return the auxilary data pointer, if any, for the iArg'th argument to
50766 ** the user-function defined by pCtx.
50767 */
50768 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
50769   VdbeFunc *pVdbeFunc;
50770
50771   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50772   pVdbeFunc = pCtx->pVdbeFunc;
50773   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
50774     return 0;
50775   }
50776   return pVdbeFunc->apAux[iArg].pAux;
50777 }
50778
50779 /*
50780 ** Set the auxilary data pointer and delete function, for the iArg'th
50781 ** argument to the user-function defined by pCtx. Any previous value is
50782 ** deleted by calling the delete function specified when it was set.
50783 */
50784 SQLITE_API void sqlite3_set_auxdata(
50785   sqlite3_context *pCtx, 
50786   int iArg, 
50787   void *pAux, 
50788   void (*xDelete)(void*)
50789 ){
50790   struct AuxData *pAuxData;
50791   VdbeFunc *pVdbeFunc;
50792   if( iArg<0 ) goto failed;
50793
50794   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50795   pVdbeFunc = pCtx->pVdbeFunc;
50796   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
50797     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
50798     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
50799     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
50800     if( !pVdbeFunc ){
50801       goto failed;
50802     }
50803     pCtx->pVdbeFunc = pVdbeFunc;
50804     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
50805     pVdbeFunc->nAux = iArg+1;
50806     pVdbeFunc->pFunc = pCtx->pFunc;
50807   }
50808
50809   pAuxData = &pVdbeFunc->apAux[iArg];
50810   if( pAuxData->pAux && pAuxData->xDelete ){
50811     pAuxData->xDelete(pAuxData->pAux);
50812   }
50813   pAuxData->pAux = pAux;
50814   pAuxData->xDelete = xDelete;
50815   return;
50816
50817 failed:
50818   if( xDelete ){
50819     xDelete(pAux);
50820   }
50821 }
50822
50823 #ifndef SQLITE_OMIT_DEPRECATED
50824 /*
50825 ** Return the number of times the Step function of a aggregate has been 
50826 ** called.
50827 **
50828 ** This function is deprecated.  Do not use it for new code.  It is
50829 ** provide only to avoid breaking legacy code.  New aggregate function
50830 ** implementations should keep their own counts within their aggregate
50831 ** context.
50832 */
50833 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
50834   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
50835   return p->pMem->n;
50836 }
50837 #endif
50838
50839 /*
50840 ** Return the number of columns in the result set for the statement pStmt.
50841 */
50842 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
50843   Vdbe *pVm = (Vdbe *)pStmt;
50844   return pVm ? pVm->nResColumn : 0;
50845 }
50846
50847 /*
50848 ** Return the number of values available from the current row of the
50849 ** currently executing statement pStmt.
50850 */
50851 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
50852   Vdbe *pVm = (Vdbe *)pStmt;
50853   if( pVm==0 || pVm->pResultSet==0 ) return 0;
50854   return pVm->nResColumn;
50855 }
50856
50857
50858 /*
50859 ** Check to see if column iCol of the given statement is valid.  If
50860 ** it is, return a pointer to the Mem for the value of that column.
50861 ** If iCol is not valid, return a pointer to a Mem which has a value
50862 ** of NULL.
50863 */
50864 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
50865   Vdbe *pVm;
50866   int vals;
50867   Mem *pOut;
50868
50869   pVm = (Vdbe *)pStmt;
50870   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
50871     sqlite3_mutex_enter(pVm->db->mutex);
50872     vals = sqlite3_data_count(pStmt);
50873     pOut = &pVm->pResultSet[i];
50874   }else{
50875     /* If the value passed as the second argument is out of range, return
50876     ** a pointer to the following static Mem object which contains the
50877     ** value SQL NULL. Even though the Mem structure contains an element
50878     ** of type i64, on certain architecture (x86) with certain compiler
50879     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
50880     ** instead of an 8-byte one. This all works fine, except that when
50881     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
50882     ** that a Mem structure is located on an 8-byte boundary. To prevent
50883     ** this assert() from failing, when building with SQLITE_DEBUG defined
50884     ** using gcc, force nullMem to be 8-byte aligned using the magical
50885     ** __attribute__((aligned(8))) macro.  */
50886     static const Mem nullMem 
50887 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
50888       __attribute__((aligned(8))) 
50889 #endif
50890       = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
50891
50892     if( pVm && ALWAYS(pVm->db) ){
50893       sqlite3_mutex_enter(pVm->db->mutex);
50894       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
50895     }
50896     pOut = (Mem*)&nullMem;
50897   }
50898   return pOut;
50899 }
50900
50901 /*
50902 ** This function is called after invoking an sqlite3_value_XXX function on a 
50903 ** column value (i.e. a value returned by evaluating an SQL expression in the
50904 ** select list of a SELECT statement) that may cause a malloc() failure. If 
50905 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
50906 ** code of statement pStmt set to SQLITE_NOMEM.
50907 **
50908 ** Specifically, this is called from within:
50909 **
50910 **     sqlite3_column_int()
50911 **     sqlite3_column_int64()
50912 **     sqlite3_column_text()
50913 **     sqlite3_column_text16()
50914 **     sqlite3_column_real()
50915 **     sqlite3_column_bytes()
50916 **     sqlite3_column_bytes16()
50917 **
50918 ** But not for sqlite3_column_blob(), which never calls malloc().
50919 */
50920 static void columnMallocFailure(sqlite3_stmt *pStmt)
50921 {
50922   /* If malloc() failed during an encoding conversion within an
50923   ** sqlite3_column_XXX API, then set the return code of the statement to
50924   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
50925   ** and _finalize() will return NOMEM.
50926   */
50927   Vdbe *p = (Vdbe *)pStmt;
50928   if( p ){
50929     p->rc = sqlite3ApiExit(p->db, p->rc);
50930     sqlite3_mutex_leave(p->db->mutex);
50931   }
50932 }
50933
50934 /**************************** sqlite3_column_  *******************************
50935 ** The following routines are used to access elements of the current row
50936 ** in the result set.
50937 */
50938 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
50939   const void *val;
50940   val = sqlite3_value_blob( columnMem(pStmt,i) );
50941   /* Even though there is no encoding conversion, value_blob() might
50942   ** need to call malloc() to expand the result of a zeroblob() 
50943   ** expression. 
50944   */
50945   columnMallocFailure(pStmt);
50946   return val;
50947 }
50948 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
50949   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
50950   columnMallocFailure(pStmt);
50951   return val;
50952 }
50953 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
50954   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
50955   columnMallocFailure(pStmt);
50956   return val;
50957 }
50958 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
50959   double val = sqlite3_value_double( columnMem(pStmt,i) );
50960   columnMallocFailure(pStmt);
50961   return val;
50962 }
50963 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
50964   int val = sqlite3_value_int( columnMem(pStmt,i) );
50965   columnMallocFailure(pStmt);
50966   return val;
50967 }
50968 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
50969   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
50970   columnMallocFailure(pStmt);
50971   return val;
50972 }
50973 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
50974   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
50975   columnMallocFailure(pStmt);
50976   return val;
50977 }
50978 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
50979   Mem *pOut = columnMem(pStmt, i);
50980   if( pOut->flags&MEM_Static ){
50981     pOut->flags &= ~MEM_Static;
50982     pOut->flags |= MEM_Ephem;
50983   }
50984   columnMallocFailure(pStmt);
50985   return (sqlite3_value *)pOut;
50986 }
50987 #ifndef SQLITE_OMIT_UTF16
50988 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
50989   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
50990   columnMallocFailure(pStmt);
50991   return val;
50992 }
50993 #endif /* SQLITE_OMIT_UTF16 */
50994 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
50995   int iType = sqlite3_value_type( columnMem(pStmt,i) );
50996   columnMallocFailure(pStmt);
50997   return iType;
50998 }
50999
51000 /* The following function is experimental and subject to change or
51001 ** removal */
51002 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
51003 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
51004 **}
51005 */
51006
51007 /*
51008 ** Convert the N-th element of pStmt->pColName[] into a string using
51009 ** xFunc() then return that string.  If N is out of range, return 0.
51010 **
51011 ** There are up to 5 names for each column.  useType determines which
51012 ** name is returned.  Here are the names:
51013 **
51014 **    0      The column name as it should be displayed for output
51015 **    1      The datatype name for the column
51016 **    2      The name of the database that the column derives from
51017 **    3      The name of the table that the column derives from
51018 **    4      The name of the table column that the result column derives from
51019 **
51020 ** If the result is not a simple column reference (if it is an expression
51021 ** or a constant) then useTypes 2, 3, and 4 return NULL.
51022 */
51023 static const void *columnName(
51024   sqlite3_stmt *pStmt,
51025   int N,
51026   const void *(*xFunc)(Mem*),
51027   int useType
51028 ){
51029   const void *ret = 0;
51030   Vdbe *p = (Vdbe *)pStmt;
51031   int n;
51032   sqlite3 *db = p->db;
51033   
51034   assert( db!=0 );
51035   n = sqlite3_column_count(pStmt);
51036   if( N<n && N>=0 ){
51037     N += useType*n;
51038     sqlite3_mutex_enter(db->mutex);
51039     assert( db->mallocFailed==0 );
51040     ret = xFunc(&p->aColName[N]);
51041      /* A malloc may have failed inside of the xFunc() call. If this
51042     ** is the case, clear the mallocFailed flag and return NULL.
51043     */
51044     if( db->mallocFailed ){
51045       db->mallocFailed = 0;
51046       ret = 0;
51047     }
51048     sqlite3_mutex_leave(db->mutex);
51049   }
51050   return ret;
51051 }
51052
51053 /*
51054 ** Return the name of the Nth column of the result set returned by SQL
51055 ** statement pStmt.
51056 */
51057 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
51058   return columnName(
51059       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
51060 }
51061 #ifndef SQLITE_OMIT_UTF16
51062 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
51063   return columnName(
51064       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
51065 }
51066 #endif
51067
51068 /*
51069 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
51070 ** not define OMIT_DECLTYPE.
51071 */
51072 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
51073 # error "Must not define both SQLITE_OMIT_DECLTYPE \
51074          and SQLITE_ENABLE_COLUMN_METADATA"
51075 #endif
51076
51077 #ifndef SQLITE_OMIT_DECLTYPE
51078 /*
51079 ** Return the column declaration type (if applicable) of the 'i'th column
51080 ** of the result set of SQL statement pStmt.
51081 */
51082 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
51083   return columnName(
51084       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
51085 }
51086 #ifndef SQLITE_OMIT_UTF16
51087 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
51088   return columnName(
51089       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
51090 }
51091 #endif /* SQLITE_OMIT_UTF16 */
51092 #endif /* SQLITE_OMIT_DECLTYPE */
51093
51094 #ifdef SQLITE_ENABLE_COLUMN_METADATA
51095 /*
51096 ** Return the name of the database from which a result column derives.
51097 ** NULL is returned if the result column is an expression or constant or
51098 ** anything else which is not an unabiguous reference to a database column.
51099 */
51100 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
51101   return columnName(
51102       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
51103 }
51104 #ifndef SQLITE_OMIT_UTF16
51105 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
51106   return columnName(
51107       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
51108 }
51109 #endif /* SQLITE_OMIT_UTF16 */
51110
51111 /*
51112 ** Return the name of the table from which a result column derives.
51113 ** NULL is returned if the result column is an expression or constant or
51114 ** anything else which is not an unabiguous reference to a database column.
51115 */
51116 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
51117   return columnName(
51118       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
51119 }
51120 #ifndef SQLITE_OMIT_UTF16
51121 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
51122   return columnName(
51123       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
51124 }
51125 #endif /* SQLITE_OMIT_UTF16 */
51126
51127 /*
51128 ** Return the name of the table column from which a result column derives.
51129 ** NULL is returned if the result column is an expression or constant or
51130 ** anything else which is not an unabiguous reference to a database column.
51131 */
51132 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
51133   return columnName(
51134       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
51135 }
51136 #ifndef SQLITE_OMIT_UTF16
51137 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
51138   return columnName(
51139       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
51140 }
51141 #endif /* SQLITE_OMIT_UTF16 */
51142 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
51143
51144
51145 /******************************* sqlite3_bind_  ***************************
51146 ** 
51147 ** Routines used to attach values to wildcards in a compiled SQL statement.
51148 */
51149 /*
51150 ** Unbind the value bound to variable i in virtual machine p. This is the 
51151 ** the same as binding a NULL value to the column. If the "i" parameter is
51152 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
51153 **
51154 ** A successful evaluation of this routine acquires the mutex on p.
51155 ** the mutex is released if any kind of error occurs.
51156 **
51157 ** The error code stored in database p->db is overwritten with the return
51158 ** value in any case.
51159 */
51160 static int vdbeUnbind(Vdbe *p, int i){
51161   Mem *pVar;
51162   if( p==0 ) return SQLITE_MISUSE;
51163   sqlite3_mutex_enter(p->db->mutex);
51164   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
51165     sqlite3Error(p->db, SQLITE_MISUSE, 0);
51166     sqlite3_mutex_leave(p->db->mutex);
51167     return SQLITE_MISUSE;
51168   }
51169   if( i<1 || i>p->nVar ){
51170     sqlite3Error(p->db, SQLITE_RANGE, 0);
51171     sqlite3_mutex_leave(p->db->mutex);
51172     return SQLITE_RANGE;
51173   }
51174   i--;
51175   pVar = &p->aVar[i];
51176   sqlite3VdbeMemRelease(pVar);
51177   pVar->flags = MEM_Null;
51178   sqlite3Error(p->db, SQLITE_OK, 0);
51179
51180   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
51181   ** binding a new value to this variable invalidates the current query plan.
51182   */
51183   if( p->isPrepareV2 &&
51184      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
51185   ){
51186     p->expired = 1;
51187   }
51188   return SQLITE_OK;
51189 }
51190
51191 /*
51192 ** Bind a text or BLOB value.
51193 */
51194 static int bindText(
51195   sqlite3_stmt *pStmt,   /* The statement to bind against */
51196   int i,                 /* Index of the parameter to bind */
51197   const void *zData,     /* Pointer to the data to be bound */
51198   int nData,             /* Number of bytes of data to be bound */
51199   void (*xDel)(void*),   /* Destructor for the data */
51200   u8 encoding            /* Encoding for the data */
51201 ){
51202   Vdbe *p = (Vdbe *)pStmt;
51203   Mem *pVar;
51204   int rc;
51205
51206   rc = vdbeUnbind(p, i);
51207   if( rc==SQLITE_OK ){
51208     if( zData!=0 ){
51209       pVar = &p->aVar[i-1];
51210       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
51211       if( rc==SQLITE_OK && encoding!=0 ){
51212         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
51213       }
51214       sqlite3Error(p->db, rc, 0);
51215       rc = sqlite3ApiExit(p->db, rc);
51216     }
51217     sqlite3_mutex_leave(p->db->mutex);
51218   }
51219   return rc;
51220 }
51221
51222
51223 /*
51224 ** Bind a blob value to an SQL statement variable.
51225 */
51226 SQLITE_API int sqlite3_bind_blob(
51227   sqlite3_stmt *pStmt, 
51228   int i, 
51229   const void *zData, 
51230   int nData, 
51231   void (*xDel)(void*)
51232 ){
51233   return bindText(pStmt, i, zData, nData, xDel, 0);
51234 }
51235 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
51236   int rc;
51237   Vdbe *p = (Vdbe *)pStmt;
51238   rc = vdbeUnbind(p, i);
51239   if( rc==SQLITE_OK ){
51240     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
51241     sqlite3_mutex_leave(p->db->mutex);
51242   }
51243   return rc;
51244 }
51245 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
51246   return sqlite3_bind_int64(p, i, (i64)iValue);
51247 }
51248 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
51249   int rc;
51250   Vdbe *p = (Vdbe *)pStmt;
51251   rc = vdbeUnbind(p, i);
51252   if( rc==SQLITE_OK ){
51253     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
51254     sqlite3_mutex_leave(p->db->mutex);
51255   }
51256   return rc;
51257 }
51258 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
51259   int rc;
51260   Vdbe *p = (Vdbe*)pStmt;
51261   rc = vdbeUnbind(p, i);
51262   if( rc==SQLITE_OK ){
51263     sqlite3_mutex_leave(p->db->mutex);
51264   }
51265   return rc;
51266 }
51267 SQLITE_API int sqlite3_bind_text( 
51268   sqlite3_stmt *pStmt, 
51269   int i, 
51270   const char *zData, 
51271   int nData, 
51272   void (*xDel)(void*)
51273 ){
51274   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
51275 }
51276 #ifndef SQLITE_OMIT_UTF16
51277 SQLITE_API int sqlite3_bind_text16(
51278   sqlite3_stmt *pStmt, 
51279   int i, 
51280   const void *zData, 
51281   int nData, 
51282   void (*xDel)(void*)
51283 ){
51284   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
51285 }
51286 #endif /* SQLITE_OMIT_UTF16 */
51287 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
51288   int rc;
51289   switch( pValue->type ){
51290     case SQLITE_INTEGER: {
51291       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
51292       break;
51293     }
51294     case SQLITE_FLOAT: {
51295       rc = sqlite3_bind_double(pStmt, i, pValue->r);
51296       break;
51297     }
51298     case SQLITE_BLOB: {
51299       if( pValue->flags & MEM_Zero ){
51300         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
51301       }else{
51302         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
51303       }
51304       break;
51305     }
51306     case SQLITE_TEXT: {
51307       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
51308                               pValue->enc);
51309       break;
51310     }
51311     default: {
51312       rc = sqlite3_bind_null(pStmt, i);
51313       break;
51314     }
51315   }
51316   return rc;
51317 }
51318 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
51319   int rc;
51320   Vdbe *p = (Vdbe *)pStmt;
51321   rc = vdbeUnbind(p, i);
51322   if( rc==SQLITE_OK ){
51323     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
51324     sqlite3_mutex_leave(p->db->mutex);
51325   }
51326   return rc;
51327 }
51328
51329 /*
51330 ** Return the number of wildcards that can be potentially bound to.
51331 ** This routine is added to support DBD::SQLite.  
51332 */
51333 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
51334   Vdbe *p = (Vdbe*)pStmt;
51335   return p ? p->nVar : 0;
51336 }
51337
51338 /*
51339 ** Create a mapping from variable numbers to variable names
51340 ** in the Vdbe.azVar[] array, if such a mapping does not already
51341 ** exist.
51342 */
51343 static void createVarMap(Vdbe *p){
51344   if( !p->okVar ){
51345     int j;
51346     Op *pOp;
51347     sqlite3_mutex_enter(p->db->mutex);
51348     /* The race condition here is harmless.  If two threads call this
51349     ** routine on the same Vdbe at the same time, they both might end
51350     ** up initializing the Vdbe.azVar[] array.  That is a little extra
51351     ** work but it results in the same answer.
51352     */
51353     for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
51354       if( pOp->opcode==OP_Variable ){
51355         assert( pOp->p1>0 && pOp->p1<=p->nVar );
51356         p->azVar[pOp->p1-1] = pOp->p4.z;
51357       }
51358     }
51359     p->okVar = 1;
51360     sqlite3_mutex_leave(p->db->mutex);
51361   }
51362 }
51363
51364 /*
51365 ** Return the name of a wildcard parameter.  Return NULL if the index
51366 ** is out of range or if the wildcard is unnamed.
51367 **
51368 ** The result is always UTF-8.
51369 */
51370 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
51371   Vdbe *p = (Vdbe*)pStmt;
51372   if( p==0 || i<1 || i>p->nVar ){
51373     return 0;
51374   }
51375   createVarMap(p);
51376   return p->azVar[i-1];
51377 }
51378
51379 /*
51380 ** Given a wildcard parameter name, return the index of the variable
51381 ** with that name.  If there is no variable with the given name,
51382 ** return 0.
51383 */
51384 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
51385   int i;
51386   if( p==0 ){
51387     return 0;
51388   }
51389   createVarMap(p); 
51390   if( zName ){
51391     for(i=0; i<p->nVar; i++){
51392       const char *z = p->azVar[i];
51393       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
51394         return i+1;
51395       }
51396     }
51397   }
51398   return 0;
51399 }
51400 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
51401   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
51402 }
51403
51404 /*
51405 ** Transfer all bindings from the first statement over to the second.
51406 */
51407 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
51408   Vdbe *pFrom = (Vdbe*)pFromStmt;
51409   Vdbe *pTo = (Vdbe*)pToStmt;
51410   int i;
51411   assert( pTo->db==pFrom->db );
51412   assert( pTo->nVar==pFrom->nVar );
51413   sqlite3_mutex_enter(pTo->db->mutex);
51414   for(i=0; i<pFrom->nVar; i++){
51415     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
51416   }
51417   sqlite3_mutex_leave(pTo->db->mutex);
51418   return SQLITE_OK;
51419 }
51420
51421 #ifndef SQLITE_OMIT_DEPRECATED
51422 /*
51423 ** Deprecated external interface.  Internal/core SQLite code
51424 ** should call sqlite3TransferBindings.
51425 **
51426 ** Is is misuse to call this routine with statements from different
51427 ** database connections.  But as this is a deprecated interface, we
51428 ** will not bother to check for that condition.
51429 **
51430 ** If the two statements contain a different number of bindings, then
51431 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
51432 ** SQLITE_OK is returned.
51433 */
51434 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
51435   Vdbe *pFrom = (Vdbe*)pFromStmt;
51436   Vdbe *pTo = (Vdbe*)pToStmt;
51437   if( pFrom->nVar!=pTo->nVar ){
51438     return SQLITE_ERROR;
51439   }
51440   if( pTo->isPrepareV2 && pTo->expmask ){
51441     pTo->expired = 1;
51442   }
51443   if( pFrom->isPrepareV2 && pFrom->expmask ){
51444     pFrom->expired = 1;
51445   }
51446   return sqlite3TransferBindings(pFromStmt, pToStmt);
51447 }
51448 #endif
51449
51450 /*
51451 ** Return the sqlite3* database handle to which the prepared statement given
51452 ** in the argument belongs.  This is the same database handle that was
51453 ** the first argument to the sqlite3_prepare() that was used to create
51454 ** the statement in the first place.
51455 */
51456 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
51457   return pStmt ? ((Vdbe*)pStmt)->db : 0;
51458 }
51459
51460 /*
51461 ** Return a pointer to the next prepared statement after pStmt associated
51462 ** with database connection pDb.  If pStmt is NULL, return the first
51463 ** prepared statement for the database connection.  Return NULL if there
51464 ** are no more.
51465 */
51466 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
51467   sqlite3_stmt *pNext;
51468   sqlite3_mutex_enter(pDb->mutex);
51469   if( pStmt==0 ){
51470     pNext = (sqlite3_stmt*)pDb->pVdbe;
51471   }else{
51472     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
51473   }
51474   sqlite3_mutex_leave(pDb->mutex);
51475   return pNext;
51476 }
51477
51478 /*
51479 ** Return the value of a status counter for a prepared statement
51480 */
51481 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
51482   Vdbe *pVdbe = (Vdbe*)pStmt;
51483   int v = pVdbe->aCounter[op-1];
51484   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
51485   return v;
51486 }
51487
51488 /************** End of vdbeapi.c *********************************************/
51489 /************** Begin file vdbetrace.c ***************************************/
51490 /*
51491 ** 2009 November 25
51492 **
51493 ** The author disclaims copyright to this source code.  In place of
51494 ** a legal notice, here is a blessing:
51495 **
51496 **    May you do good and not evil.
51497 **    May you find forgiveness for yourself and forgive others.
51498 **    May you share freely, never taking more than you give.
51499 **
51500 *************************************************************************
51501 **
51502 ** This file contains code used to insert the values of host parameters
51503 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
51504 */
51505
51506 #ifndef SQLITE_OMIT_TRACE
51507
51508 /*
51509 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
51510 ** bytes in this text up to but excluding the first character in
51511 ** a host parameter.  If the text contains no host parameters, return
51512 ** the total number of bytes in the text.
51513 */
51514 static int findNextHostParameter(const char *zSql, int *pnToken){
51515   int tokenType;
51516   int nTotal = 0;
51517   int n;
51518
51519   *pnToken = 0;
51520   while( zSql[0] ){
51521     n = sqlite3GetToken((u8*)zSql, &tokenType);
51522     assert( n>0 && tokenType!=TK_ILLEGAL );
51523     if( tokenType==TK_VARIABLE ){
51524       *pnToken = n;
51525       break;
51526     }
51527     nTotal += n;
51528     zSql += n;
51529   }
51530   return nTotal;
51531 }
51532
51533 /*
51534 ** Return a pointer to a string in memory obtained form sqlite3DbMalloc() which
51535 ** holds a copy of zRawSql but with host parameters expanded to their
51536 ** current bindings.
51537 **
51538 ** The calling function is responsible for making sure the memory returned
51539 ** is eventually freed.
51540 **
51541 ** ALGORITHM:  Scan the input string looking for host parameters in any of
51542 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
51543 ** string literals, quoted identifier names, and comments.  For text forms,
51544 ** the host parameter index is found by scanning the perpared
51545 ** statement for the corresponding OP_Variable opcode.  Once the host
51546 ** parameter index is known, locate the value in p->aVar[].  Then render
51547 ** the value as a literal in place of the host parameter name.
51548 */
51549 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
51550   Vdbe *p,                 /* The prepared statement being evaluated */
51551   const char *zRawSql      /* Raw text of the SQL statement */
51552 ){
51553   sqlite3 *db;             /* The database connection */
51554   int idx = 0;             /* Index of a host parameter */
51555   int nextIndex = 1;       /* Index of next ? host parameter */
51556   int n;                   /* Length of a token prefix */
51557   int nToken;              /* Length of the parameter token */
51558   int i;                   /* Loop counter */
51559   Mem *pVar;               /* Value of a host parameter */
51560   StrAccum out;            /* Accumulate the output here */
51561   char zBase[100];         /* Initial working space */
51562
51563   db = p->db;
51564   sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
51565                       db->aLimit[SQLITE_LIMIT_LENGTH]);
51566   out.db = db;
51567   while( zRawSql[0] ){
51568     n = findNextHostParameter(zRawSql, &nToken);
51569     assert( n>0 );
51570     sqlite3StrAccumAppend(&out, zRawSql, n);
51571     zRawSql += n;
51572     assert( zRawSql[0] || nToken==0 );
51573     if( nToken==0 ) break;
51574     if( zRawSql[0]=='?' ){
51575       if( nToken>1 ){
51576         assert( sqlite3Isdigit(zRawSql[1]) );
51577         sqlite3GetInt32(&zRawSql[1], &idx);
51578       }else{
51579         idx = nextIndex;
51580       }
51581     }else{
51582       assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
51583       testcase( zRawSql[0]==':' );
51584       testcase( zRawSql[0]=='$' );
51585       testcase( zRawSql[0]=='@' );
51586       idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
51587       assert( idx>0 );
51588     }
51589     zRawSql += nToken;
51590     nextIndex = idx + 1;
51591     assert( idx>0 && idx<=p->nVar );
51592     pVar = &p->aVar[idx-1];
51593     if( pVar->flags & MEM_Null ){
51594       sqlite3StrAccumAppend(&out, "NULL", 4);
51595     }else if( pVar->flags & MEM_Int ){
51596       sqlite3XPrintf(&out, "%lld", pVar->u.i);
51597     }else if( pVar->flags & MEM_Real ){
51598       sqlite3XPrintf(&out, "%!.15g", pVar->r);
51599     }else if( pVar->flags & MEM_Str ){
51600 #ifndef SQLITE_OMIT_UTF16
51601       u8 enc = ENC(db);
51602       if( enc!=SQLITE_UTF8 ){
51603         Mem utf8;
51604         memset(&utf8, 0, sizeof(utf8));
51605         utf8.db = db;
51606         sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
51607         sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
51608         sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
51609         sqlite3VdbeMemRelease(&utf8);
51610       }else
51611 #endif
51612       {
51613         sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
51614       }
51615     }else if( pVar->flags & MEM_Zero ){
51616       sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
51617     }else{
51618       assert( pVar->flags & MEM_Blob );
51619       sqlite3StrAccumAppend(&out, "x'", 2);
51620       for(i=0; i<pVar->n; i++){
51621         sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
51622       }
51623       sqlite3StrAccumAppend(&out, "'", 1);
51624     }
51625   }
51626   return sqlite3StrAccumFinish(&out);
51627 }
51628
51629 #endif /* #ifndef SQLITE_OMIT_TRACE */
51630
51631 /************** End of vdbetrace.c *******************************************/
51632 /************** Begin file vdbe.c ********************************************/
51633 /*
51634 ** 2001 September 15
51635 **
51636 ** The author disclaims copyright to this source code.  In place of
51637 ** a legal notice, here is a blessing:
51638 **
51639 **    May you do good and not evil.
51640 **    May you find forgiveness for yourself and forgive others.
51641 **    May you share freely, never taking more than you give.
51642 **
51643 *************************************************************************
51644 ** The code in this file implements execution method of the 
51645 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
51646 ** handles housekeeping details such as creating and deleting
51647 ** VDBE instances.  This file is solely interested in executing
51648 ** the VDBE program.
51649 **
51650 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
51651 ** to a VDBE.
51652 **
51653 ** The SQL parser generates a program which is then executed by
51654 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
51655 ** similar in form to assembly language.  The program consists of
51656 ** a linear sequence of operations.  Each operation has an opcode 
51657 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
51658 ** is a null-terminated string.  Operand P5 is an unsigned character.
51659 ** Few opcodes use all 5 operands.
51660 **
51661 ** Computation results are stored on a set of registers numbered beginning
51662 ** with 1 and going up to Vdbe.nMem.  Each register can store
51663 ** either an integer, a null-terminated string, a floating point
51664 ** number, or the SQL "NULL" value.  An implicit conversion from one
51665 ** type to the other occurs as necessary.
51666 ** 
51667 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
51668 ** function which does the work of interpreting a VDBE program.
51669 ** But other routines are also provided to help in building up
51670 ** a program instruction by instruction.
51671 **
51672 ** Various scripts scan this source file in order to generate HTML
51673 ** documentation, headers files, or other derived files.  The formatting
51674 ** of the code in this file is, therefore, important.  See other comments
51675 ** in this file for details.  If in doubt, do not deviate from existing
51676 ** commenting and indentation practices when changing or adding code.
51677 */
51678
51679 /*
51680 ** The following global variable is incremented every time a cursor
51681 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
51682 ** procedures use this information to make sure that indices are
51683 ** working correctly.  This variable has no function other than to
51684 ** help verify the correct operation of the library.
51685 */
51686 #ifdef SQLITE_TEST
51687 SQLITE_API int sqlite3_search_count = 0;
51688 #endif
51689
51690 /*
51691 ** When this global variable is positive, it gets decremented once before
51692 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
51693 ** field of the sqlite3 structure is set in order to simulate and interrupt.
51694 **
51695 ** This facility is used for testing purposes only.  It does not function
51696 ** in an ordinary build.
51697 */
51698 #ifdef SQLITE_TEST
51699 SQLITE_API int sqlite3_interrupt_count = 0;
51700 #endif
51701
51702 /*
51703 ** The next global variable is incremented each type the OP_Sort opcode
51704 ** is executed.  The test procedures use this information to make sure that
51705 ** sorting is occurring or not occurring at appropriate times.   This variable
51706 ** has no function other than to help verify the correct operation of the
51707 ** library.
51708 */
51709 #ifdef SQLITE_TEST
51710 SQLITE_API int sqlite3_sort_count = 0;
51711 #endif
51712
51713 /*
51714 ** The next global variable records the size of the largest MEM_Blob
51715 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
51716 ** use this information to make sure that the zero-blob functionality
51717 ** is working correctly.   This variable has no function other than to
51718 ** help verify the correct operation of the library.
51719 */
51720 #ifdef SQLITE_TEST
51721 SQLITE_API int sqlite3_max_blobsize = 0;
51722 static void updateMaxBlobsize(Mem *p){
51723   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
51724     sqlite3_max_blobsize = p->n;
51725   }
51726 }
51727 #endif
51728
51729 /*
51730 ** The next global variable is incremented each type the OP_Found opcode
51731 ** is executed. This is used to test whether or not the foreign key
51732 ** operation implemented using OP_FkIsZero is working. This variable
51733 ** has no function other than to help verify the correct operation of the
51734 ** library.
51735 */
51736 #ifdef SQLITE_TEST
51737 SQLITE_API int sqlite3_found_count = 0;
51738 #endif
51739
51740 /*
51741 ** Test a register to see if it exceeds the current maximum blob size.
51742 ** If it does, record the new maximum blob size.
51743 */
51744 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
51745 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
51746 #else
51747 # define UPDATE_MAX_BLOBSIZE(P)
51748 #endif
51749
51750 /*
51751 ** Convert the given register into a string if it isn't one
51752 ** already. Return non-zero if a malloc() fails.
51753 */
51754 #define Stringify(P, enc) \
51755    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
51756      { goto no_mem; }
51757
51758 /*
51759 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
51760 ** a pointer to a dynamically allocated string where some other entity
51761 ** is responsible for deallocating that string.  Because the register
51762 ** does not control the string, it might be deleted without the register
51763 ** knowing it.
51764 **
51765 ** This routine converts an ephemeral string into a dynamically allocated
51766 ** string that the register itself controls.  In other words, it
51767 ** converts an MEM_Ephem string into an MEM_Dyn string.
51768 */
51769 #define Deephemeralize(P) \
51770    if( ((P)->flags&MEM_Ephem)!=0 \
51771        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
51772
51773 /*
51774 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
51775 ** P if required.
51776 */
51777 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
51778
51779 /*
51780 ** Argument pMem points at a register that will be passed to a
51781 ** user-defined function or returned to the user as the result of a query.
51782 ** This routine sets the pMem->type variable used by the sqlite3_value_*() 
51783 ** routines.
51784 */
51785 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
51786   int flags = pMem->flags;
51787   if( flags & MEM_Null ){
51788     pMem->type = SQLITE_NULL;
51789   }
51790   else if( flags & MEM_Int ){
51791     pMem->type = SQLITE_INTEGER;
51792   }
51793   else if( flags & MEM_Real ){
51794     pMem->type = SQLITE_FLOAT;
51795   }
51796   else if( flags & MEM_Str ){
51797     pMem->type = SQLITE_TEXT;
51798   }else{
51799     pMem->type = SQLITE_BLOB;
51800   }
51801 }
51802
51803 /*
51804 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
51805 ** if we run out of memory.
51806 */
51807 static VdbeCursor *allocateCursor(
51808   Vdbe *p,              /* The virtual machine */
51809   int iCur,             /* Index of the new VdbeCursor */
51810   int nField,           /* Number of fields in the table or index */
51811   int iDb,              /* When database the cursor belongs to, or -1 */
51812   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
51813 ){
51814   /* Find the memory cell that will be used to store the blob of memory
51815   ** required for this VdbeCursor structure. It is convenient to use a 
51816   ** vdbe memory cell to manage the memory allocation required for a
51817   ** VdbeCursor structure for the following reasons:
51818   **
51819   **   * Sometimes cursor numbers are used for a couple of different
51820   **     purposes in a vdbe program. The different uses might require
51821   **     different sized allocations. Memory cells provide growable
51822   **     allocations.
51823   **
51824   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
51825   **     be freed lazily via the sqlite3_release_memory() API. This
51826   **     minimizes the number of malloc calls made by the system.
51827   **
51828   ** Memory cells for cursors are allocated at the top of the address
51829   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
51830   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
51831   */
51832   Mem *pMem = &p->aMem[p->nMem-iCur];
51833
51834   int nByte;
51835   VdbeCursor *pCx = 0;
51836   nByte = 
51837       ROUND8(sizeof(VdbeCursor)) + 
51838       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
51839       2*nField*sizeof(u32);
51840
51841   assert( iCur<p->nCursor );
51842   if( p->apCsr[iCur] ){
51843     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
51844     p->apCsr[iCur] = 0;
51845   }
51846   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
51847     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
51848     memset(pCx, 0, sizeof(VdbeCursor));
51849     pCx->iDb = iDb;
51850     pCx->nField = nField;
51851     if( nField ){
51852       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
51853     }
51854     if( isBtreeCursor ){
51855       pCx->pCursor = (BtCursor*)
51856           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
51857       sqlite3BtreeCursorZero(pCx->pCursor);
51858     }
51859   }
51860   return pCx;
51861 }
51862
51863 /*
51864 ** Try to convert a value into a numeric representation if we can
51865 ** do so without loss of information.  In other words, if the string
51866 ** looks like a number, convert it into a number.  If it does not
51867 ** look like a number, leave it alone.
51868 */
51869 static void applyNumericAffinity(Mem *pRec){
51870   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
51871     int realnum;
51872     sqlite3VdbeMemNulTerminate(pRec);
51873     if( (pRec->flags&MEM_Str)
51874          && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
51875       i64 value;
51876       sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
51877       if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
51878         pRec->u.i = value;
51879         MemSetTypeFlag(pRec, MEM_Int);
51880       }else{
51881         sqlite3VdbeMemRealify(pRec);
51882       }
51883     }
51884   }
51885 }
51886
51887 /*
51888 ** Processing is determine by the affinity parameter:
51889 **
51890 ** SQLITE_AFF_INTEGER:
51891 ** SQLITE_AFF_REAL:
51892 ** SQLITE_AFF_NUMERIC:
51893 **    Try to convert pRec to an integer representation or a 
51894 **    floating-point representation if an integer representation
51895 **    is not possible.  Note that the integer representation is
51896 **    always preferred, even if the affinity is REAL, because
51897 **    an integer representation is more space efficient on disk.
51898 **
51899 ** SQLITE_AFF_TEXT:
51900 **    Convert pRec to a text representation.
51901 **
51902 ** SQLITE_AFF_NONE:
51903 **    No-op.  pRec is unchanged.
51904 */
51905 static void applyAffinity(
51906   Mem *pRec,          /* The value to apply affinity to */
51907   char affinity,      /* The affinity to be applied */
51908   u8 enc              /* Use this text encoding */
51909 ){
51910   if( affinity==SQLITE_AFF_TEXT ){
51911     /* Only attempt the conversion to TEXT if there is an integer or real
51912     ** representation (blob and NULL do not get converted) but no string
51913     ** representation.
51914     */
51915     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
51916       sqlite3VdbeMemStringify(pRec, enc);
51917     }
51918     pRec->flags &= ~(MEM_Real|MEM_Int);
51919   }else if( affinity!=SQLITE_AFF_NONE ){
51920     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
51921              || affinity==SQLITE_AFF_NUMERIC );
51922     applyNumericAffinity(pRec);
51923     if( pRec->flags & MEM_Real ){
51924       sqlite3VdbeIntegerAffinity(pRec);
51925     }
51926   }
51927 }
51928
51929 /*
51930 ** Try to convert the type of a function argument or a result column
51931 ** into a numeric representation.  Use either INTEGER or REAL whichever
51932 ** is appropriate.  But only do the conversion if it is possible without
51933 ** loss of information and return the revised type of the argument.
51934 **
51935 ** This is an EXPERIMENTAL api and is subject to change or removal.
51936 */
51937 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
51938   Mem *pMem = (Mem*)pVal;
51939   applyNumericAffinity(pMem);
51940   sqlite3VdbeMemStoreType(pMem);
51941   return pMem->type;
51942 }
51943
51944 /*
51945 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
51946 ** not the internal Mem* type.
51947 */
51948 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
51949   sqlite3_value *pVal, 
51950   u8 affinity, 
51951   u8 enc
51952 ){
51953   applyAffinity((Mem *)pVal, affinity, enc);
51954 }
51955
51956 #ifdef SQLITE_DEBUG
51957 /*
51958 ** Write a nice string representation of the contents of cell pMem
51959 ** into buffer zBuf, length nBuf.
51960 */
51961 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
51962   char *zCsr = zBuf;
51963   int f = pMem->flags;
51964
51965   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
51966
51967   if( f&MEM_Blob ){
51968     int i;
51969     char c;
51970     if( f & MEM_Dyn ){
51971       c = 'z';
51972       assert( (f & (MEM_Static|MEM_Ephem))==0 );
51973     }else if( f & MEM_Static ){
51974       c = 't';
51975       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
51976     }else if( f & MEM_Ephem ){
51977       c = 'e';
51978       assert( (f & (MEM_Static|MEM_Dyn))==0 );
51979     }else{
51980       c = 's';
51981     }
51982
51983     sqlite3_snprintf(100, zCsr, "%c", c);
51984     zCsr += sqlite3Strlen30(zCsr);
51985     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
51986     zCsr += sqlite3Strlen30(zCsr);
51987     for(i=0; i<16 && i<pMem->n; i++){
51988       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
51989       zCsr += sqlite3Strlen30(zCsr);
51990     }
51991     for(i=0; i<16 && i<pMem->n; i++){
51992       char z = pMem->z[i];
51993       if( z<32 || z>126 ) *zCsr++ = '.';
51994       else *zCsr++ = z;
51995     }
51996
51997     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
51998     zCsr += sqlite3Strlen30(zCsr);
51999     if( f & MEM_Zero ){
52000       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
52001       zCsr += sqlite3Strlen30(zCsr);
52002     }
52003     *zCsr = '\0';
52004   }else if( f & MEM_Str ){
52005     int j, k;
52006     zBuf[0] = ' ';
52007     if( f & MEM_Dyn ){
52008       zBuf[1] = 'z';
52009       assert( (f & (MEM_Static|MEM_Ephem))==0 );
52010     }else if( f & MEM_Static ){
52011       zBuf[1] = 't';
52012       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
52013     }else if( f & MEM_Ephem ){
52014       zBuf[1] = 'e';
52015       assert( (f & (MEM_Static|MEM_Dyn))==0 );
52016     }else{
52017       zBuf[1] = 's';
52018     }
52019     k = 2;
52020     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
52021     k += sqlite3Strlen30(&zBuf[k]);
52022     zBuf[k++] = '[';
52023     for(j=0; j<15 && j<pMem->n; j++){
52024       u8 c = pMem->z[j];
52025       if( c>=0x20 && c<0x7f ){
52026         zBuf[k++] = c;
52027       }else{
52028         zBuf[k++] = '.';
52029       }
52030     }
52031     zBuf[k++] = ']';
52032     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
52033     k += sqlite3Strlen30(&zBuf[k]);
52034     zBuf[k++] = 0;
52035   }
52036 }
52037 #endif
52038
52039 #ifdef SQLITE_DEBUG
52040 /*
52041 ** Print the value of a register for tracing purposes:
52042 */
52043 static void memTracePrint(FILE *out, Mem *p){
52044   if( p->flags & MEM_Null ){
52045     fprintf(out, " NULL");
52046   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
52047     fprintf(out, " si:%lld", p->u.i);
52048   }else if( p->flags & MEM_Int ){
52049     fprintf(out, " i:%lld", p->u.i);
52050 #ifndef SQLITE_OMIT_FLOATING_POINT
52051   }else if( p->flags & MEM_Real ){
52052     fprintf(out, " r:%g", p->r);
52053 #endif
52054   }else if( p->flags & MEM_RowSet ){
52055     fprintf(out, " (rowset)");
52056   }else{
52057     char zBuf[200];
52058     sqlite3VdbeMemPrettyPrint(p, zBuf);
52059     fprintf(out, " ");
52060     fprintf(out, "%s", zBuf);
52061   }
52062 }
52063 static void registerTrace(FILE *out, int iReg, Mem *p){
52064   fprintf(out, "REG[%d] = ", iReg);
52065   memTracePrint(out, p);
52066   fprintf(out, "\n");
52067 }
52068 #endif
52069
52070 #ifdef SQLITE_DEBUG
52071 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
52072 #else
52073 #  define REGISTER_TRACE(R,M)
52074 #endif
52075
52076
52077 #ifdef VDBE_PROFILE
52078
52079 /* 
52080 ** hwtime.h contains inline assembler code for implementing 
52081 ** high-performance timing routines.
52082 */
52083 /************** Include hwtime.h in the middle of vdbe.c *********************/
52084 /************** Begin file hwtime.h ******************************************/
52085 /*
52086 ** 2008 May 27
52087 **
52088 ** The author disclaims copyright to this source code.  In place of
52089 ** a legal notice, here is a blessing:
52090 **
52091 **    May you do good and not evil.
52092 **    May you find forgiveness for yourself and forgive others.
52093 **    May you share freely, never taking more than you give.
52094 **
52095 ******************************************************************************
52096 **
52097 ** This file contains inline asm code for retrieving "high-performance"
52098 ** counters for x86 class CPUs.
52099 */
52100 #ifndef _HWTIME_H_
52101 #define _HWTIME_H_
52102
52103 /*
52104 ** The following routine only works on pentium-class (or newer) processors.
52105 ** It uses the RDTSC opcode to read the cycle count value out of the
52106 ** processor and returns that value.  This can be used for high-res
52107 ** profiling.
52108 */
52109 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
52110       (defined(i386) || defined(__i386__) || defined(_M_IX86))
52111
52112   #if defined(__GNUC__)
52113
52114   __inline__ sqlite_uint64 sqlite3Hwtime(void){
52115      unsigned int lo, hi;
52116      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
52117      return (sqlite_uint64)hi << 32 | lo;
52118   }
52119
52120   #elif defined(_MSC_VER)
52121
52122   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
52123      __asm {
52124         rdtsc
52125         ret       ; return value at EDX:EAX
52126      }
52127   }
52128
52129   #endif
52130
52131 #elif (defined(__GNUC__) && defined(__x86_64__))
52132
52133   __inline__ sqlite_uint64 sqlite3Hwtime(void){
52134       unsigned long val;
52135       __asm__ __volatile__ ("rdtsc" : "=A" (val));
52136       return val;
52137   }
52138  
52139 #elif (defined(__GNUC__) && defined(__ppc__))
52140
52141   __inline__ sqlite_uint64 sqlite3Hwtime(void){
52142       unsigned long long retval;
52143       unsigned long junk;
52144       __asm__ __volatile__ ("\n\
52145           1:      mftbu   %1\n\
52146                   mftb    %L0\n\
52147                   mftbu   %0\n\
52148                   cmpw    %0,%1\n\
52149                   bne     1b"
52150                   : "=r" (retval), "=r" (junk));
52151       return retval;
52152   }
52153
52154 #else
52155
52156   #error Need implementation of sqlite3Hwtime() for your platform.
52157
52158   /*
52159   ** To compile without implementing sqlite3Hwtime() for your platform,
52160   ** you can remove the above #error and use the following
52161   ** stub function.  You will lose timing support for many
52162   ** of the debugging and testing utilities, but it should at
52163   ** least compile and run.
52164   */
52165 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
52166
52167 #endif
52168
52169 #endif /* !defined(_HWTIME_H_) */
52170
52171 /************** End of hwtime.h **********************************************/
52172 /************** Continuing where we left off in vdbe.c ***********************/
52173
52174 #endif
52175
52176 /*
52177 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
52178 ** sqlite3_interrupt() routine has been called.  If it has been, then
52179 ** processing of the VDBE program is interrupted.
52180 **
52181 ** This macro added to every instruction that does a jump in order to
52182 ** implement a loop.  This test used to be on every single instruction,
52183 ** but that meant we more testing that we needed.  By only testing the
52184 ** flag on jump instructions, we get a (small) speed improvement.
52185 */
52186 #define CHECK_FOR_INTERRUPT \
52187    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
52188
52189 #ifdef SQLITE_DEBUG
52190 static int fileExists(sqlite3 *db, const char *zFile){
52191   int res = 0;
52192   int rc = SQLITE_OK;
52193 #ifdef SQLITE_TEST
52194   /* If we are currently testing IO errors, then do not call OsAccess() to
52195   ** test for the presence of zFile. This is because any IO error that
52196   ** occurs here will not be reported, causing the test to fail.
52197   */
52198   extern int sqlite3_io_error_pending;
52199   if( sqlite3_io_error_pending<=0 )
52200 #endif
52201     rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
52202   return (res && rc==SQLITE_OK);
52203 }
52204 #endif
52205
52206 #ifndef NDEBUG
52207 /*
52208 ** This function is only called from within an assert() expression. It
52209 ** checks that the sqlite3.nTransaction variable is correctly set to
52210 ** the number of non-transaction savepoints currently in the 
52211 ** linked list starting at sqlite3.pSavepoint.
52212 ** 
52213 ** Usage:
52214 **
52215 **     assert( checkSavepointCount(db) );
52216 */
52217 static int checkSavepointCount(sqlite3 *db){
52218   int n = 0;
52219   Savepoint *p;
52220   for(p=db->pSavepoint; p; p=p->pNext) n++;
52221   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
52222   return 1;
52223 }
52224 #endif
52225
52226 /*
52227 ** Execute as much of a VDBE program as we can then return.
52228 **
52229 ** sqlite3VdbeMakeReady() must be called before this routine in order to
52230 ** close the program with a final OP_Halt and to set up the callbacks
52231 ** and the error message pointer.
52232 **
52233 ** Whenever a row or result data is available, this routine will either
52234 ** invoke the result callback (if there is one) or return with
52235 ** SQLITE_ROW.
52236 **
52237 ** If an attempt is made to open a locked database, then this routine
52238 ** will either invoke the busy callback (if there is one) or it will
52239 ** return SQLITE_BUSY.
52240 **
52241 ** If an error occurs, an error message is written to memory obtained
52242 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
52243 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
52244 **
52245 ** If the callback ever returns non-zero, then the program exits
52246 ** immediately.  There will be no error message but the p->rc field is
52247 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
52248 **
52249 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
52250 ** routine to return SQLITE_ERROR.
52251 **
52252 ** Other fatal errors return SQLITE_ERROR.
52253 **
52254 ** After this routine has finished, sqlite3VdbeFinalize() should be
52255 ** used to clean up the mess that was left behind.
52256 */
52257 SQLITE_PRIVATE int sqlite3VdbeExec(
52258   Vdbe *p                    /* The VDBE */
52259 ){
52260   int pc;                    /* The program counter */
52261   Op *aOp = p->aOp;          /* Copy of p->aOp */
52262   Op *pOp;                   /* Current operation */
52263   int rc = SQLITE_OK;        /* Value to return */
52264   sqlite3 *db = p->db;       /* The database */
52265   u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */
52266   u8 encoding = ENC(db);     /* The database encoding */
52267 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
52268   int checkProgress;         /* True if progress callbacks are enabled */
52269   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
52270 #endif
52271   Mem *aMem = p->aMem;       /* Copy of p->aMem */
52272   Mem *pIn1 = 0;             /* 1st input operand */
52273   Mem *pIn2 = 0;             /* 2nd input operand */
52274   Mem *pIn3 = 0;             /* 3rd input operand */
52275   Mem *pOut = 0;             /* Output operand */
52276   int iCompare = 0;          /* Result of last OP_Compare operation */
52277   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
52278 #ifdef VDBE_PROFILE
52279   u64 start;                 /* CPU clock count at start of opcode */
52280   int origPc;                /* Program counter at start of opcode */
52281 #endif
52282   /********************************************************************
52283   ** Automatically generated code
52284   **
52285   ** The following union is automatically generated by the
52286   ** vdbe-compress.tcl script.  The purpose of this union is to
52287   ** reduce the amount of stack space required by this function.
52288   ** See comments in the vdbe-compress.tcl script for details.
52289   */
52290   union vdbeExecUnion {
52291     struct OP_Yield_stack_vars {
52292       int pcDest;
52293     } aa;
52294     struct OP_Variable_stack_vars {
52295       int p1;          /* Variable to copy from */
52296       int p2;          /* Register to copy to */
52297       int n;           /* Number of values left to copy */
52298       Mem *pVar;       /* Value being transferred */
52299     } ab;
52300     struct OP_Move_stack_vars {
52301       char *zMalloc;   /* Holding variable for allocated memory */
52302       int n;           /* Number of registers left to copy */
52303       int p1;          /* Register to copy from */
52304       int p2;          /* Register to copy to */
52305     } ac;
52306     struct OP_ResultRow_stack_vars {
52307       Mem *pMem;
52308       int i;
52309     } ad;
52310     struct OP_Concat_stack_vars {
52311       i64 nByte;
52312     } ae;
52313     struct OP_Remainder_stack_vars {
52314       int flags;      /* Combined MEM_* flags from both inputs */
52315       i64 iA;         /* Integer value of left operand */
52316       i64 iB;         /* Integer value of right operand */
52317       double rA;      /* Real value of left operand */
52318       double rB;      /* Real value of right operand */
52319     } af;
52320     struct OP_Function_stack_vars {
52321       int i;
52322       Mem *pArg;
52323       sqlite3_context ctx;
52324       sqlite3_value **apVal;
52325       int n;
52326     } ag;
52327     struct OP_ShiftRight_stack_vars {
52328       i64 a;
52329       i64 b;
52330     } ah;
52331     struct OP_Ge_stack_vars {
52332       int res;            /* Result of the comparison of pIn1 against pIn3 */
52333       char affinity;      /* Affinity to use for comparison */
52334     } ai;
52335     struct OP_Compare_stack_vars {
52336       int n;
52337       int i;
52338       int p1;
52339       int p2;
52340       const KeyInfo *pKeyInfo;
52341       int idx;
52342       CollSeq *pColl;    /* Collating sequence to use on this term */
52343       int bRev;          /* True for DESCENDING sort order */
52344     } aj;
52345     struct OP_Or_stack_vars {
52346       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
52347       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
52348     } ak;
52349     struct OP_IfNot_stack_vars {
52350       int c;
52351     } al;
52352     struct OP_Column_stack_vars {
52353       u32 payloadSize;   /* Number of bytes in the record */
52354       i64 payloadSize64; /* Number of bytes in the record */
52355       int p1;            /* P1 value of the opcode */
52356       int p2;            /* column number to retrieve */
52357       VdbeCursor *pC;    /* The VDBE cursor */
52358       char *zRec;        /* Pointer to complete record-data */
52359       BtCursor *pCrsr;   /* The BTree cursor */
52360       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
52361       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
52362       int nField;        /* number of fields in the record */
52363       int len;           /* The length of the serialized data for the column */
52364       int i;             /* Loop counter */
52365       char *zData;       /* Part of the record being decoded */
52366       Mem *pDest;        /* Where to write the extracted value */
52367       Mem sMem;          /* For storing the record being decoded */
52368       u8 *zIdx;          /* Index into header */
52369       u8 *zEndHdr;       /* Pointer to first byte after the header */
52370       u32 offset;        /* Offset into the data */
52371       u64 offset64;      /* 64-bit offset.  64 bits needed to catch overflow */
52372       int szHdr;         /* Size of the header size field at start of record */
52373       int avail;         /* Number of bytes of available data */
52374       Mem *pReg;         /* PseudoTable input register */
52375     } am;
52376     struct OP_Affinity_stack_vars {
52377       const char *zAffinity;   /* The affinity to be applied */
52378       char cAff;               /* A single character of affinity */
52379     } an;
52380     struct OP_MakeRecord_stack_vars {
52381       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
52382       Mem *pRec;             /* The new record */
52383       u64 nData;             /* Number of bytes of data space */
52384       int nHdr;              /* Number of bytes of header space */
52385       i64 nByte;             /* Data space required for this record */
52386       int nZero;             /* Number of zero bytes at the end of the record */
52387       int nVarint;           /* Number of bytes in a varint */
52388       u32 serial_type;       /* Type field */
52389       Mem *pData0;           /* First field to be combined into the record */
52390       Mem *pLast;            /* Last field of the record */
52391       int nField;            /* Number of fields in the record */
52392       char *zAffinity;       /* The affinity string for the record */
52393       int file_format;       /* File format to use for encoding */
52394       int i;                 /* Space used in zNewRecord[] */
52395       int len;               /* Length of a field */
52396     } ao;
52397     struct OP_Count_stack_vars {
52398       i64 nEntry;
52399       BtCursor *pCrsr;
52400     } ap;
52401     struct OP_Savepoint_stack_vars {
52402       int p1;                         /* Value of P1 operand */
52403       char *zName;                    /* Name of savepoint */
52404       int nName;
52405       Savepoint *pNew;
52406       Savepoint *pSavepoint;
52407       Savepoint *pTmp;
52408       int iSavepoint;
52409       int ii;
52410     } aq;
52411     struct OP_AutoCommit_stack_vars {
52412       int desiredAutoCommit;
52413       int iRollback;
52414       int turnOnAC;
52415     } ar;
52416     struct OP_Transaction_stack_vars {
52417       Btree *pBt;
52418     } as;
52419     struct OP_ReadCookie_stack_vars {
52420       int iMeta;
52421       int iDb;
52422       int iCookie;
52423     } at;
52424     struct OP_SetCookie_stack_vars {
52425       Db *pDb;
52426     } au;
52427     struct OP_VerifyCookie_stack_vars {
52428       int iMeta;
52429       Btree *pBt;
52430     } av;
52431     struct OP_OpenWrite_stack_vars {
52432       int nField;
52433       KeyInfo *pKeyInfo;
52434       int p2;
52435       int iDb;
52436       int wrFlag;
52437       Btree *pX;
52438       VdbeCursor *pCur;
52439       Db *pDb;
52440     } aw;
52441     struct OP_OpenEphemeral_stack_vars {
52442       VdbeCursor *pCx;
52443     } ax;
52444     struct OP_OpenPseudo_stack_vars {
52445       VdbeCursor *pCx;
52446     } ay;
52447     struct OP_SeekGt_stack_vars {
52448       int res;
52449       int oc;
52450       VdbeCursor *pC;
52451       UnpackedRecord r;
52452       int nField;
52453       i64 iKey;      /* The rowid we are to seek to */
52454     } az;
52455     struct OP_Seek_stack_vars {
52456       VdbeCursor *pC;
52457     } ba;
52458     struct OP_Found_stack_vars {
52459       int alreadyExists;
52460       VdbeCursor *pC;
52461       int res;
52462       UnpackedRecord *pIdxKey;
52463       UnpackedRecord r;
52464       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
52465     } bb;
52466     struct OP_IsUnique_stack_vars {
52467       u16 ii;
52468       VdbeCursor *pCx;
52469       BtCursor *pCrsr;
52470       u16 nField;
52471       Mem *aMx;
52472       UnpackedRecord r;                  /* B-Tree index search key */
52473       i64 R;                             /* Rowid stored in register P3 */
52474     } bc;
52475     struct OP_NotExists_stack_vars {
52476       VdbeCursor *pC;
52477       BtCursor *pCrsr;
52478       int res;
52479       u64 iKey;
52480     } bd;
52481     struct OP_NewRowid_stack_vars {
52482       i64 v;                 /* The new rowid */
52483       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
52484       int res;               /* Result of an sqlite3BtreeLast() */
52485       int cnt;               /* Counter to limit the number of searches */
52486       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
52487       VdbeFrame *pFrame;     /* Root frame of VDBE */
52488     } be;
52489     struct OP_InsertInt_stack_vars {
52490       Mem *pData;       /* MEM cell holding data for the record to be inserted */
52491       Mem *pKey;        /* MEM cell holding key  for the record */
52492       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
52493       VdbeCursor *pC;   /* Cursor to table into which insert is written */
52494       int nZero;        /* Number of zero-bytes to append */
52495       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
52496       const char *zDb;  /* database name - used by the update hook */
52497       const char *zTbl; /* Table name - used by the opdate hook */
52498       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
52499     } bf;
52500     struct OP_Delete_stack_vars {
52501       i64 iKey;
52502       VdbeCursor *pC;
52503     } bg;
52504     struct OP_RowData_stack_vars {
52505       VdbeCursor *pC;
52506       BtCursor *pCrsr;
52507       u32 n;
52508       i64 n64;
52509     } bh;
52510     struct OP_Rowid_stack_vars {
52511       VdbeCursor *pC;
52512       i64 v;
52513       sqlite3_vtab *pVtab;
52514       const sqlite3_module *pModule;
52515     } bi;
52516     struct OP_NullRow_stack_vars {
52517       VdbeCursor *pC;
52518     } bj;
52519     struct OP_Last_stack_vars {
52520       VdbeCursor *pC;
52521       BtCursor *pCrsr;
52522       int res;
52523     } bk;
52524     struct OP_Rewind_stack_vars {
52525       VdbeCursor *pC;
52526       BtCursor *pCrsr;
52527       int res;
52528     } bl;
52529     struct OP_Next_stack_vars {
52530       VdbeCursor *pC;
52531       BtCursor *pCrsr;
52532       int res;
52533     } bm;
52534     struct OP_IdxInsert_stack_vars {
52535       VdbeCursor *pC;
52536       BtCursor *pCrsr;
52537       int nKey;
52538       const char *zKey;
52539     } bn;
52540     struct OP_IdxDelete_stack_vars {
52541       VdbeCursor *pC;
52542       BtCursor *pCrsr;
52543       int res;
52544       UnpackedRecord r;
52545     } bo;
52546     struct OP_IdxRowid_stack_vars {
52547       BtCursor *pCrsr;
52548       VdbeCursor *pC;
52549       i64 rowid;
52550     } bp;
52551     struct OP_IdxGE_stack_vars {
52552       VdbeCursor *pC;
52553       int res;
52554       UnpackedRecord r;
52555     } bq;
52556     struct OP_Destroy_stack_vars {
52557       int iMoved;
52558       int iCnt;
52559       Vdbe *pVdbe;
52560       int iDb;
52561     } br;
52562     struct OP_Clear_stack_vars {
52563       int nChange;
52564     } bs;
52565     struct OP_CreateTable_stack_vars {
52566       int pgno;
52567       int flags;
52568       Db *pDb;
52569     } bt;
52570     struct OP_ParseSchema_stack_vars {
52571       int iDb;
52572       const char *zMaster;
52573       char *zSql;
52574       InitData initData;
52575     } bu;
52576     struct OP_IntegrityCk_stack_vars {
52577       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
52578       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
52579       int j;          /* Loop counter */
52580       int nErr;       /* Number of errors reported */
52581       char *z;        /* Text of the error report */
52582       Mem *pnErr;     /* Register keeping track of errors remaining */
52583     } bv;
52584     struct OP_RowSetRead_stack_vars {
52585       i64 val;
52586     } bw;
52587     struct OP_RowSetTest_stack_vars {
52588       int iSet;
52589       int exists;
52590     } bx;
52591     struct OP_Program_stack_vars {
52592       int nMem;               /* Number of memory registers for sub-program */
52593       int nByte;              /* Bytes of runtime space required for sub-program */
52594       Mem *pRt;               /* Register to allocate runtime space */
52595       Mem *pMem;              /* Used to iterate through memory cells */
52596       Mem *pEnd;              /* Last memory cell in new array */
52597       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
52598       SubProgram *pProgram;   /* Sub-program to execute */
52599       void *t;                /* Token identifying trigger */
52600     } by;
52601     struct OP_Param_stack_vars {
52602       VdbeFrame *pFrame;
52603       Mem *pIn;
52604     } bz;
52605     struct OP_MemMax_stack_vars {
52606       Mem *pIn1;
52607       VdbeFrame *pFrame;
52608     } ca;
52609     struct OP_AggStep_stack_vars {
52610       int n;
52611       int i;
52612       Mem *pMem;
52613       Mem *pRec;
52614       sqlite3_context ctx;
52615       sqlite3_value **apVal;
52616     } cb;
52617     struct OP_AggFinal_stack_vars {
52618       Mem *pMem;
52619     } cc;
52620     struct OP_IncrVacuum_stack_vars {
52621       Btree *pBt;
52622     } cd;
52623     struct OP_VBegin_stack_vars {
52624       VTable *pVTab;
52625     } ce;
52626     struct OP_VOpen_stack_vars {
52627       VdbeCursor *pCur;
52628       sqlite3_vtab_cursor *pVtabCursor;
52629       sqlite3_vtab *pVtab;
52630       sqlite3_module *pModule;
52631     } cf;
52632     struct OP_VFilter_stack_vars {
52633       int nArg;
52634       int iQuery;
52635       const sqlite3_module *pModule;
52636       Mem *pQuery;
52637       Mem *pArgc;
52638       sqlite3_vtab_cursor *pVtabCursor;
52639       sqlite3_vtab *pVtab;
52640       VdbeCursor *pCur;
52641       int res;
52642       int i;
52643       Mem **apArg;
52644     } cg;
52645     struct OP_VColumn_stack_vars {
52646       sqlite3_vtab *pVtab;
52647       const sqlite3_module *pModule;
52648       Mem *pDest;
52649       sqlite3_context sContext;
52650     } ch;
52651     struct OP_VNext_stack_vars {
52652       sqlite3_vtab *pVtab;
52653       const sqlite3_module *pModule;
52654       int res;
52655       VdbeCursor *pCur;
52656     } ci;
52657     struct OP_VRename_stack_vars {
52658       sqlite3_vtab *pVtab;
52659       Mem *pName;
52660     } cj;
52661     struct OP_VUpdate_stack_vars {
52662       sqlite3_vtab *pVtab;
52663       sqlite3_module *pModule;
52664       int nArg;
52665       int i;
52666       sqlite_int64 rowid;
52667       Mem **apArg;
52668       Mem *pX;
52669     } ck;
52670     struct OP_Pagecount_stack_vars {
52671       int p1;
52672       int nPage;
52673       Pager *pPager;
52674     } cl;
52675     struct OP_Trace_stack_vars {
52676       char *zTrace;
52677     } cm;
52678   } u;
52679   /* End automatically generated code
52680   ********************************************************************/
52681
52682   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
52683   assert( db->magic==SQLITE_MAGIC_BUSY );
52684   sqlite3VdbeMutexArrayEnter(p);
52685   if( p->rc==SQLITE_NOMEM ){
52686     /* This happens if a malloc() inside a call to sqlite3_column_text() or
52687     ** sqlite3_column_text16() failed.  */
52688     goto no_mem;
52689   }
52690   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
52691   p->rc = SQLITE_OK;
52692   assert( p->explain==0 );
52693   p->pResultSet = 0;
52694   db->busyHandler.nBusy = 0;
52695   CHECK_FOR_INTERRUPT;
52696   sqlite3VdbeIOTraceSql(p);
52697 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
52698   checkProgress = db->xProgress!=0;
52699 #endif
52700 #ifdef SQLITE_DEBUG
52701   sqlite3BeginBenignMalloc();
52702   if( p->pc==0 
52703    && ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
52704   ){
52705     int i;
52706     printf("VDBE Program Listing:\n");
52707     sqlite3VdbePrintSql(p);
52708     for(i=0; i<p->nOp; i++){
52709       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
52710     }
52711   }
52712   if( fileExists(db, "vdbe_trace") ){
52713     p->trace = stdout;
52714   }
52715   sqlite3EndBenignMalloc();
52716 #endif
52717   for(pc=p->pc; rc==SQLITE_OK; pc++){
52718     assert( pc>=0 && pc<p->nOp );
52719     if( db->mallocFailed ) goto no_mem;
52720 #ifdef VDBE_PROFILE
52721     origPc = pc;
52722     start = sqlite3Hwtime();
52723 #endif
52724     pOp = &aOp[pc];
52725
52726     /* Only allow tracing if SQLITE_DEBUG is defined.
52727     */
52728 #ifdef SQLITE_DEBUG
52729     if( p->trace ){
52730       if( pc==0 ){
52731         printf("VDBE Execution Trace:\n");
52732         sqlite3VdbePrintSql(p);
52733       }
52734       sqlite3VdbePrintOp(p->trace, pc, pOp);
52735     }
52736     if( p->trace==0 && pc==0 ){
52737       sqlite3BeginBenignMalloc();
52738       if( fileExists(db, "vdbe_sqltrace") ){
52739         sqlite3VdbePrintSql(p);
52740       }
52741       sqlite3EndBenignMalloc();
52742     }
52743 #endif
52744       
52745
52746     /* Check to see if we need to simulate an interrupt.  This only happens
52747     ** if we have a special test build.
52748     */
52749 #ifdef SQLITE_TEST
52750     if( sqlite3_interrupt_count>0 ){
52751       sqlite3_interrupt_count--;
52752       if( sqlite3_interrupt_count==0 ){
52753         sqlite3_interrupt(db);
52754       }
52755     }
52756 #endif
52757
52758 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
52759     /* Call the progress callback if it is configured and the required number
52760     ** of VDBE ops have been executed (either since this invocation of
52761     ** sqlite3VdbeExec() or since last time the progress callback was called).
52762     ** If the progress callback returns non-zero, exit the virtual machine with
52763     ** a return code SQLITE_ABORT.
52764     */
52765     if( checkProgress ){
52766       if( db->nProgressOps==nProgressOps ){
52767         int prc;
52768         if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
52769         prc =db->xProgress(db->pProgressArg);
52770         if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
52771         if( prc!=0 ){
52772           rc = SQLITE_INTERRUPT;
52773           goto vdbe_error_halt;
52774         }
52775         nProgressOps = 0;
52776       }
52777       nProgressOps++;
52778     }
52779 #endif
52780
52781     /* On any opcode with the "out2-prerelase" tag, free any
52782     ** external allocations out of mem[p2] and set mem[p2] to be
52783     ** an undefined integer.  Opcodes will either fill in the integer
52784     ** value or convert mem[p2] to a different type.
52785     */
52786     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
52787     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
52788       assert( pOp->p2>0 );
52789       assert( pOp->p2<=p->nMem );
52790       pOut = &aMem[pOp->p2];
52791       sqlite3VdbeMemReleaseExternal(pOut);
52792       pOut->flags = MEM_Int;
52793     }
52794
52795     /* Sanity checking on other operands */
52796 #ifdef SQLITE_DEBUG
52797     if( (pOp->opflags & OPFLG_IN1)!=0 ){
52798       assert( pOp->p1>0 );
52799       assert( pOp->p1<=p->nMem );
52800       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
52801     }
52802     if( (pOp->opflags & OPFLG_IN2)!=0 ){
52803       assert( pOp->p2>0 );
52804       assert( pOp->p2<=p->nMem );
52805       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
52806     }
52807     if( (pOp->opflags & OPFLG_IN3)!=0 ){
52808       assert( pOp->p3>0 );
52809       assert( pOp->p3<=p->nMem );
52810       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
52811     }
52812     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
52813       assert( pOp->p2>0 );
52814       assert( pOp->p2<=p->nMem );
52815     }
52816     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
52817       assert( pOp->p3>0 );
52818       assert( pOp->p3<=p->nMem );
52819     }
52820 #endif
52821   
52822     switch( pOp->opcode ){
52823
52824 /*****************************************************************************
52825 ** What follows is a massive switch statement where each case implements a
52826 ** separate instruction in the virtual machine.  If we follow the usual
52827 ** indentation conventions, each case should be indented by 6 spaces.  But
52828 ** that is a lot of wasted space on the left margin.  So the code within
52829 ** the switch statement will break with convention and be flush-left. Another
52830 ** big comment (similar to this one) will mark the point in the code where
52831 ** we transition back to normal indentation.
52832 **
52833 ** The formatting of each case is important.  The makefile for SQLite
52834 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
52835 ** file looking for lines that begin with "case OP_".  The opcodes.h files
52836 ** will be filled with #defines that give unique integer values to each
52837 ** opcode and the opcodes.c file is filled with an array of strings where
52838 ** each string is the symbolic name for the corresponding opcode.  If the
52839 ** case statement is followed by a comment of the form "/# same as ... #/"
52840 ** that comment is used to determine the particular value of the opcode.
52841 **
52842 ** Other keywords in the comment that follows each case are used to
52843 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
52844 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
52845 ** the mkopcodeh.awk script for additional information.
52846 **
52847 ** Documentation about VDBE opcodes is generated by scanning this file
52848 ** for lines of that contain "Opcode:".  That line and all subsequent
52849 ** comment lines are used in the generation of the opcode.html documentation
52850 ** file.
52851 **
52852 ** SUMMARY:
52853 **
52854 **     Formatting is important to scripts that scan this file.
52855 **     Do not deviate from the formatting style currently in use.
52856 **
52857 *****************************************************************************/
52858
52859 /* Opcode:  Goto * P2 * * *
52860 **
52861 ** An unconditional jump to address P2.
52862 ** The next instruction executed will be 
52863 ** the one at index P2 from the beginning of
52864 ** the program.
52865 */
52866 case OP_Goto: {             /* jump */
52867   CHECK_FOR_INTERRUPT;
52868   pc = pOp->p2 - 1;
52869   break;
52870 }
52871
52872 /* Opcode:  Gosub P1 P2 * * *
52873 **
52874 ** Write the current address onto register P1
52875 ** and then jump to address P2.
52876 */
52877 case OP_Gosub: {            /* jump, in1 */
52878   pIn1 = &aMem[pOp->p1];
52879   assert( (pIn1->flags & MEM_Dyn)==0 );
52880   pIn1->flags = MEM_Int;
52881   pIn1->u.i = pc;
52882   REGISTER_TRACE(pOp->p1, pIn1);
52883   pc = pOp->p2 - 1;
52884   break;
52885 }
52886
52887 /* Opcode:  Return P1 * * * *
52888 **
52889 ** Jump to the next instruction after the address in register P1.
52890 */
52891 case OP_Return: {           /* in1 */
52892   pIn1 = &aMem[pOp->p1];
52893   assert( pIn1->flags & MEM_Int );
52894   pc = (int)pIn1->u.i;
52895   break;
52896 }
52897
52898 /* Opcode:  Yield P1 * * * *
52899 **
52900 ** Swap the program counter with the value in register P1.
52901 */
52902 case OP_Yield: {            /* in1 */
52903 #if 0  /* local variables moved into u.aa */
52904   int pcDest;
52905 #endif /* local variables moved into u.aa */
52906   pIn1 = &aMem[pOp->p1];
52907   assert( (pIn1->flags & MEM_Dyn)==0 );
52908   pIn1->flags = MEM_Int;
52909   u.aa.pcDest = (int)pIn1->u.i;
52910   pIn1->u.i = pc;
52911   REGISTER_TRACE(pOp->p1, pIn1);
52912   pc = u.aa.pcDest;
52913   break;
52914 }
52915
52916 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
52917 **
52918 ** Check the value in register P3.  If is is NULL then Halt using
52919 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
52920 ** value in register P3 is not NULL, then this routine is a no-op.
52921 */
52922 case OP_HaltIfNull: {      /* in3 */
52923   pIn3 = &aMem[pOp->p3];
52924   if( (pIn3->flags & MEM_Null)==0 ) break;
52925   /* Fall through into OP_Halt */
52926 }
52927
52928 /* Opcode:  Halt P1 P2 * P4 *
52929 **
52930 ** Exit immediately.  All open cursors, etc are closed
52931 ** automatically.
52932 **
52933 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
52934 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
52935 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
52936 ** whether or not to rollback the current transaction.  Do not rollback
52937 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
52938 ** then back out all changes that have occurred during this execution of the
52939 ** VDBE, but do not rollback the transaction. 
52940 **
52941 ** If P4 is not null then it is an error message string.
52942 **
52943 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
52944 ** every program.  So a jump past the last instruction of the program
52945 ** is the same as executing Halt.
52946 */
52947 case OP_Halt: {
52948   if( pOp->p1==SQLITE_OK && p->pFrame ){
52949     /* Halt the sub-program. Return control to the parent frame. */
52950     VdbeFrame *pFrame = p->pFrame;
52951     p->pFrame = pFrame->pParent;
52952     p->nFrame--;
52953     sqlite3VdbeSetChanges(db, p->nChange);
52954     pc = sqlite3VdbeFrameRestore(pFrame);
52955     if( pOp->p2==OE_Ignore ){
52956       /* Instruction pc is the OP_Program that invoked the sub-program 
52957       ** currently being halted. If the p2 instruction of this OP_Halt
52958       ** instruction is set to OE_Ignore, then the sub-program is throwing
52959       ** an IGNORE exception. In this case jump to the address specified
52960       ** as the p2 of the calling OP_Program.  */
52961       pc = p->aOp[pc].p2-1;
52962     }
52963     aOp = p->aOp;
52964     aMem = p->aMem;
52965     break;
52966   }
52967
52968   p->rc = pOp->p1;
52969   p->errorAction = (u8)pOp->p2;
52970   p->pc = pc;
52971   if( pOp->p4.z ){
52972     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
52973   }
52974   rc = sqlite3VdbeHalt(p);
52975   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
52976   if( rc==SQLITE_BUSY ){
52977     p->rc = rc = SQLITE_BUSY;
52978   }else{
52979     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
52980     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
52981     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
52982   }
52983   goto vdbe_return;
52984 }
52985
52986 /* Opcode: Integer P1 P2 * * *
52987 **
52988 ** The 32-bit integer value P1 is written into register P2.
52989 */
52990 case OP_Integer: {         /* out2-prerelease */
52991   pOut->u.i = pOp->p1;
52992   break;
52993 }
52994
52995 /* Opcode: Int64 * P2 * P4 *
52996 **
52997 ** P4 is a pointer to a 64-bit integer value.
52998 ** Write that value into register P2.
52999 */
53000 case OP_Int64: {           /* out2-prerelease */
53001   assert( pOp->p4.pI64!=0 );
53002   pOut->u.i = *pOp->p4.pI64;
53003   break;
53004 }
53005
53006 /* Opcode: Real * P2 * P4 *
53007 **
53008 ** P4 is a pointer to a 64-bit floating point value.
53009 ** Write that value into register P2.
53010 */
53011 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
53012   pOut->flags = MEM_Real;
53013   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
53014   pOut->r = *pOp->p4.pReal;
53015   break;
53016 }
53017
53018 /* Opcode: String8 * P2 * P4 *
53019 **
53020 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
53021 ** into an OP_String before it is executed for the first time.
53022 */
53023 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
53024   assert( pOp->p4.z!=0 );
53025   pOp->opcode = OP_String;
53026   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
53027
53028 #ifndef SQLITE_OMIT_UTF16
53029   if( encoding!=SQLITE_UTF8 ){
53030     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
53031     if( rc==SQLITE_TOOBIG ) goto too_big;
53032     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
53033     assert( pOut->zMalloc==pOut->z );
53034     assert( pOut->flags & MEM_Dyn );
53035     pOut->zMalloc = 0;
53036     pOut->flags |= MEM_Static;
53037     pOut->flags &= ~MEM_Dyn;
53038     if( pOp->p4type==P4_DYNAMIC ){
53039       sqlite3DbFree(db, pOp->p4.z);
53040     }
53041     pOp->p4type = P4_DYNAMIC;
53042     pOp->p4.z = pOut->z;
53043     pOp->p1 = pOut->n;
53044   }
53045 #endif
53046   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
53047     goto too_big;
53048   }
53049   /* Fall through to the next case, OP_String */
53050 }
53051   
53052 /* Opcode: String P1 P2 * P4 *
53053 **
53054 ** The string value P4 of length P1 (bytes) is stored in register P2.
53055 */
53056 case OP_String: {          /* out2-prerelease */
53057   assert( pOp->p4.z!=0 );
53058   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
53059   pOut->z = pOp->p4.z;
53060   pOut->n = pOp->p1;
53061   pOut->enc = encoding;
53062   UPDATE_MAX_BLOBSIZE(pOut);
53063   break;
53064 }
53065
53066 /* Opcode: Null * P2 * * *
53067 **
53068 ** Write a NULL into register P2.
53069 */
53070 case OP_Null: {           /* out2-prerelease */
53071   pOut->flags = MEM_Null;
53072   break;
53073 }
53074
53075
53076 /* Opcode: Blob P1 P2 * P4
53077 **
53078 ** P4 points to a blob of data P1 bytes long.  Store this
53079 ** blob in register P2. This instruction is not coded directly
53080 ** by the compiler. Instead, the compiler layer specifies
53081 ** an OP_HexBlob opcode, with the hex string representation of
53082 ** the blob as P4. This opcode is transformed to an OP_Blob
53083 ** the first time it is executed.
53084 */
53085 case OP_Blob: {                /* out2-prerelease */
53086   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
53087   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
53088   pOut->enc = encoding;
53089   UPDATE_MAX_BLOBSIZE(pOut);
53090   break;
53091 }
53092
53093 /* Opcode: Variable P1 P2 P3 P4 *
53094 **
53095 ** Transfer the values of bound parameters P1..P1+P3-1 into registers
53096 ** P2..P2+P3-1.
53097 **
53098 ** If the parameter is named, then its name appears in P4 and P3==1.
53099 ** The P4 value is used by sqlite3_bind_parameter_name().
53100 */
53101 case OP_Variable: {
53102 #if 0  /* local variables moved into u.ab */
53103   int p1;          /* Variable to copy from */
53104   int p2;          /* Register to copy to */
53105   int n;           /* Number of values left to copy */
53106   Mem *pVar;       /* Value being transferred */
53107 #endif /* local variables moved into u.ab */
53108
53109   u.ab.p1 = pOp->p1 - 1;
53110   u.ab.p2 = pOp->p2;
53111   u.ab.n = pOp->p3;
53112   assert( u.ab.p1>=0 && u.ab.p1+u.ab.n<=p->nVar );
53113   assert( u.ab.p2>=1 && u.ab.p2+u.ab.n-1<=p->nMem );
53114   assert( pOp->p4.z==0 || pOp->p3==1 || pOp->p3==0 );
53115
53116   while( u.ab.n-- > 0 ){
53117     u.ab.pVar = &p->aVar[u.ab.p1++];
53118     if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
53119       goto too_big;
53120     }
53121     pOut = &aMem[u.ab.p2++];
53122     sqlite3VdbeMemReleaseExternal(pOut);
53123     pOut->flags = MEM_Null;
53124     sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
53125     UPDATE_MAX_BLOBSIZE(pOut);
53126   }
53127   break;
53128 }
53129
53130 /* Opcode: Move P1 P2 P3 * *
53131 **
53132 ** Move the values in register P1..P1+P3-1 over into
53133 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
53134 ** left holding a NULL.  It is an error for register ranges
53135 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
53136 */
53137 case OP_Move: {
53138 #if 0  /* local variables moved into u.ac */
53139   char *zMalloc;   /* Holding variable for allocated memory */
53140   int n;           /* Number of registers left to copy */
53141   int p1;          /* Register to copy from */
53142   int p2;          /* Register to copy to */
53143 #endif /* local variables moved into u.ac */
53144
53145   u.ac.n = pOp->p3;
53146   u.ac.p1 = pOp->p1;
53147   u.ac.p2 = pOp->p2;
53148   assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
53149   assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
53150
53151   pIn1 = &aMem[u.ac.p1];
53152   pOut = &aMem[u.ac.p2];
53153   while( u.ac.n-- ){
53154     assert( pOut<=&aMem[p->nMem] );
53155     assert( pIn1<=&aMem[p->nMem] );
53156     u.ac.zMalloc = pOut->zMalloc;
53157     pOut->zMalloc = 0;
53158     sqlite3VdbeMemMove(pOut, pIn1);
53159     pIn1->zMalloc = u.ac.zMalloc;
53160     REGISTER_TRACE(u.ac.p2++, pOut);
53161     pIn1++;
53162     pOut++;
53163   }
53164   break;
53165 }
53166
53167 /* Opcode: Copy P1 P2 * * *
53168 **
53169 ** Make a copy of register P1 into register P2.
53170 **
53171 ** This instruction makes a deep copy of the value.  A duplicate
53172 ** is made of any string or blob constant.  See also OP_SCopy.
53173 */
53174 case OP_Copy: {             /* in1, out2 */
53175   pIn1 = &aMem[pOp->p1];
53176   pOut = &aMem[pOp->p2];
53177   assert( pOut!=pIn1 );
53178   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
53179   Deephemeralize(pOut);
53180   REGISTER_TRACE(pOp->p2, pOut);
53181   break;
53182 }
53183
53184 /* Opcode: SCopy P1 P2 * * *
53185 **
53186 ** Make a shallow copy of register P1 into register P2.
53187 **
53188 ** This instruction makes a shallow copy of the value.  If the value
53189 ** is a string or blob, then the copy is only a pointer to the
53190 ** original and hence if the original changes so will the copy.
53191 ** Worse, if the original is deallocated, the copy becomes invalid.
53192 ** Thus the program must guarantee that the original will not change
53193 ** during the lifetime of the copy.  Use OP_Copy to make a complete
53194 ** copy.
53195 */
53196 case OP_SCopy: {            /* in1, out2 */
53197   pIn1 = &aMem[pOp->p1];
53198   pOut = &aMem[pOp->p2];
53199   assert( pOut!=pIn1 );
53200   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
53201   REGISTER_TRACE(pOp->p2, pOut);
53202   break;
53203 }
53204
53205 /* Opcode: ResultRow P1 P2 * * *
53206 **
53207 ** The registers P1 through P1+P2-1 contain a single row of
53208 ** results. This opcode causes the sqlite3_step() call to terminate
53209 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
53210 ** structure to provide access to the top P1 values as the result
53211 ** row.
53212 */
53213 case OP_ResultRow: {
53214 #if 0  /* local variables moved into u.ad */
53215   Mem *pMem;
53216   int i;
53217 #endif /* local variables moved into u.ad */
53218   assert( p->nResColumn==pOp->p2 );
53219   assert( pOp->p1>0 );
53220   assert( pOp->p1+pOp->p2<=p->nMem+1 );
53221
53222   /* If this statement has violated immediate foreign key constraints, do
53223   ** not return the number of rows modified. And do not RELEASE the statement
53224   ** transaction. It needs to be rolled back.  */
53225   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
53226     assert( db->flags&SQLITE_CountRows );
53227     assert( p->usesStmtJournal );
53228     break;
53229   }
53230
53231   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
53232   ** DML statements invoke this opcode to return the number of rows
53233   ** modified to the user. This is the only way that a VM that
53234   ** opens a statement transaction may invoke this opcode.
53235   **
53236   ** In case this is such a statement, close any statement transaction
53237   ** opened by this VM before returning control to the user. This is to
53238   ** ensure that statement-transactions are always nested, not overlapping.
53239   ** If the open statement-transaction is not closed here, then the user
53240   ** may step another VM that opens its own statement transaction. This
53241   ** may lead to overlapping statement transactions.
53242   **
53243   ** The statement transaction is never a top-level transaction.  Hence
53244   ** the RELEASE call below can never fail.
53245   */
53246   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
53247   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
53248   if( NEVER(rc!=SQLITE_OK) ){
53249     break;
53250   }
53251
53252   /* Invalidate all ephemeral cursor row caches */
53253   p->cacheCtr = (p->cacheCtr + 2)|1;
53254
53255   /* Make sure the results of the current row are \000 terminated
53256   ** and have an assigned type.  The results are de-ephemeralized as
53257   ** as side effect.
53258   */
53259   u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
53260   for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
53261     sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
53262     sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
53263     REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
53264   }
53265   if( db->mallocFailed ) goto no_mem;
53266
53267   /* Return SQLITE_ROW
53268   */
53269   p->pc = pc + 1;
53270   rc = SQLITE_ROW;
53271   goto vdbe_return;
53272 }
53273
53274 /* Opcode: Concat P1 P2 P3 * *
53275 **
53276 ** Add the text in register P1 onto the end of the text in
53277 ** register P2 and store the result in register P3.
53278 ** If either the P1 or P2 text are NULL then store NULL in P3.
53279 **
53280 **   P3 = P2 || P1
53281 **
53282 ** It is illegal for P1 and P3 to be the same register. Sometimes,
53283 ** if P3 is the same register as P2, the implementation is able
53284 ** to avoid a memcpy().
53285 */
53286 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
53287 #if 0  /* local variables moved into u.ae */
53288   i64 nByte;
53289 #endif /* local variables moved into u.ae */
53290
53291   pIn1 = &aMem[pOp->p1];
53292   pIn2 = &aMem[pOp->p2];
53293   pOut = &aMem[pOp->p3];
53294   assert( pIn1!=pOut );
53295   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
53296     sqlite3VdbeMemSetNull(pOut);
53297     break;
53298   }
53299   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
53300   Stringify(pIn1, encoding);
53301   Stringify(pIn2, encoding);
53302   u.ae.nByte = pIn1->n + pIn2->n;
53303   if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
53304     goto too_big;
53305   }
53306   MemSetTypeFlag(pOut, MEM_Str);
53307   if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
53308     goto no_mem;
53309   }
53310   if( pOut!=pIn2 ){
53311     memcpy(pOut->z, pIn2->z, pIn2->n);
53312   }
53313   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
53314   pOut->z[u.ae.nByte] = 0;
53315   pOut->z[u.ae.nByte+1] = 0;
53316   pOut->flags |= MEM_Term;
53317   pOut->n = (int)u.ae.nByte;
53318   pOut->enc = encoding;
53319   UPDATE_MAX_BLOBSIZE(pOut);
53320   break;
53321 }
53322
53323 /* Opcode: Add P1 P2 P3 * *
53324 **
53325 ** Add the value in register P1 to the value in register P2
53326 ** and store the result in register P3.
53327 ** If either input is NULL, the result is NULL.
53328 */
53329 /* Opcode: Multiply P1 P2 P3 * *
53330 **
53331 **
53332 ** Multiply the value in register P1 by the value in register P2
53333 ** and store the result in register P3.
53334 ** If either input is NULL, the result is NULL.
53335 */
53336 /* Opcode: Subtract P1 P2 P3 * *
53337 **
53338 ** Subtract the value in register P1 from the value in register P2
53339 ** and store the result in register P3.
53340 ** If either input is NULL, the result is NULL.
53341 */
53342 /* Opcode: Divide P1 P2 P3 * *
53343 **
53344 ** Divide the value in register P1 by the value in register P2
53345 ** and store the result in register P3 (P3=P2/P1). If the value in 
53346 ** register P1 is zero, then the result is NULL. If either input is 
53347 ** NULL, the result is NULL.
53348 */
53349 /* Opcode: Remainder P1 P2 P3 * *
53350 **
53351 ** Compute the remainder after integer division of the value in
53352 ** register P1 by the value in register P2 and store the result in P3. 
53353 ** If the value in register P2 is zero the result is NULL.
53354 ** If either operand is NULL, the result is NULL.
53355 */
53356 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
53357 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
53358 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
53359 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
53360 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
53361 #if 0  /* local variables moved into u.af */
53362   int flags;      /* Combined MEM_* flags from both inputs */
53363   i64 iA;         /* Integer value of left operand */
53364   i64 iB;         /* Integer value of right operand */
53365   double rA;      /* Real value of left operand */
53366   double rB;      /* Real value of right operand */
53367 #endif /* local variables moved into u.af */
53368
53369   pIn1 = &aMem[pOp->p1];
53370   applyNumericAffinity(pIn1);
53371   pIn2 = &aMem[pOp->p2];
53372   applyNumericAffinity(pIn2);
53373   pOut = &aMem[pOp->p3];
53374   u.af.flags = pIn1->flags | pIn2->flags;
53375   if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
53376   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
53377     u.af.iA = pIn1->u.i;
53378     u.af.iB = pIn2->u.i;
53379     switch( pOp->opcode ){
53380       case OP_Add:         u.af.iB += u.af.iA;       break;
53381       case OP_Subtract:    u.af.iB -= u.af.iA;       break;
53382       case OP_Multiply:    u.af.iB *= u.af.iA;       break;
53383       case OP_Divide: {
53384         if( u.af.iA==0 ) goto arithmetic_result_is_null;
53385         /* Dividing the largest possible negative 64-bit integer (1<<63) by
53386         ** -1 returns an integer too large to store in a 64-bit data-type. On
53387         ** some architectures, the value overflows to (1<<63). On others,
53388         ** a SIGFPE is issued. The following statement normalizes this
53389         ** behavior so that all architectures behave as if integer
53390         ** overflow occurred.
53391         */
53392         if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) u.af.iA = 1;
53393         u.af.iB /= u.af.iA;
53394         break;
53395       }
53396       default: {
53397         if( u.af.iA==0 ) goto arithmetic_result_is_null;
53398         if( u.af.iA==-1 ) u.af.iA = 1;
53399         u.af.iB %= u.af.iA;
53400         break;
53401       }
53402     }
53403     pOut->u.i = u.af.iB;
53404     MemSetTypeFlag(pOut, MEM_Int);
53405   }else{
53406     u.af.rA = sqlite3VdbeRealValue(pIn1);
53407     u.af.rB = sqlite3VdbeRealValue(pIn2);
53408     switch( pOp->opcode ){
53409       case OP_Add:         u.af.rB += u.af.rA;       break;
53410       case OP_Subtract:    u.af.rB -= u.af.rA;       break;
53411       case OP_Multiply:    u.af.rB *= u.af.rA;       break;
53412       case OP_Divide: {
53413         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
53414         if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
53415         u.af.rB /= u.af.rA;
53416         break;
53417       }
53418       default: {
53419         u.af.iA = (i64)u.af.rA;
53420         u.af.iB = (i64)u.af.rB;
53421         if( u.af.iA==0 ) goto arithmetic_result_is_null;
53422         if( u.af.iA==-1 ) u.af.iA = 1;
53423         u.af.rB = (double)(u.af.iB % u.af.iA);
53424         break;
53425       }
53426     }
53427     if( sqlite3IsNaN(u.af.rB) ){
53428       goto arithmetic_result_is_null;
53429     }
53430     pOut->r = u.af.rB;
53431     MemSetTypeFlag(pOut, MEM_Real);
53432     if( (u.af.flags & MEM_Real)==0 ){
53433       sqlite3VdbeIntegerAffinity(pOut);
53434     }
53435   }
53436   break;
53437
53438 arithmetic_result_is_null:
53439   sqlite3VdbeMemSetNull(pOut);
53440   break;
53441 }
53442
53443 /* Opcode: CollSeq * * P4
53444 **
53445 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
53446 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
53447 ** be returned. This is used by the built-in min(), max() and nullif()
53448 ** functions.
53449 **
53450 ** The interface used by the implementation of the aforementioned functions
53451 ** to retrieve the collation sequence set by this opcode is not available
53452 ** publicly, only to user functions defined in func.c.
53453 */
53454 case OP_CollSeq: {
53455   assert( pOp->p4type==P4_COLLSEQ );
53456   break;
53457 }
53458
53459 /* Opcode: Function P1 P2 P3 P4 P5
53460 **
53461 ** Invoke a user function (P4 is a pointer to a Function structure that
53462 ** defines the function) with P5 arguments taken from register P2 and
53463 ** successors.  The result of the function is stored in register P3.
53464 ** Register P3 must not be one of the function inputs.
53465 **
53466 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
53467 ** function was determined to be constant at compile time. If the first
53468 ** argument was constant then bit 0 of P1 is set. This is used to determine
53469 ** whether meta data associated with a user function argument using the
53470 ** sqlite3_set_auxdata() API may be safely retained until the next
53471 ** invocation of this opcode.
53472 **
53473 ** See also: AggStep and AggFinal
53474 */
53475 case OP_Function: {
53476 #if 0  /* local variables moved into u.ag */
53477   int i;
53478   Mem *pArg;
53479   sqlite3_context ctx;
53480   sqlite3_value **apVal;
53481   int n;
53482 #endif /* local variables moved into u.ag */
53483
53484   u.ag.n = pOp->p5;
53485   u.ag.apVal = p->apArg;
53486   assert( u.ag.apVal || u.ag.n==0 );
53487
53488   assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
53489   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
53490   u.ag.pArg = &aMem[pOp->p2];
53491   for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
53492     u.ag.apVal[u.ag.i] = u.ag.pArg;
53493     sqlite3VdbeMemStoreType(u.ag.pArg);
53494     REGISTER_TRACE(pOp->p2, u.ag.pArg);
53495   }
53496
53497   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
53498   if( pOp->p4type==P4_FUNCDEF ){
53499     u.ag.ctx.pFunc = pOp->p4.pFunc;
53500     u.ag.ctx.pVdbeFunc = 0;
53501   }else{
53502     u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
53503     u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
53504   }
53505
53506   assert( pOp->p3>0 && pOp->p3<=p->nMem );
53507   pOut = &aMem[pOp->p3];
53508   u.ag.ctx.s.flags = MEM_Null;
53509   u.ag.ctx.s.db = db;
53510   u.ag.ctx.s.xDel = 0;
53511   u.ag.ctx.s.zMalloc = 0;
53512
53513   /* The output cell may already have a buffer allocated. Move
53514   ** the pointer to u.ag.ctx.s so in case the user-function can use
53515   ** the already allocated buffer instead of allocating a new one.
53516   */
53517   sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
53518   MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
53519
53520   u.ag.ctx.isError = 0;
53521   if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
53522     assert( pOp>aOp );
53523     assert( pOp[-1].p4type==P4_COLLSEQ );
53524     assert( pOp[-1].opcode==OP_CollSeq );
53525     u.ag.ctx.pColl = pOp[-1].p4.pColl;
53526   }
53527   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
53528   (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal);
53529   if( sqlite3SafetyOn(db) ){
53530     sqlite3VdbeMemRelease(&u.ag.ctx.s);
53531     goto abort_due_to_misuse;
53532   }
53533   if( db->mallocFailed ){
53534     /* Even though a malloc() has failed, the implementation of the
53535     ** user function may have called an sqlite3_result_XXX() function
53536     ** to return a value. The following call releases any resources
53537     ** associated with such a value.
53538     **
53539     ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
53540     ** fails also (the if(...) statement above). But if people are
53541     ** misusing sqlite, they have bigger problems than a leaked value.
53542     */
53543     sqlite3VdbeMemRelease(&u.ag.ctx.s);
53544     goto no_mem;
53545   }
53546
53547   /* If any auxiliary data functions have been called by this user function,
53548   ** immediately call the destructor for any non-static values.
53549   */
53550   if( u.ag.ctx.pVdbeFunc ){
53551     sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
53552     pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
53553     pOp->p4type = P4_VDBEFUNC;
53554   }
53555
53556   /* If the function returned an error, throw an exception */
53557   if( u.ag.ctx.isError ){
53558     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
53559     rc = u.ag.ctx.isError;
53560   }
53561
53562   /* Copy the result of the function into register P3 */
53563   sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
53564   sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
53565   if( sqlite3VdbeMemTooBig(pOut) ){
53566     goto too_big;
53567   }
53568   REGISTER_TRACE(pOp->p3, pOut);
53569   UPDATE_MAX_BLOBSIZE(pOut);
53570   break;
53571 }
53572
53573 /* Opcode: BitAnd P1 P2 P3 * *
53574 **
53575 ** Take the bit-wise AND of the values in register P1 and P2 and
53576 ** store the result in register P3.
53577 ** If either input is NULL, the result is NULL.
53578 */
53579 /* Opcode: BitOr P1 P2 P3 * *
53580 **
53581 ** Take the bit-wise OR of the values in register P1 and P2 and
53582 ** store the result in register P3.
53583 ** If either input is NULL, the result is NULL.
53584 */
53585 /* Opcode: ShiftLeft P1 P2 P3 * *
53586 **
53587 ** Shift the integer value in register P2 to the left by the
53588 ** number of bits specified by the integer in regiser P1.
53589 ** Store the result in register P3.
53590 ** If either input is NULL, the result is NULL.
53591 */
53592 /* Opcode: ShiftRight P1 P2 P3 * *
53593 **
53594 ** Shift the integer value in register P2 to the right by the
53595 ** number of bits specified by the integer in register P1.
53596 ** Store the result in register P3.
53597 ** If either input is NULL, the result is NULL.
53598 */
53599 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
53600 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
53601 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
53602 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
53603 #if 0  /* local variables moved into u.ah */
53604   i64 a;
53605   i64 b;
53606 #endif /* local variables moved into u.ah */
53607
53608   pIn1 = &aMem[pOp->p1];
53609   pIn2 = &aMem[pOp->p2];
53610   pOut = &aMem[pOp->p3];
53611   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
53612     sqlite3VdbeMemSetNull(pOut);
53613     break;
53614   }
53615   u.ah.a = sqlite3VdbeIntValue(pIn2);
53616   u.ah.b = sqlite3VdbeIntValue(pIn1);
53617   switch( pOp->opcode ){
53618     case OP_BitAnd:      u.ah.a &= u.ah.b;     break;
53619     case OP_BitOr:       u.ah.a |= u.ah.b;     break;
53620     case OP_ShiftLeft:   u.ah.a <<= u.ah.b;    break;
53621     default:  assert( pOp->opcode==OP_ShiftRight );
53622                          u.ah.a >>= u.ah.b;    break;
53623   }
53624   pOut->u.i = u.ah.a;
53625   MemSetTypeFlag(pOut, MEM_Int);
53626   break;
53627 }
53628
53629 /* Opcode: AddImm  P1 P2 * * *
53630 ** 
53631 ** Add the constant P2 to the value in register P1.
53632 ** The result is always an integer.
53633 **
53634 ** To force any register to be an integer, just add 0.
53635 */
53636 case OP_AddImm: {            /* in1 */
53637   pIn1 = &aMem[pOp->p1];
53638   sqlite3VdbeMemIntegerify(pIn1);
53639   pIn1->u.i += pOp->p2;
53640   break;
53641 }
53642
53643 /* Opcode: MustBeInt P1 P2 * * *
53644 ** 
53645 ** Force the value in register P1 to be an integer.  If the value
53646 ** in P1 is not an integer and cannot be converted into an integer
53647 ** without data loss, then jump immediately to P2, or if P2==0
53648 ** raise an SQLITE_MISMATCH exception.
53649 */
53650 case OP_MustBeInt: {            /* jump, in1 */
53651   pIn1 = &aMem[pOp->p1];
53652   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
53653   if( (pIn1->flags & MEM_Int)==0 ){
53654     if( pOp->p2==0 ){
53655       rc = SQLITE_MISMATCH;
53656       goto abort_due_to_error;
53657     }else{
53658       pc = pOp->p2 - 1;
53659     }
53660   }else{
53661     MemSetTypeFlag(pIn1, MEM_Int);
53662   }
53663   break;
53664 }
53665
53666 /* Opcode: RealAffinity P1 * * * *
53667 **
53668 ** If register P1 holds an integer convert it to a real value.
53669 **
53670 ** This opcode is used when extracting information from a column that
53671 ** has REAL affinity.  Such column values may still be stored as
53672 ** integers, for space efficiency, but after extraction we want them
53673 ** to have only a real value.
53674 */
53675 case OP_RealAffinity: {                  /* in1 */
53676   pIn1 = &aMem[pOp->p1];
53677   if( pIn1->flags & MEM_Int ){
53678     sqlite3VdbeMemRealify(pIn1);
53679   }
53680   break;
53681 }
53682
53683 #ifndef SQLITE_OMIT_CAST
53684 /* Opcode: ToText P1 * * * *
53685 **
53686 ** Force the value in register P1 to be text.
53687 ** If the value is numeric, convert it to a string using the
53688 ** equivalent of printf().  Blob values are unchanged and
53689 ** are afterwards simply interpreted as text.
53690 **
53691 ** A NULL value is not changed by this routine.  It remains NULL.
53692 */
53693 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
53694   pIn1 = &aMem[pOp->p1];
53695   if( pIn1->flags & MEM_Null ) break;
53696   assert( MEM_Str==(MEM_Blob>>3) );
53697   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
53698   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
53699   rc = ExpandBlob(pIn1);
53700   assert( pIn1->flags & MEM_Str || db->mallocFailed );
53701   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
53702   UPDATE_MAX_BLOBSIZE(pIn1);
53703   break;
53704 }
53705
53706 /* Opcode: ToBlob P1 * * * *
53707 **
53708 ** Force the value in register P1 to be a BLOB.
53709 ** If the value is numeric, convert it to a string first.
53710 ** Strings are simply reinterpreted as blobs with no change
53711 ** to the underlying data.
53712 **
53713 ** A NULL value is not changed by this routine.  It remains NULL.
53714 */
53715 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
53716   pIn1 = &aMem[pOp->p1];
53717   if( pIn1->flags & MEM_Null ) break;
53718   if( (pIn1->flags & MEM_Blob)==0 ){
53719     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
53720     assert( pIn1->flags & MEM_Str || db->mallocFailed );
53721     MemSetTypeFlag(pIn1, MEM_Blob);
53722   }else{
53723     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
53724   }
53725   UPDATE_MAX_BLOBSIZE(pIn1);
53726   break;
53727 }
53728
53729 /* Opcode: ToNumeric P1 * * * *
53730 **
53731 ** Force the value in register P1 to be numeric (either an
53732 ** integer or a floating-point number.)
53733 ** If the value is text or blob, try to convert it to an using the
53734 ** equivalent of atoi() or atof() and store 0 if no such conversion 
53735 ** is possible.
53736 **
53737 ** A NULL value is not changed by this routine.  It remains NULL.
53738 */
53739 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
53740   pIn1 = &aMem[pOp->p1];
53741   if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
53742     sqlite3VdbeMemNumerify(pIn1);
53743   }
53744   break;
53745 }
53746 #endif /* SQLITE_OMIT_CAST */
53747
53748 /* Opcode: ToInt P1 * * * *
53749 **
53750 ** Force the value in register P1 be an integer.  If
53751 ** The value is currently a real number, drop its fractional part.
53752 ** If the value is text or blob, try to convert it to an integer using the
53753 ** equivalent of atoi() and store 0 if no such conversion is possible.
53754 **
53755 ** A NULL value is not changed by this routine.  It remains NULL.
53756 */
53757 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
53758   pIn1 = &aMem[pOp->p1];
53759   if( (pIn1->flags & MEM_Null)==0 ){
53760     sqlite3VdbeMemIntegerify(pIn1);
53761   }
53762   break;
53763 }
53764
53765 #ifndef SQLITE_OMIT_CAST
53766 /* Opcode: ToReal P1 * * * *
53767 **
53768 ** Force the value in register P1 to be a floating point number.
53769 ** If The value is currently an integer, convert it.
53770 ** If the value is text or blob, try to convert it to an integer using the
53771 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
53772 **
53773 ** A NULL value is not changed by this routine.  It remains NULL.
53774 */
53775 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
53776   pIn1 = &aMem[pOp->p1];
53777   if( (pIn1->flags & MEM_Null)==0 ){
53778     sqlite3VdbeMemRealify(pIn1);
53779   }
53780   break;
53781 }
53782 #endif /* SQLITE_OMIT_CAST */
53783
53784 /* Opcode: Lt P1 P2 P3 P4 P5
53785 **
53786 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
53787 ** jump to address P2.  
53788 **
53789 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
53790 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
53791 ** bit is clear then fall thru if either operand is NULL.
53792 **
53793 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
53794 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
53795 ** to coerce both inputs according to this affinity before the
53796 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
53797 ** affinity is used. Note that the affinity conversions are stored
53798 ** back into the input registers P1 and P3.  So this opcode can cause
53799 ** persistent changes to registers P1 and P3.
53800 **
53801 ** Once any conversions have taken place, and neither value is NULL, 
53802 ** the values are compared. If both values are blobs then memcmp() is
53803 ** used to determine the results of the comparison.  If both values
53804 ** are text, then the appropriate collating function specified in
53805 ** P4 is  used to do the comparison.  If P4 is not specified then
53806 ** memcmp() is used to compare text string.  If both values are
53807 ** numeric, then a numeric comparison is used. If the two values
53808 ** are of different types, then numbers are considered less than
53809 ** strings and strings are considered less than blobs.
53810 **
53811 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
53812 ** store a boolean result (either 0, or 1, or NULL) in register P2.
53813 */
53814 /* Opcode: Ne P1 P2 P3 P4 P5
53815 **
53816 ** This works just like the Lt opcode except that the jump is taken if
53817 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
53818 ** additional information.
53819 **
53820 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
53821 ** true or false and is never NULL.  If both operands are NULL then the result
53822 ** of comparison is false.  If either operand is NULL then the result is true.
53823 ** If neither operand is NULL the the result is the same as it would be if
53824 ** the SQLITE_NULLEQ flag were omitted from P5.
53825 */
53826 /* Opcode: Eq P1 P2 P3 P4 P5
53827 **
53828 ** This works just like the Lt opcode except that the jump is taken if
53829 ** the operands in registers P1 and P3 are equal.
53830 ** See the Lt opcode for additional information.
53831 **
53832 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
53833 ** true or false and is never NULL.  If both operands are NULL then the result
53834 ** of comparison is true.  If either operand is NULL then the result is false.
53835 ** If neither operand is NULL the the result is the same as it would be if
53836 ** the SQLITE_NULLEQ flag were omitted from P5.
53837 */
53838 /* Opcode: Le P1 P2 P3 P4 P5
53839 **
53840 ** This works just like the Lt opcode except that the jump is taken if
53841 ** the content of register P3 is less than or equal to the content of
53842 ** register P1.  See the Lt opcode for additional information.
53843 */
53844 /* Opcode: Gt P1 P2 P3 P4 P5
53845 **
53846 ** This works just like the Lt opcode except that the jump is taken if
53847 ** the content of register P3 is greater than the content of
53848 ** register P1.  See the Lt opcode for additional information.
53849 */
53850 /* Opcode: Ge P1 P2 P3 P4 P5
53851 **
53852 ** This works just like the Lt opcode except that the jump is taken if
53853 ** the content of register P3 is greater than or equal to the content of
53854 ** register P1.  See the Lt opcode for additional information.
53855 */
53856 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
53857 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
53858 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
53859 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
53860 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
53861 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
53862 #if 0  /* local variables moved into u.ai */
53863   int res;            /* Result of the comparison of pIn1 against pIn3 */
53864   char affinity;      /* Affinity to use for comparison */
53865 #endif /* local variables moved into u.ai */
53866
53867   pIn1 = &aMem[pOp->p1];
53868   pIn3 = &aMem[pOp->p3];
53869   if( (pIn1->flags | pIn3->flags)&MEM_Null ){
53870     /* One or both operands are NULL */
53871     if( pOp->p5 & SQLITE_NULLEQ ){
53872       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
53873       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
53874       ** or not both operands are null.
53875       */
53876       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
53877       u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
53878     }else{
53879       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
53880       ** then the result is always NULL.
53881       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
53882       */
53883       if( pOp->p5 & SQLITE_STOREP2 ){
53884         pOut = &aMem[pOp->p2];
53885         MemSetTypeFlag(pOut, MEM_Null);
53886         REGISTER_TRACE(pOp->p2, pOut);
53887       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
53888         pc = pOp->p2-1;
53889       }
53890       break;
53891     }
53892   }else{
53893     /* Neither operand is NULL.  Do a comparison. */
53894     u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
53895     if( u.ai.affinity ){
53896       applyAffinity(pIn1, u.ai.affinity, encoding);
53897       applyAffinity(pIn3, u.ai.affinity, encoding);
53898       if( db->mallocFailed ) goto no_mem;
53899     }
53900
53901     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
53902     ExpandBlob(pIn1);
53903     ExpandBlob(pIn3);
53904     u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
53905   }
53906   switch( pOp->opcode ){
53907     case OP_Eq:    u.ai.res = u.ai.res==0;     break;
53908     case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
53909     case OP_Lt:    u.ai.res = u.ai.res<0;      break;
53910     case OP_Le:    u.ai.res = u.ai.res<=0;     break;
53911     case OP_Gt:    u.ai.res = u.ai.res>0;      break;
53912     default:       u.ai.res = u.ai.res>=0;     break;
53913   }
53914
53915   if( pOp->p5 & SQLITE_STOREP2 ){
53916     pOut = &aMem[pOp->p2];
53917     MemSetTypeFlag(pOut, MEM_Int);
53918     pOut->u.i = u.ai.res;
53919     REGISTER_TRACE(pOp->p2, pOut);
53920   }else if( u.ai.res ){
53921     pc = pOp->p2-1;
53922   }
53923   break;
53924 }
53925
53926 /* Opcode: Permutation * * * P4 *
53927 **
53928 ** Set the permutation used by the OP_Compare operator to be the array
53929 ** of integers in P4.
53930 **
53931 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
53932 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
53933 ** immediately prior to the OP_Compare.
53934 */
53935 case OP_Permutation: {
53936   assert( pOp->p4type==P4_INTARRAY );
53937   assert( pOp->p4.ai );
53938   aPermute = pOp->p4.ai;
53939   break;
53940 }
53941
53942 /* Opcode: Compare P1 P2 P3 P4 *
53943 **
53944 ** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
53945 ** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
53946 ** the comparison for use by the next OP_Jump instruct.
53947 **
53948 ** P4 is a KeyInfo structure that defines collating sequences and sort
53949 ** orders for the comparison.  The permutation applies to registers
53950 ** only.  The KeyInfo elements are used sequentially.
53951 **
53952 ** The comparison is a sort comparison, so NULLs compare equal,
53953 ** NULLs are less than numbers, numbers are less than strings,
53954 ** and strings are less than blobs.
53955 */
53956 case OP_Compare: {
53957 #if 0  /* local variables moved into u.aj */
53958   int n;
53959   int i;
53960   int p1;
53961   int p2;
53962   const KeyInfo *pKeyInfo;
53963   int idx;
53964   CollSeq *pColl;    /* Collating sequence to use on this term */
53965   int bRev;          /* True for DESCENDING sort order */
53966 #endif /* local variables moved into u.aj */
53967
53968   u.aj.n = pOp->p3;
53969   u.aj.pKeyInfo = pOp->p4.pKeyInfo;
53970   assert( u.aj.n>0 );
53971   assert( u.aj.pKeyInfo!=0 );
53972   u.aj.p1 = pOp->p1;
53973   u.aj.p2 = pOp->p2;
53974 #if SQLITE_DEBUG
53975   if( aPermute ){
53976     int k, mx = 0;
53977     for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
53978     assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
53979     assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
53980   }else{
53981     assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
53982     assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
53983   }
53984 #endif /* SQLITE_DEBUG */
53985   for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
53986     u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
53987     REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
53988     REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
53989     assert( u.aj.i<u.aj.pKeyInfo->nField );
53990     u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
53991     u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
53992     iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
53993     if( iCompare ){
53994       if( u.aj.bRev ) iCompare = -iCompare;
53995       break;
53996     }
53997   }
53998   aPermute = 0;
53999   break;
54000 }
54001
54002 /* Opcode: Jump P1 P2 P3 * *
54003 **
54004 ** Jump to the instruction at address P1, P2, or P3 depending on whether
54005 ** in the most recent OP_Compare instruction the P1 vector was less than
54006 ** equal to, or greater than the P2 vector, respectively.
54007 */
54008 case OP_Jump: {             /* jump */
54009   if( iCompare<0 ){
54010     pc = pOp->p1 - 1;
54011   }else if( iCompare==0 ){
54012     pc = pOp->p2 - 1;
54013   }else{
54014     pc = pOp->p3 - 1;
54015   }
54016   break;
54017 }
54018
54019 /* Opcode: And P1 P2 P3 * *
54020 **
54021 ** Take the logical AND of the values in registers P1 and P2 and
54022 ** write the result into register P3.
54023 **
54024 ** If either P1 or P2 is 0 (false) then the result is 0 even if
54025 ** the other input is NULL.  A NULL and true or two NULLs give
54026 ** a NULL output.
54027 */
54028 /* Opcode: Or P1 P2 P3 * *
54029 **
54030 ** Take the logical OR of the values in register P1 and P2 and
54031 ** store the answer in register P3.
54032 **
54033 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
54034 ** even if the other input is NULL.  A NULL and false or two NULLs
54035 ** give a NULL output.
54036 */
54037 case OP_And:              /* same as TK_AND, in1, in2, out3 */
54038 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
54039 #if 0  /* local variables moved into u.ak */
54040   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
54041   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
54042 #endif /* local variables moved into u.ak */
54043
54044   pIn1 = &aMem[pOp->p1];
54045   if( pIn1->flags & MEM_Null ){
54046     u.ak.v1 = 2;
54047   }else{
54048     u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
54049   }
54050   pIn2 = &aMem[pOp->p2];
54051   if( pIn2->flags & MEM_Null ){
54052     u.ak.v2 = 2;
54053   }else{
54054     u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
54055   }
54056   if( pOp->opcode==OP_And ){
54057     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
54058     u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
54059   }else{
54060     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
54061     u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
54062   }
54063   pOut = &aMem[pOp->p3];
54064   if( u.ak.v1==2 ){
54065     MemSetTypeFlag(pOut, MEM_Null);
54066   }else{
54067     pOut->u.i = u.ak.v1;
54068     MemSetTypeFlag(pOut, MEM_Int);
54069   }
54070   break;
54071 }
54072
54073 /* Opcode: Not P1 P2 * * *
54074 **
54075 ** Interpret the value in register P1 as a boolean value.  Store the
54076 ** boolean complement in register P2.  If the value in register P1 is 
54077 ** NULL, then a NULL is stored in P2.
54078 */
54079 case OP_Not: {                /* same as TK_NOT, in1, out2 */
54080   pIn1 = &aMem[pOp->p1];
54081   pOut = &aMem[pOp->p2];
54082   if( pIn1->flags & MEM_Null ){
54083     sqlite3VdbeMemSetNull(pOut);
54084   }else{
54085     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
54086   }
54087   break;
54088 }
54089
54090 /* Opcode: BitNot P1 P2 * * *
54091 **
54092 ** Interpret the content of register P1 as an integer.  Store the
54093 ** ones-complement of the P1 value into register P2.  If P1 holds
54094 ** a NULL then store a NULL in P2.
54095 */
54096 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
54097   pIn1 = &aMem[pOp->p1];
54098   pOut = &aMem[pOp->p2];
54099   if( pIn1->flags & MEM_Null ){
54100     sqlite3VdbeMemSetNull(pOut);
54101   }else{
54102     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
54103   }
54104   break;
54105 }
54106
54107 /* Opcode: If P1 P2 P3 * *
54108 **
54109 ** Jump to P2 if the value in register P1 is true.  The value is
54110 ** is considered true if it is numeric and non-zero.  If the value
54111 ** in P1 is NULL then take the jump if P3 is true.
54112 */
54113 /* Opcode: IfNot P1 P2 P3 * *
54114 **
54115 ** Jump to P2 if the value in register P1 is False.  The value is
54116 ** is considered true if it has a numeric value of zero.  If the value
54117 ** in P1 is NULL then take the jump if P3 is true.
54118 */
54119 case OP_If:                 /* jump, in1 */
54120 case OP_IfNot: {            /* jump, in1 */
54121 #if 0  /* local variables moved into u.al */
54122   int c;
54123 #endif /* local variables moved into u.al */
54124   pIn1 = &aMem[pOp->p1];
54125   if( pIn1->flags & MEM_Null ){
54126     u.al.c = pOp->p3;
54127   }else{
54128 #ifdef SQLITE_OMIT_FLOATING_POINT
54129     u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
54130 #else
54131     u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
54132 #endif
54133     if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
54134   }
54135   if( u.al.c ){
54136     pc = pOp->p2-1;
54137   }
54138   break;
54139 }
54140
54141 /* Opcode: IsNull P1 P2 * * *
54142 **
54143 ** Jump to P2 if the value in register P1 is NULL.
54144 */
54145 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
54146   pIn1 = &aMem[pOp->p1];
54147   if( (pIn1->flags & MEM_Null)!=0 ){
54148     pc = pOp->p2 - 1;
54149   }
54150   break;
54151 }
54152
54153 /* Opcode: NotNull P1 P2 * * *
54154 **
54155 ** Jump to P2 if the value in register P1 is not NULL.  
54156 */
54157 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
54158   pIn1 = &aMem[pOp->p1];
54159   if( (pIn1->flags & MEM_Null)==0 ){
54160     pc = pOp->p2 - 1;
54161   }
54162   break;
54163 }
54164
54165 /* Opcode: Column P1 P2 P3 P4 P5
54166 **
54167 ** Interpret the data that cursor P1 points to as a structure built using
54168 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
54169 ** information about the format of the data.)  Extract the P2-th column
54170 ** from this record.  If there are less that (P2+1) 
54171 ** values in the record, extract a NULL.
54172 **
54173 ** The value extracted is stored in register P3.
54174 **
54175 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
54176 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
54177 ** the result.
54178 **
54179 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
54180 ** then the cache of the cursor is reset prior to extracting the column.
54181 ** The first OP_Column against a pseudo-table after the value of the content
54182 ** register has changed should have this bit set.
54183 */
54184 case OP_Column: {
54185 #if 0  /* local variables moved into u.am */
54186   u32 payloadSize;   /* Number of bytes in the record */
54187   i64 payloadSize64; /* Number of bytes in the record */
54188   int p1;            /* P1 value of the opcode */
54189   int p2;            /* column number to retrieve */
54190   VdbeCursor *pC;    /* The VDBE cursor */
54191   char *zRec;        /* Pointer to complete record-data */
54192   BtCursor *pCrsr;   /* The BTree cursor */
54193   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
54194   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
54195   int nField;        /* number of fields in the record */
54196   int len;           /* The length of the serialized data for the column */
54197   int i;             /* Loop counter */
54198   char *zData;       /* Part of the record being decoded */
54199   Mem *pDest;        /* Where to write the extracted value */
54200   Mem sMem;          /* For storing the record being decoded */
54201   u8 *zIdx;          /* Index into header */
54202   u8 *zEndHdr;       /* Pointer to first byte after the header */
54203   u32 offset;        /* Offset into the data */
54204   u64 offset64;      /* 64-bit offset.  64 bits needed to catch overflow */
54205   int szHdr;         /* Size of the header size field at start of record */
54206   int avail;         /* Number of bytes of available data */
54207   Mem *pReg;         /* PseudoTable input register */
54208 #endif /* local variables moved into u.am */
54209
54210
54211   u.am.p1 = pOp->p1;
54212   u.am.p2 = pOp->p2;
54213   u.am.pC = 0;
54214   memset(&u.am.sMem, 0, sizeof(u.am.sMem));
54215   assert( u.am.p1<p->nCursor );
54216   assert( pOp->p3>0 && pOp->p3<=p->nMem );
54217   u.am.pDest = &aMem[pOp->p3];
54218   MemSetTypeFlag(u.am.pDest, MEM_Null);
54219   u.am.zRec = 0;
54220
54221   /* This block sets the variable u.am.payloadSize to be the total number of
54222   ** bytes in the record.
54223   **
54224   ** u.am.zRec is set to be the complete text of the record if it is available.
54225   ** The complete record text is always available for pseudo-tables
54226   ** If the record is stored in a cursor, the complete record text
54227   ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
54228   ** If the data is unavailable,  u.am.zRec is set to NULL.
54229   **
54230   ** We also compute the number of columns in the record.  For cursors,
54231   ** the number of columns is stored in the VdbeCursor.nField element.
54232   */
54233   u.am.pC = p->apCsr[u.am.p1];
54234   assert( u.am.pC!=0 );
54235 #ifndef SQLITE_OMIT_VIRTUALTABLE
54236   assert( u.am.pC->pVtabCursor==0 );
54237 #endif
54238   u.am.pCrsr = u.am.pC->pCursor;
54239   if( u.am.pCrsr!=0 ){
54240     /* The record is stored in a B-Tree */
54241     rc = sqlite3VdbeCursorMoveto(u.am.pC);
54242     if( rc ) goto abort_due_to_error;
54243     if( u.am.pC->nullRow ){
54244       u.am.payloadSize = 0;
54245     }else if( u.am.pC->cacheStatus==p->cacheCtr ){
54246       u.am.payloadSize = u.am.pC->payloadSize;
54247       u.am.zRec = (char*)u.am.pC->aRow;
54248     }else if( u.am.pC->isIndex ){
54249       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
54250       rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
54251       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
54252       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
54253       ** payload size, so it is impossible for u.am.payloadSize64 to be
54254       ** larger than 32 bits. */
54255       assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
54256       u.am.payloadSize = (u32)u.am.payloadSize64;
54257     }else{
54258       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
54259       rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
54260       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
54261     }
54262   }else if( u.am.pC->pseudoTableReg>0 ){
54263     u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
54264     assert( u.am.pReg->flags & MEM_Blob );
54265     u.am.payloadSize = u.am.pReg->n;
54266     u.am.zRec = u.am.pReg->z;
54267     u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
54268     assert( u.am.payloadSize==0 || u.am.zRec!=0 );
54269   }else{
54270     /* Consider the row to be NULL */
54271     u.am.payloadSize = 0;
54272   }
54273
54274   /* If u.am.payloadSize is 0, then just store a NULL */
54275   if( u.am.payloadSize==0 ){
54276     assert( u.am.pDest->flags&MEM_Null );
54277     goto op_column_out;
54278   }
54279   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
54280   if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
54281     goto too_big;
54282   }
54283
54284   u.am.nField = u.am.pC->nField;
54285   assert( u.am.p2<u.am.nField );
54286
54287   /* Read and parse the table header.  Store the results of the parse
54288   ** into the record header cache fields of the cursor.
54289   */
54290   u.am.aType = u.am.pC->aType;
54291   if( u.am.pC->cacheStatus==p->cacheCtr ){
54292     u.am.aOffset = u.am.pC->aOffset;
54293   }else{
54294     assert(u.am.aType);
54295     u.am.avail = 0;
54296     u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
54297     u.am.pC->payloadSize = u.am.payloadSize;
54298     u.am.pC->cacheStatus = p->cacheCtr;
54299
54300     /* Figure out how many bytes are in the header */
54301     if( u.am.zRec ){
54302       u.am.zData = u.am.zRec;
54303     }else{
54304       if( u.am.pC->isIndex ){
54305         u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
54306       }else{
54307         u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
54308       }
54309       /* If KeyFetch()/DataFetch() managed to get the entire payload,
54310       ** save the payload in the u.am.pC->aRow cache.  That will save us from
54311       ** having to make additional calls to fetch the content portion of
54312       ** the record.
54313       */
54314       assert( u.am.avail>=0 );
54315       if( u.am.payloadSize <= (u32)u.am.avail ){
54316         u.am.zRec = u.am.zData;
54317         u.am.pC->aRow = (u8*)u.am.zData;
54318       }else{
54319         u.am.pC->aRow = 0;
54320       }
54321     }
54322     /* The following assert is true in all cases accept when
54323     ** the database file has been corrupted externally.
54324     **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
54325     u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
54326
54327     /* Make sure a corrupt database has not given us an oversize header.
54328     ** Do this now to avoid an oversize memory allocation.
54329     **
54330     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
54331     ** types use so much data space that there can only be 4096 and 32 of
54332     ** them, respectively.  So the maximum header length results from a
54333     ** 3-byte type for each of the maximum of 32768 columns plus three
54334     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
54335     */
54336     if( u.am.offset > 98307 ){
54337       rc = SQLITE_CORRUPT_BKPT;
54338       goto op_column_out;
54339     }
54340
54341     /* Compute in u.am.len the number of bytes of data we need to read in order
54342     ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
54343     ** u.am.nField might be significantly less than the true number of columns
54344     ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
54345     ** We want to minimize u.am.len in order to limit the size of the memory
54346     ** allocation, especially if a corrupt database file has caused u.am.offset
54347     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
54348     ** still exceed Robson memory allocation limits on some configurations.
54349     ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
54350     ** will likely be much smaller since u.am.nField will likely be less than
54351     ** 20 or so.  This insures that Robson memory allocation limits are
54352     ** not exceeded even for corrupt database files.
54353     */
54354     u.am.len = u.am.nField*5 + 3;
54355     if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
54356
54357     /* The KeyFetch() or DataFetch() above are fast and will get the entire
54358     ** record header in most cases.  But they will fail to get the complete
54359     ** record header if the record header does not fit on a single page
54360     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
54361     ** acquire the complete header text.
54362     */
54363     if( !u.am.zRec && u.am.avail<u.am.len ){
54364       u.am.sMem.flags = 0;
54365       u.am.sMem.db = 0;
54366       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
54367       if( rc!=SQLITE_OK ){
54368         goto op_column_out;
54369       }
54370       u.am.zData = u.am.sMem.z;
54371     }
54372     u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
54373     u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
54374
54375     /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
54376     ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
54377     ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
54378     ** of the record to the start of the data for the u.am.i-th column
54379     */
54380     u.am.offset64 = u.am.offset;
54381     for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
54382       if( u.am.zIdx<u.am.zEndHdr ){
54383         u.am.aOffset[u.am.i] = (u32)u.am.offset64;
54384         u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
54385         u.am.offset64 += sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
54386       }else{
54387         /* If u.am.i is less that u.am.nField, then there are less fields in this
54388         ** record than SetNumColumns indicated there are columns in the
54389         ** table. Set the u.am.offset for any extra columns not present in
54390         ** the record to 0. This tells code below to store a NULL
54391         ** instead of deserializing a value from the record.
54392         */
54393         u.am.aOffset[u.am.i] = 0;
54394       }
54395     }
54396     sqlite3VdbeMemRelease(&u.am.sMem);
54397     u.am.sMem.flags = MEM_Null;
54398
54399     /* If we have read more header data than was contained in the header,
54400     ** or if the end of the last field appears to be past the end of the
54401     ** record, or if the end of the last field appears to be before the end
54402     ** of the record (when all fields present), then we must be dealing
54403     ** with a corrupt database.
54404     */
54405     if( (u.am.zIdx > u.am.zEndHdr)|| (u.am.offset64 > u.am.payloadSize)
54406      || (u.am.zIdx==u.am.zEndHdr && u.am.offset64!=(u64)u.am.payloadSize) ){
54407       rc = SQLITE_CORRUPT_BKPT;
54408       goto op_column_out;
54409     }
54410   }
54411
54412   /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
54413   ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
54414   ** then there are not enough fields in the record to satisfy the
54415   ** request.  In this case, set the value NULL or to P4 if P4 is
54416   ** a pointer to a Mem object.
54417   */
54418   if( u.am.aOffset[u.am.p2] ){
54419     assert( rc==SQLITE_OK );
54420     if( u.am.zRec ){
54421       sqlite3VdbeMemReleaseExternal(u.am.pDest);
54422       sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
54423     }else{
54424       u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
54425       sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
54426       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
54427       if( rc!=SQLITE_OK ){
54428         goto op_column_out;
54429       }
54430       u.am.zData = u.am.sMem.z;
54431       sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
54432     }
54433     u.am.pDest->enc = encoding;
54434   }else{
54435     if( pOp->p4type==P4_MEM ){
54436       sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
54437     }else{
54438       assert( u.am.pDest->flags&MEM_Null );
54439     }
54440   }
54441
54442   /* If we dynamically allocated space to hold the data (in the
54443   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
54444   ** dynamically allocated space over to the u.am.pDest structure.
54445   ** This prevents a memory copy.
54446   */
54447   if( u.am.sMem.zMalloc ){
54448     assert( u.am.sMem.z==u.am.sMem.zMalloc );
54449     assert( !(u.am.pDest->flags & MEM_Dyn) );
54450     assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
54451     u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
54452     u.am.pDest->flags |= MEM_Term;
54453     u.am.pDest->z = u.am.sMem.z;
54454     u.am.pDest->zMalloc = u.am.sMem.zMalloc;
54455   }
54456
54457   rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
54458
54459 op_column_out:
54460   UPDATE_MAX_BLOBSIZE(u.am.pDest);
54461   REGISTER_TRACE(pOp->p3, u.am.pDest);
54462   break;
54463 }
54464
54465 /* Opcode: Affinity P1 P2 * P4 *
54466 **
54467 ** Apply affinities to a range of P2 registers starting with P1.
54468 **
54469 ** P4 is a string that is P2 characters long. The nth character of the
54470 ** string indicates the column affinity that should be used for the nth
54471 ** memory cell in the range.
54472 */
54473 case OP_Affinity: {
54474 #if 0  /* local variables moved into u.an */
54475   const char *zAffinity;   /* The affinity to be applied */
54476   char cAff;               /* A single character of affinity */
54477 #endif /* local variables moved into u.an */
54478
54479   u.an.zAffinity = pOp->p4.z;
54480   assert( u.an.zAffinity!=0 );
54481   assert( u.an.zAffinity[pOp->p2]==0 );
54482   pIn1 = &aMem[pOp->p1];
54483   while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
54484     assert( pIn1 <= &p->aMem[p->nMem] );
54485     ExpandBlob(pIn1);
54486     applyAffinity(pIn1, u.an.cAff, encoding);
54487     pIn1++;
54488   }
54489   break;
54490 }
54491
54492 /* Opcode: MakeRecord P1 P2 P3 P4 *
54493 **
54494 ** Convert P2 registers beginning with P1 into a single entry
54495 ** suitable for use as a data record in a database table or as a key
54496 ** in an index.  The details of the format are irrelevant as long as
54497 ** the OP_Column opcode can decode the record later.
54498 ** Refer to source code comments for the details of the record
54499 ** format.
54500 **
54501 ** P4 may be a string that is P2 characters long.  The nth character of the
54502 ** string indicates the column affinity that should be used for the nth
54503 ** field of the index key.
54504 **
54505 ** The mapping from character to affinity is given by the SQLITE_AFF_
54506 ** macros defined in sqliteInt.h.
54507 **
54508 ** If P4 is NULL then all index fields have the affinity NONE.
54509 */
54510 case OP_MakeRecord: {
54511 #if 0  /* local variables moved into u.ao */
54512   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
54513   Mem *pRec;             /* The new record */
54514   u64 nData;             /* Number of bytes of data space */
54515   int nHdr;              /* Number of bytes of header space */
54516   i64 nByte;             /* Data space required for this record */
54517   int nZero;             /* Number of zero bytes at the end of the record */
54518   int nVarint;           /* Number of bytes in a varint */
54519   u32 serial_type;       /* Type field */
54520   Mem *pData0;           /* First field to be combined into the record */
54521   Mem *pLast;            /* Last field of the record */
54522   int nField;            /* Number of fields in the record */
54523   char *zAffinity;       /* The affinity string for the record */
54524   int file_format;       /* File format to use for encoding */
54525   int i;                 /* Space used in zNewRecord[] */
54526   int len;               /* Length of a field */
54527 #endif /* local variables moved into u.ao */
54528
54529   /* Assuming the record contains N fields, the record format looks
54530   ** like this:
54531   **
54532   ** ------------------------------------------------------------------------
54533   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
54534   ** ------------------------------------------------------------------------
54535   **
54536   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
54537   ** and so froth.
54538   **
54539   ** Each type field is a varint representing the serial type of the
54540   ** corresponding data element (see sqlite3VdbeSerialType()). The
54541   ** hdr-size field is also a varint which is the offset from the beginning
54542   ** of the record to data0.
54543   */
54544   u.ao.nData = 0;         /* Number of bytes of data space */
54545   u.ao.nHdr = 0;          /* Number of bytes of header space */
54546   u.ao.nByte = 0;         /* Data space required for this record */
54547   u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
54548   u.ao.nField = pOp->p1;
54549   u.ao.zAffinity = pOp->p4.z;
54550   assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
54551   u.ao.pData0 = &aMem[u.ao.nField];
54552   u.ao.nField = pOp->p2;
54553   u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
54554   u.ao.file_format = p->minWriteFileFormat;
54555
54556   /* Loop through the elements that will make up the record to figure
54557   ** out how much space is required for the new record.
54558   */
54559   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
54560     if( u.ao.zAffinity ){
54561       applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
54562     }
54563     if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
54564       sqlite3VdbeMemExpandBlob(u.ao.pRec);
54565     }
54566     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
54567     u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
54568     u.ao.nData += u.ao.len;
54569     u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
54570     if( u.ao.pRec->flags & MEM_Zero ){
54571       /* Only pure zero-filled BLOBs can be input to this Opcode.
54572       ** We do not allow blobs with a prefix and a zero-filled tail. */
54573       u.ao.nZero += u.ao.pRec->u.nZero;
54574     }else if( u.ao.len ){
54575       u.ao.nZero = 0;
54576     }
54577   }
54578
54579   /* Add the initial header varint and total the size */
54580   u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
54581   if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
54582     u.ao.nHdr++;
54583   }
54584   u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
54585   if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
54586     goto too_big;
54587   }
54588
54589   /* Make sure the output register has a buffer large enough to store
54590   ** the new record. The output register (pOp->p3) is not allowed to
54591   ** be one of the input registers (because the following call to
54592   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
54593   */
54594   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
54595   pOut = &aMem[pOp->p3];
54596   if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
54597     goto no_mem;
54598   }
54599   u.ao.zNewRecord = (u8 *)pOut->z;
54600
54601   /* Write the record */
54602   u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
54603   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
54604     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
54605     u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
54606   }
54607   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
54608     u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
54609   }
54610   assert( u.ao.i==u.ao.nByte );
54611
54612   assert( pOp->p3>0 && pOp->p3<=p->nMem );
54613   pOut->n = (int)u.ao.nByte;
54614   pOut->flags = MEM_Blob | MEM_Dyn;
54615   pOut->xDel = 0;
54616   if( u.ao.nZero ){
54617     pOut->u.nZero = u.ao.nZero;
54618     pOut->flags |= MEM_Zero;
54619   }
54620   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
54621   REGISTER_TRACE(pOp->p3, pOut);
54622   UPDATE_MAX_BLOBSIZE(pOut);
54623   break;
54624 }
54625
54626 /* Opcode: Count P1 P2 * * *
54627 **
54628 ** Store the number of entries (an integer value) in the table or index 
54629 ** opened by cursor P1 in register P2
54630 */
54631 #ifndef SQLITE_OMIT_BTREECOUNT
54632 case OP_Count: {         /* out2-prerelease */
54633 #if 0  /* local variables moved into u.ap */
54634   i64 nEntry;
54635   BtCursor *pCrsr;
54636 #endif /* local variables moved into u.ap */
54637
54638   u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
54639   if( u.ap.pCrsr ){
54640     rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
54641   }else{
54642     u.ap.nEntry = 0;
54643   }
54644   pOut->u.i = u.ap.nEntry;
54645   break;
54646 }
54647 #endif
54648
54649 /* Opcode: Savepoint P1 * * P4 *
54650 **
54651 ** Open, release or rollback the savepoint named by parameter P4, depending
54652 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
54653 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
54654 */
54655 case OP_Savepoint: {
54656 #if 0  /* local variables moved into u.aq */
54657   int p1;                         /* Value of P1 operand */
54658   char *zName;                    /* Name of savepoint */
54659   int nName;
54660   Savepoint *pNew;
54661   Savepoint *pSavepoint;
54662   Savepoint *pTmp;
54663   int iSavepoint;
54664   int ii;
54665 #endif /* local variables moved into u.aq */
54666
54667   u.aq.p1 = pOp->p1;
54668   u.aq.zName = pOp->p4.z;
54669
54670   /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
54671   ** transaction, then there cannot be any savepoints.
54672   */
54673   assert( db->pSavepoint==0 || db->autoCommit==0 );
54674   assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
54675   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
54676   assert( checkSavepointCount(db) );
54677
54678   if( u.aq.p1==SAVEPOINT_BEGIN ){
54679     if( db->writeVdbeCnt>0 ){
54680       /* A new savepoint cannot be created if there are active write
54681       ** statements (i.e. open read/write incremental blob handles).
54682       */
54683       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
54684         "SQL statements in progress");
54685       rc = SQLITE_BUSY;
54686     }else{
54687       u.aq.nName = sqlite3Strlen30(u.aq.zName);
54688
54689       /* Create a new savepoint structure. */
54690       u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
54691       if( u.aq.pNew ){
54692         u.aq.pNew->zName = (char *)&u.aq.pNew[1];
54693         memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
54694
54695         /* If there is no open transaction, then mark this as a special
54696         ** "transaction savepoint". */
54697         if( db->autoCommit ){
54698           db->autoCommit = 0;
54699           db->isTransactionSavepoint = 1;
54700         }else{
54701           db->nSavepoint++;
54702         }
54703
54704         /* Link the new savepoint into the database handle's list. */
54705         u.aq.pNew->pNext = db->pSavepoint;
54706         db->pSavepoint = u.aq.pNew;
54707         u.aq.pNew->nDeferredCons = db->nDeferredCons;
54708       }
54709     }
54710   }else{
54711     u.aq.iSavepoint = 0;
54712
54713     /* Find the named savepoint. If there is no such savepoint, then an
54714     ** an error is returned to the user.  */
54715     for(
54716       u.aq.pSavepoint = db->pSavepoint;
54717       u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
54718       u.aq.pSavepoint = u.aq.pSavepoint->pNext
54719     ){
54720       u.aq.iSavepoint++;
54721     }
54722     if( !u.aq.pSavepoint ){
54723       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
54724       rc = SQLITE_ERROR;
54725     }else if(
54726         db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
54727     ){
54728       /* It is not possible to release (commit) a savepoint if there are
54729       ** active write statements. It is not possible to rollback a savepoint
54730       ** if there are any active statements at all.
54731       */
54732       sqlite3SetString(&p->zErrMsg, db,
54733         "cannot %s savepoint - SQL statements in progress",
54734         (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
54735       );
54736       rc = SQLITE_BUSY;
54737     }else{
54738
54739       /* Determine whether or not this is a transaction savepoint. If so,
54740       ** and this is a RELEASE command, then the current transaction
54741       ** is committed.
54742       */
54743       int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
54744       if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
54745         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
54746           goto vdbe_return;
54747         }
54748         db->autoCommit = 1;
54749         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
54750           p->pc = pc;
54751           db->autoCommit = 0;
54752           p->rc = rc = SQLITE_BUSY;
54753           goto vdbe_return;
54754         }
54755         db->isTransactionSavepoint = 0;
54756         rc = p->rc;
54757       }else{
54758         u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
54759         for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
54760           rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
54761           if( rc!=SQLITE_OK ){
54762             goto abort_due_to_error;
54763           }
54764         }
54765         if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
54766           sqlite3ExpirePreparedStatements(db);
54767           sqlite3ResetInternalSchema(db, 0);
54768         }
54769       }
54770
54771       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
54772       ** savepoints nested inside of the savepoint being operated on. */
54773       while( db->pSavepoint!=u.aq.pSavepoint ){
54774         u.aq.pTmp = db->pSavepoint;
54775         db->pSavepoint = u.aq.pTmp->pNext;
54776         sqlite3DbFree(db, u.aq.pTmp);
54777         db->nSavepoint--;
54778       }
54779
54780       /* If it is a RELEASE, then destroy the savepoint being operated on
54781       ** too. If it is a ROLLBACK TO, then set the number of deferred
54782       ** constraint violations present in the database to the value stored
54783       ** when the savepoint was created.  */
54784       if( u.aq.p1==SAVEPOINT_RELEASE ){
54785         assert( u.aq.pSavepoint==db->pSavepoint );
54786         db->pSavepoint = u.aq.pSavepoint->pNext;
54787         sqlite3DbFree(db, u.aq.pSavepoint);
54788         if( !isTransaction ){
54789           db->nSavepoint--;
54790         }
54791       }else{
54792         db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
54793       }
54794     }
54795   }
54796
54797   break;
54798 }
54799
54800 /* Opcode: AutoCommit P1 P2 * * *
54801 **
54802 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
54803 ** back any currently active btree transactions. If there are any active
54804 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
54805 ** there are active writing VMs or active VMs that use shared cache.
54806 **
54807 ** This instruction causes the VM to halt.
54808 */
54809 case OP_AutoCommit: {
54810 #if 0  /* local variables moved into u.ar */
54811   int desiredAutoCommit;
54812   int iRollback;
54813   int turnOnAC;
54814 #endif /* local variables moved into u.ar */
54815
54816   u.ar.desiredAutoCommit = pOp->p1;
54817   u.ar.iRollback = pOp->p2;
54818   u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
54819   assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
54820   assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
54821   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
54822
54823   if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
54824     /* If this instruction implements a ROLLBACK and other VMs are
54825     ** still running, and a transaction is active, return an error indicating
54826     ** that the other VMs must complete first.
54827     */
54828     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
54829         "SQL statements in progress");
54830     rc = SQLITE_BUSY;
54831   }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
54832     /* If this instruction implements a COMMIT and other VMs are writing
54833     ** return an error indicating that the other VMs must complete first.
54834     */
54835     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
54836         "SQL statements in progress");
54837     rc = SQLITE_BUSY;
54838   }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
54839     if( u.ar.iRollback ){
54840       assert( u.ar.desiredAutoCommit==1 );
54841       sqlite3RollbackAll(db);
54842       db->autoCommit = 1;
54843     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
54844       goto vdbe_return;
54845     }else{
54846       db->autoCommit = (u8)u.ar.desiredAutoCommit;
54847       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
54848         p->pc = pc;
54849         db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
54850         p->rc = rc = SQLITE_BUSY;
54851         goto vdbe_return;
54852       }
54853     }
54854     assert( db->nStatement==0 );
54855     sqlite3CloseSavepoints(db);
54856     if( p->rc==SQLITE_OK ){
54857       rc = SQLITE_DONE;
54858     }else{
54859       rc = SQLITE_ERROR;
54860     }
54861     goto vdbe_return;
54862   }else{
54863     sqlite3SetString(&p->zErrMsg, db,
54864         (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
54865         (u.ar.iRollback)?"cannot rollback - no transaction is active":
54866                    "cannot commit - no transaction is active"));
54867
54868     rc = SQLITE_ERROR;
54869   }
54870   break;
54871 }
54872
54873 /* Opcode: Transaction P1 P2 * * *
54874 **
54875 ** Begin a transaction.  The transaction ends when a Commit or Rollback
54876 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
54877 ** transaction might also be rolled back if an error is encountered.
54878 **
54879 ** P1 is the index of the database file on which the transaction is
54880 ** started.  Index 0 is the main database file and index 1 is the
54881 ** file used for temporary tables.  Indices of 2 or more are used for
54882 ** attached databases.
54883 **
54884 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
54885 ** obtained on the database file when a write-transaction is started.  No
54886 ** other process can start another write transaction while this transaction is
54887 ** underway.  Starting a write transaction also creates a rollback journal. A
54888 ** write transaction must be started before any changes can be made to the
54889 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
54890 ** on the file.
54891 **
54892 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
54893 ** true (this flag is set if the Vdbe may modify more than one row and may
54894 ** throw an ABORT exception), a statement transaction may also be opened.
54895 ** More specifically, a statement transaction is opened iff the database
54896 ** connection is currently not in autocommit mode, or if there are other
54897 ** active statements. A statement transaction allows the affects of this
54898 ** VDBE to be rolled back after an error without having to roll back the
54899 ** entire transaction. If no error is encountered, the statement transaction
54900 ** will automatically commit when the VDBE halts.
54901 **
54902 ** If P2 is zero, then a read-lock is obtained on the database file.
54903 */
54904 case OP_Transaction: {
54905 #if 0  /* local variables moved into u.as */
54906   Btree *pBt;
54907 #endif /* local variables moved into u.as */
54908
54909   assert( pOp->p1>=0 && pOp->p1<db->nDb );
54910   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
54911   u.as.pBt = db->aDb[pOp->p1].pBt;
54912
54913   if( u.as.pBt ){
54914     rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
54915     if( rc==SQLITE_BUSY ){
54916       p->pc = pc;
54917       p->rc = rc = SQLITE_BUSY;
54918       goto vdbe_return;
54919     }
54920     if( rc!=SQLITE_OK ){
54921       goto abort_due_to_error;
54922     }
54923
54924     if( pOp->p2 && p->usesStmtJournal
54925      && (db->autoCommit==0 || db->activeVdbeCnt>1)
54926     ){
54927       assert( sqlite3BtreeIsInTrans(u.as.pBt) );
54928       if( p->iStatement==0 ){
54929         assert( db->nStatement>=0 && db->nSavepoint>=0 );
54930         db->nStatement++;
54931         p->iStatement = db->nSavepoint + db->nStatement;
54932       }
54933       rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
54934
54935       /* Store the current value of the database handles deferred constraint
54936       ** counter. If the statement transaction needs to be rolled back,
54937       ** the value of this counter needs to be restored too.  */
54938       p->nStmtDefCons = db->nDeferredCons;
54939     }
54940   }
54941   break;
54942 }
54943
54944 /* Opcode: ReadCookie P1 P2 P3 * *
54945 **
54946 ** Read cookie number P3 from database P1 and write it into register P2.
54947 ** P3==1 is the schema version.  P3==2 is the database format.
54948 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
54949 ** the main database file and P1==1 is the database file used to store
54950 ** temporary tables.
54951 **
54952 ** There must be a read-lock on the database (either a transaction
54953 ** must be started or there must be an open cursor) before
54954 ** executing this instruction.
54955 */
54956 case OP_ReadCookie: {               /* out2-prerelease */
54957 #if 0  /* local variables moved into u.at */
54958   int iMeta;
54959   int iDb;
54960   int iCookie;
54961 #endif /* local variables moved into u.at */
54962
54963   u.at.iDb = pOp->p1;
54964   u.at.iCookie = pOp->p3;
54965   assert( pOp->p3<SQLITE_N_BTREE_META );
54966   assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
54967   assert( db->aDb[u.at.iDb].pBt!=0 );
54968   assert( (p->btreeMask & (1<<u.at.iDb))!=0 );
54969
54970   sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
54971   pOut->u.i = u.at.iMeta;
54972   break;
54973 }
54974
54975 /* Opcode: SetCookie P1 P2 P3 * *
54976 **
54977 ** Write the content of register P3 (interpreted as an integer)
54978 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
54979 ** P2==2 is the database format. P2==3 is the recommended pager cache 
54980 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
54981 ** database file used to store temporary tables.
54982 **
54983 ** A transaction must be started before executing this opcode.
54984 */
54985 case OP_SetCookie: {       /* in3 */
54986 #if 0  /* local variables moved into u.au */
54987   Db *pDb;
54988 #endif /* local variables moved into u.au */
54989   assert( pOp->p2<SQLITE_N_BTREE_META );
54990   assert( pOp->p1>=0 && pOp->p1<db->nDb );
54991   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
54992   u.au.pDb = &db->aDb[pOp->p1];
54993   assert( u.au.pDb->pBt!=0 );
54994   pIn3 = &aMem[pOp->p3];
54995   sqlite3VdbeMemIntegerify(pIn3);
54996   /* See note about index shifting on OP_ReadCookie */
54997   rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
54998   if( pOp->p2==BTREE_SCHEMA_VERSION ){
54999     /* When the schema cookie changes, record the new cookie internally */
55000     u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
55001     db->flags |= SQLITE_InternChanges;
55002   }else if( pOp->p2==BTREE_FILE_FORMAT ){
55003     /* Record changes in the file format */
55004     u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
55005   }
55006   if( pOp->p1==1 ){
55007     /* Invalidate all prepared statements whenever the TEMP database
55008     ** schema is changed.  Ticket #1644 */
55009     sqlite3ExpirePreparedStatements(db);
55010     p->expired = 0;
55011   }
55012   break;
55013 }
55014
55015 /* Opcode: VerifyCookie P1 P2 *
55016 **
55017 ** Check the value of global database parameter number 0 (the
55018 ** schema version) and make sure it is equal to P2.  
55019 ** P1 is the database number which is 0 for the main database file
55020 ** and 1 for the file holding temporary tables and some higher number
55021 ** for auxiliary databases.
55022 **
55023 ** The cookie changes its value whenever the database schema changes.
55024 ** This operation is used to detect when that the cookie has changed
55025 ** and that the current process needs to reread the schema.
55026 **
55027 ** Either a transaction needs to have been started or an OP_Open needs
55028 ** to be executed (to establish a read lock) before this opcode is
55029 ** invoked.
55030 */
55031 case OP_VerifyCookie: {
55032 #if 0  /* local variables moved into u.av */
55033   int iMeta;
55034   Btree *pBt;
55035 #endif /* local variables moved into u.av */
55036   assert( pOp->p1>=0 && pOp->p1<db->nDb );
55037   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
55038   u.av.pBt = db->aDb[pOp->p1].pBt;
55039   if( u.av.pBt ){
55040     sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
55041   }else{
55042     u.av.iMeta = 0;
55043   }
55044   if( u.av.iMeta!=pOp->p2 ){
55045     sqlite3DbFree(db, p->zErrMsg);
55046     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
55047     /* If the schema-cookie from the database file matches the cookie
55048     ** stored with the in-memory representation of the schema, do
55049     ** not reload the schema from the database file.
55050     **
55051     ** If virtual-tables are in use, this is not just an optimization.
55052     ** Often, v-tables store their data in other SQLite tables, which
55053     ** are queried from within xNext() and other v-table methods using
55054     ** prepared queries. If such a query is out-of-date, we do not want to
55055     ** discard the database schema, as the user code implementing the
55056     ** v-table would have to be ready for the sqlite3_vtab structure itself
55057     ** to be invalidated whenever sqlite3_step() is called from within
55058     ** a v-table method.
55059     */
55060     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
55061       sqlite3ResetInternalSchema(db, pOp->p1);
55062     }
55063
55064     sqlite3ExpirePreparedStatements(db);
55065     rc = SQLITE_SCHEMA;
55066   }
55067   break;
55068 }
55069
55070 /* Opcode: OpenRead P1 P2 P3 P4 P5
55071 **
55072 ** Open a read-only cursor for the database table whose root page is
55073 ** P2 in a database file.  The database file is determined by P3. 
55074 ** P3==0 means the main database, P3==1 means the database used for 
55075 ** temporary tables, and P3>1 means used the corresponding attached
55076 ** database.  Give the new cursor an identifier of P1.  The P1
55077 ** values need not be contiguous but all P1 values should be small integers.
55078 ** It is an error for P1 to be negative.
55079 **
55080 ** If P5!=0 then use the content of register P2 as the root page, not
55081 ** the value of P2 itself.
55082 **
55083 ** There will be a read lock on the database whenever there is an
55084 ** open cursor.  If the database was unlocked prior to this instruction
55085 ** then a read lock is acquired as part of this instruction.  A read
55086 ** lock allows other processes to read the database but prohibits
55087 ** any other process from modifying the database.  The read lock is
55088 ** released when all cursors are closed.  If this instruction attempts
55089 ** to get a read lock but fails, the script terminates with an
55090 ** SQLITE_BUSY error code.
55091 **
55092 ** The P4 value may be either an integer (P4_INT32) or a pointer to
55093 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
55094 ** structure, then said structure defines the content and collating 
55095 ** sequence of the index being opened. Otherwise, if P4 is an integer 
55096 ** value, it is set to the number of columns in the table.
55097 **
55098 ** See also OpenWrite.
55099 */
55100 /* Opcode: OpenWrite P1 P2 P3 P4 P5
55101 **
55102 ** Open a read/write cursor named P1 on the table or index whose root
55103 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
55104 ** root page.
55105 **
55106 ** The P4 value may be either an integer (P4_INT32) or a pointer to
55107 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
55108 ** structure, then said structure defines the content and collating 
55109 ** sequence of the index being opened. Otherwise, if P4 is an integer 
55110 ** value, it is set to the number of columns in the table, or to the
55111 ** largest index of any column of the table that is actually used.
55112 **
55113 ** This instruction works just like OpenRead except that it opens the cursor
55114 ** in read/write mode.  For a given table, there can be one or more read-only
55115 ** cursors or a single read/write cursor but not both.
55116 **
55117 ** See also OpenRead.
55118 */
55119 case OP_OpenRead:
55120 case OP_OpenWrite: {
55121 #if 0  /* local variables moved into u.aw */
55122   int nField;
55123   KeyInfo *pKeyInfo;
55124   int p2;
55125   int iDb;
55126   int wrFlag;
55127   Btree *pX;
55128   VdbeCursor *pCur;
55129   Db *pDb;
55130 #endif /* local variables moved into u.aw */
55131
55132   if( p->expired ){
55133     rc = SQLITE_ABORT;
55134     break;
55135   }
55136
55137   u.aw.nField = 0;
55138   u.aw.pKeyInfo = 0;
55139   u.aw.p2 = pOp->p2;
55140   u.aw.iDb = pOp->p3;
55141   assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
55142   assert( (p->btreeMask & (1<<u.aw.iDb))!=0 );
55143   u.aw.pDb = &db->aDb[u.aw.iDb];
55144   u.aw.pX = u.aw.pDb->pBt;
55145   assert( u.aw.pX!=0 );
55146   if( pOp->opcode==OP_OpenWrite ){
55147     u.aw.wrFlag = 1;
55148     if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
55149       p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
55150     }
55151   }else{
55152     u.aw.wrFlag = 0;
55153   }
55154   if( pOp->p5 ){
55155     assert( u.aw.p2>0 );
55156     assert( u.aw.p2<=p->nMem );
55157     pIn2 = &aMem[u.aw.p2];
55158     sqlite3VdbeMemIntegerify(pIn2);
55159     u.aw.p2 = (int)pIn2->u.i;
55160     /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
55161     ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
55162     ** If there were a failure, the prepared statement would have halted
55163     ** before reaching this instruction. */
55164     if( NEVER(u.aw.p2<2) ) {
55165       rc = SQLITE_CORRUPT_BKPT;
55166       goto abort_due_to_error;
55167     }
55168   }
55169   if( pOp->p4type==P4_KEYINFO ){
55170     u.aw.pKeyInfo = pOp->p4.pKeyInfo;
55171     u.aw.pKeyInfo->enc = ENC(p->db);
55172     u.aw.nField = u.aw.pKeyInfo->nField+1;
55173   }else if( pOp->p4type==P4_INT32 ){
55174     u.aw.nField = pOp->p4.i;
55175   }
55176   assert( pOp->p1>=0 );
55177   u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
55178   if( u.aw.pCur==0 ) goto no_mem;
55179   u.aw.pCur->nullRow = 1;
55180   rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
55181   u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
55182
55183   /* Since it performs no memory allocation or IO, the only values that
55184   ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
55185   ** SQLITE_EMPTY is only returned when attempting to open the table
55186   ** rooted at page 1 of a zero-byte database.  */
55187   assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
55188   if( rc==SQLITE_EMPTY ){
55189     u.aw.pCur->pCursor = 0;
55190     rc = SQLITE_OK;
55191   }
55192
55193   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
55194   ** SQLite used to check if the root-page flags were sane at this point
55195   ** and report database corruption if they were not, but this check has
55196   ** since moved into the btree layer.  */
55197   u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
55198   u.aw.pCur->isIndex = !u.aw.pCur->isTable;
55199   break;
55200 }
55201
55202 /* Opcode: OpenEphemeral P1 P2 * P4 *
55203 **
55204 ** Open a new cursor P1 to a transient table.
55205 ** The cursor is always opened read/write even if 
55206 ** the main database is read-only.  The transient or virtual
55207 ** table is deleted automatically when the cursor is closed.
55208 **
55209 ** P2 is the number of columns in the virtual table.
55210 ** The cursor points to a BTree table if P4==0 and to a BTree index
55211 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
55212 ** that defines the format of keys in the index.
55213 **
55214 ** This opcode was once called OpenTemp.  But that created
55215 ** confusion because the term "temp table", might refer either
55216 ** to a TEMP table at the SQL level, or to a table opened by
55217 ** this opcode.  Then this opcode was call OpenVirtual.  But
55218 ** that created confusion with the whole virtual-table idea.
55219 */
55220 case OP_OpenEphemeral: {
55221 #if 0  /* local variables moved into u.ax */
55222   VdbeCursor *pCx;
55223 #endif /* local variables moved into u.ax */
55224   static const int openFlags =
55225       SQLITE_OPEN_READWRITE |
55226       SQLITE_OPEN_CREATE |
55227       SQLITE_OPEN_EXCLUSIVE |
55228       SQLITE_OPEN_DELETEONCLOSE |
55229       SQLITE_OPEN_TRANSIENT_DB;
55230
55231   assert( pOp->p1>=0 );
55232   u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
55233   if( u.ax.pCx==0 ) goto no_mem;
55234   u.ax.pCx->nullRow = 1;
55235   rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
55236                            &u.ax.pCx->pBt);
55237   if( rc==SQLITE_OK ){
55238     rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
55239   }
55240   if( rc==SQLITE_OK ){
55241     /* If a transient index is required, create it by calling
55242     ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
55243     ** opening it. If a transient table is required, just use the
55244     ** automatically created table with root-page 1 (an INTKEY table).
55245     */
55246     if( pOp->p4.pKeyInfo ){
55247       int pgno;
55248       assert( pOp->p4type==P4_KEYINFO );
55249       rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_ZERODATA);
55250       if( rc==SQLITE_OK ){
55251         assert( pgno==MASTER_ROOT+1 );
55252         rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
55253                                 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
55254         u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
55255         u.ax.pCx->pKeyInfo->enc = ENC(p->db);
55256       }
55257       u.ax.pCx->isTable = 0;
55258     }else{
55259       rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
55260       u.ax.pCx->isTable = 1;
55261     }
55262   }
55263   u.ax.pCx->isIndex = !u.ax.pCx->isTable;
55264   break;
55265 }
55266
55267 /* Opcode: OpenPseudo P1 P2 P3 * *
55268 **
55269 ** Open a new cursor that points to a fake table that contains a single
55270 ** row of data.  The content of that one row in the content of memory
55271 ** register P2.  In other words, cursor P1 becomes an alias for the 
55272 ** MEM_Blob content contained in register P2.
55273 **
55274 ** A pseudo-table created by this opcode is used to hold the a single
55275 ** row output from the sorter so that the row can be decomposed into
55276 ** individual columns using the OP_Column opcode.  The OP_Column opcode
55277 ** is the only cursor opcode that works with a pseudo-table.
55278 **
55279 ** P3 is the number of fields in the records that will be stored by
55280 ** the pseudo-table.
55281 */
55282 case OP_OpenPseudo: {
55283 #if 0  /* local variables moved into u.ay */
55284   VdbeCursor *pCx;
55285 #endif /* local variables moved into u.ay */
55286
55287   assert( pOp->p1>=0 );
55288   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
55289   if( u.ay.pCx==0 ) goto no_mem;
55290   u.ay.pCx->nullRow = 1;
55291   u.ay.pCx->pseudoTableReg = pOp->p2;
55292   u.ay.pCx->isTable = 1;
55293   u.ay.pCx->isIndex = 0;
55294   break;
55295 }
55296
55297 /* Opcode: Close P1 * * * *
55298 **
55299 ** Close a cursor previously opened as P1.  If P1 is not
55300 ** currently open, this instruction is a no-op.
55301 */
55302 case OP_Close: {
55303   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55304   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
55305   p->apCsr[pOp->p1] = 0;
55306   break;
55307 }
55308
55309 /* Opcode: SeekGe P1 P2 P3 P4 *
55310 **
55311 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
55312 ** use the value in register P3 as the key.  If cursor P1 refers 
55313 ** to an SQL index, then P3 is the first in an array of P4 registers 
55314 ** that are used as an unpacked index key. 
55315 **
55316 ** Reposition cursor P1 so that  it points to the smallest entry that 
55317 ** is greater than or equal to the key value. If there are no records 
55318 ** greater than or equal to the key and P2 is not zero, then jump to P2.
55319 **
55320 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
55321 */
55322 /* Opcode: SeekGt P1 P2 P3 P4 *
55323 **
55324 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
55325 ** use the value in register P3 as a key. If cursor P1 refers 
55326 ** to an SQL index, then P3 is the first in an array of P4 registers 
55327 ** that are used as an unpacked index key. 
55328 **
55329 ** Reposition cursor P1 so that  it points to the smallest entry that 
55330 ** is greater than the key value. If there are no records greater than 
55331 ** the key and P2 is not zero, then jump to P2.
55332 **
55333 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
55334 */
55335 /* Opcode: SeekLt P1 P2 P3 P4 * 
55336 **
55337 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
55338 ** use the value in register P3 as a key. If cursor P1 refers 
55339 ** to an SQL index, then P3 is the first in an array of P4 registers 
55340 ** that are used as an unpacked index key. 
55341 **
55342 ** Reposition cursor P1 so that  it points to the largest entry that 
55343 ** is less than the key value. If there are no records less than 
55344 ** the key and P2 is not zero, then jump to P2.
55345 **
55346 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
55347 */
55348 /* Opcode: SeekLe P1 P2 P3 P4 *
55349 **
55350 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
55351 ** use the value in register P3 as a key. If cursor P1 refers 
55352 ** to an SQL index, then P3 is the first in an array of P4 registers 
55353 ** that are used as an unpacked index key. 
55354 **
55355 ** Reposition cursor P1 so that it points to the largest entry that 
55356 ** is less than or equal to the key value. If there are no records 
55357 ** less than or equal to the key and P2 is not zero, then jump to P2.
55358 **
55359 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
55360 */
55361 case OP_SeekLt:         /* jump, in3 */
55362 case OP_SeekLe:         /* jump, in3 */
55363 case OP_SeekGe:         /* jump, in3 */
55364 case OP_SeekGt: {       /* jump, in3 */
55365 #if 0  /* local variables moved into u.az */
55366   int res;
55367   int oc;
55368   VdbeCursor *pC;
55369   UnpackedRecord r;
55370   int nField;
55371   i64 iKey;      /* The rowid we are to seek to */
55372 #endif /* local variables moved into u.az */
55373
55374   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55375   assert( pOp->p2!=0 );
55376   u.az.pC = p->apCsr[pOp->p1];
55377   assert( u.az.pC!=0 );
55378   assert( u.az.pC->pseudoTableReg==0 );
55379   assert( OP_SeekLe == OP_SeekLt+1 );
55380   assert( OP_SeekGe == OP_SeekLt+2 );
55381   assert( OP_SeekGt == OP_SeekLt+3 );
55382   if( u.az.pC->pCursor!=0 ){
55383     u.az.oc = pOp->opcode;
55384     u.az.pC->nullRow = 0;
55385     if( u.az.pC->isTable ){
55386       /* The input value in P3 might be of any type: integer, real, string,
55387       ** blob, or NULL.  But it needs to be an integer before we can do
55388       ** the seek, so covert it. */
55389       pIn3 = &aMem[pOp->p3];
55390       applyNumericAffinity(pIn3);
55391       u.az.iKey = sqlite3VdbeIntValue(pIn3);
55392       u.az.pC->rowidIsValid = 0;
55393
55394       /* If the P3 value could not be converted into an integer without
55395       ** loss of information, then special processing is required... */
55396       if( (pIn3->flags & MEM_Int)==0 ){
55397         if( (pIn3->flags & MEM_Real)==0 ){
55398           /* If the P3 value cannot be converted into any kind of a number,
55399           ** then the seek is not possible, so jump to P2 */
55400           pc = pOp->p2 - 1;
55401           break;
55402         }
55403         /* If we reach this point, then the P3 value must be a floating
55404         ** point number. */
55405         assert( (pIn3->flags & MEM_Real)!=0 );
55406
55407         if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
55408           /* The P3 value is too large in magnitude to be expressed as an
55409           ** integer. */
55410           u.az.res = 1;
55411           if( pIn3->r<0 ){
55412             if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
55413               rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
55414               if( rc!=SQLITE_OK ) goto abort_due_to_error;
55415             }
55416           }else{
55417             if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
55418               rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
55419               if( rc!=SQLITE_OK ) goto abort_due_to_error;
55420             }
55421           }
55422           if( u.az.res ){
55423             pc = pOp->p2 - 1;
55424           }
55425           break;
55426         }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
55427           /* Use the ceiling() function to convert real->int */
55428           if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
55429         }else{
55430           /* Use the floor() function to convert real->int */
55431           assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
55432           if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
55433         }
55434       }
55435       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
55436       if( rc!=SQLITE_OK ){
55437         goto abort_due_to_error;
55438       }
55439       if( u.az.res==0 ){
55440         u.az.pC->rowidIsValid = 1;
55441         u.az.pC->lastRowid = u.az.iKey;
55442       }
55443     }else{
55444       u.az.nField = pOp->p4.i;
55445       assert( pOp->p4type==P4_INT32 );
55446       assert( u.az.nField>0 );
55447       u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
55448       u.az.r.nField = (u16)u.az.nField;
55449
55450       /* The next line of code computes as follows, only faster:
55451       **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
55452       **     u.az.r.flags = UNPACKED_INCRKEY;
55453       **   }else{
55454       **     u.az.r.flags = 0;
55455       **   }
55456       */
55457       u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
55458       assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
55459       assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
55460       assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
55461       assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
55462
55463       u.az.r.aMem = &aMem[pOp->p3];
55464       ExpandBlob(u.az.r.aMem);
55465       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
55466       if( rc!=SQLITE_OK ){
55467         goto abort_due_to_error;
55468       }
55469       u.az.pC->rowidIsValid = 0;
55470     }
55471     u.az.pC->deferredMoveto = 0;
55472     u.az.pC->cacheStatus = CACHE_STALE;
55473 #ifdef SQLITE_TEST
55474     sqlite3_search_count++;
55475 #endif
55476     if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
55477       if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
55478         rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
55479         if( rc!=SQLITE_OK ) goto abort_due_to_error;
55480         u.az.pC->rowidIsValid = 0;
55481       }else{
55482         u.az.res = 0;
55483       }
55484     }else{
55485       assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
55486       if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
55487         rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
55488         if( rc!=SQLITE_OK ) goto abort_due_to_error;
55489         u.az.pC->rowidIsValid = 0;
55490       }else{
55491         /* u.az.res might be negative because the table is empty.  Check to
55492         ** see if this is the case.
55493         */
55494         u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
55495       }
55496     }
55497     assert( pOp->p2>0 );
55498     if( u.az.res ){
55499       pc = pOp->p2 - 1;
55500     }
55501   }else{
55502     /* This happens when attempting to open the sqlite3_master table
55503     ** for read access returns SQLITE_EMPTY. In this case always
55504     ** take the jump (since there are no records in the table).
55505     */
55506     pc = pOp->p2 - 1;
55507   }
55508   break;
55509 }
55510
55511 /* Opcode: Seek P1 P2 * * *
55512 **
55513 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
55514 ** for P1 to move so that it points to the rowid given by P2.
55515 **
55516 ** This is actually a deferred seek.  Nothing actually happens until
55517 ** the cursor is used to read a record.  That way, if no reads
55518 ** occur, no unnecessary I/O happens.
55519 */
55520 case OP_Seek: {    /* in2 */
55521 #if 0  /* local variables moved into u.ba */
55522   VdbeCursor *pC;
55523 #endif /* local variables moved into u.ba */
55524
55525   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55526   u.ba.pC = p->apCsr[pOp->p1];
55527   assert( u.ba.pC!=0 );
55528   if( ALWAYS(u.ba.pC->pCursor!=0) ){
55529     assert( u.ba.pC->isTable );
55530     u.ba.pC->nullRow = 0;
55531     pIn2 = &aMem[pOp->p2];
55532     u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
55533     u.ba.pC->rowidIsValid = 0;
55534     u.ba.pC->deferredMoveto = 1;
55535   }
55536   break;
55537 }
55538   
55539
55540 /* Opcode: Found P1 P2 P3 P4 *
55541 **
55542 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
55543 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
55544 ** record.
55545 **
55546 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
55547 ** is a prefix of any entry in P1 then a jump is made to P2 and
55548 ** P1 is left pointing at the matching entry.
55549 */
55550 /* Opcode: NotFound P1 P2 P3 P4 *
55551 **
55552 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
55553 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
55554 ** record.
55555 ** 
55556 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
55557 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
55558 ** does contain an entry whose prefix matches the P3/P4 record then control
55559 ** falls through to the next instruction and P1 is left pointing at the
55560 ** matching entry.
55561 **
55562 ** See also: Found, NotExists, IsUnique
55563 */
55564 case OP_NotFound:       /* jump, in3 */
55565 case OP_Found: {        /* jump, in3 */
55566 #if 0  /* local variables moved into u.bb */
55567   int alreadyExists;
55568   VdbeCursor *pC;
55569   int res;
55570   UnpackedRecord *pIdxKey;
55571   UnpackedRecord r;
55572   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
55573 #endif /* local variables moved into u.bb */
55574
55575 #ifdef SQLITE_TEST
55576   sqlite3_found_count++;
55577 #endif
55578
55579   u.bb.alreadyExists = 0;
55580   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55581   assert( pOp->p4type==P4_INT32 );
55582   u.bb.pC = p->apCsr[pOp->p1];
55583   assert( u.bb.pC!=0 );
55584   pIn3 = &aMem[pOp->p3];
55585   if( ALWAYS(u.bb.pC->pCursor!=0) ){
55586
55587     assert( u.bb.pC->isTable==0 );
55588     if( pOp->p4.i>0 ){
55589       u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
55590       u.bb.r.nField = (u16)pOp->p4.i;
55591       u.bb.r.aMem = pIn3;
55592       u.bb.r.flags = UNPACKED_PREFIX_MATCH;
55593       u.bb.pIdxKey = &u.bb.r;
55594     }else{
55595       assert( pIn3->flags & MEM_Blob );
55596       ExpandBlob(pIn3);
55597       u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
55598                                         u.bb.aTempRec, sizeof(u.bb.aTempRec));
55599       if( u.bb.pIdxKey==0 ){
55600         goto no_mem;
55601       }
55602       u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
55603     }
55604     rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
55605     if( pOp->p4.i==0 ){
55606       sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
55607     }
55608     if( rc!=SQLITE_OK ){
55609       break;
55610     }
55611     u.bb.alreadyExists = (u.bb.res==0);
55612     u.bb.pC->deferredMoveto = 0;
55613     u.bb.pC->cacheStatus = CACHE_STALE;
55614   }
55615   if( pOp->opcode==OP_Found ){
55616     if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
55617   }else{
55618     if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
55619   }
55620   break;
55621 }
55622
55623 /* Opcode: IsUnique P1 P2 P3 P4 *
55624 **
55625 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
55626 ** no data and where the key are records generated by OP_MakeRecord with
55627 ** the list field being the integer ROWID of the entry that the index
55628 ** entry refers to.
55629 **
55630 ** The P3 register contains an integer record number. Call this record 
55631 ** number R. Register P4 is the first in a set of N contiguous registers
55632 ** that make up an unpacked index key that can be used with cursor P1.
55633 ** The value of N can be inferred from the cursor. N includes the rowid
55634 ** value appended to the end of the index record. This rowid value may
55635 ** or may not be the same as R.
55636 **
55637 ** If any of the N registers beginning with register P4 contains a NULL
55638 ** value, jump immediately to P2.
55639 **
55640 ** Otherwise, this instruction checks if cursor P1 contains an entry
55641 ** where the first (N-1) fields match but the rowid value at the end
55642 ** of the index entry is not R. If there is no such entry, control jumps
55643 ** to instruction P2. Otherwise, the rowid of the conflicting index
55644 ** entry is copied to register P3 and control falls through to the next
55645 ** instruction.
55646 **
55647 ** See also: NotFound, NotExists, Found
55648 */
55649 case OP_IsUnique: {        /* jump, in3 */
55650 #if 0  /* local variables moved into u.bc */
55651   u16 ii;
55652   VdbeCursor *pCx;
55653   BtCursor *pCrsr;
55654   u16 nField;
55655   Mem *aMx;
55656   UnpackedRecord r;                  /* B-Tree index search key */
55657   i64 R;                             /* Rowid stored in register P3 */
55658 #endif /* local variables moved into u.bc */
55659
55660   pIn3 = &aMem[pOp->p3];
55661   u.bc.aMx = &aMem[pOp->p4.i];
55662   /* Assert that the values of parameters P1 and P4 are in range. */
55663   assert( pOp->p4type==P4_INT32 );
55664   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
55665   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55666
55667   /* Find the index cursor. */
55668   u.bc.pCx = p->apCsr[pOp->p1];
55669   assert( u.bc.pCx->deferredMoveto==0 );
55670   u.bc.pCx->seekResult = 0;
55671   u.bc.pCx->cacheStatus = CACHE_STALE;
55672   u.bc.pCrsr = u.bc.pCx->pCursor;
55673
55674   /* If any of the values are NULL, take the jump. */
55675   u.bc.nField = u.bc.pCx->pKeyInfo->nField;
55676   for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
55677     if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
55678       pc = pOp->p2 - 1;
55679       u.bc.pCrsr = 0;
55680       break;
55681     }
55682   }
55683   assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
55684
55685   if( u.bc.pCrsr!=0 ){
55686     /* Populate the index search key. */
55687     u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
55688     u.bc.r.nField = u.bc.nField + 1;
55689     u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
55690     u.bc.r.aMem = u.bc.aMx;
55691
55692     /* Extract the value of u.bc.R from register P3. */
55693     sqlite3VdbeMemIntegerify(pIn3);
55694     u.bc.R = pIn3->u.i;
55695
55696     /* Search the B-Tree index. If no conflicting record is found, jump
55697     ** to P2. Otherwise, copy the rowid of the conflicting record to
55698     ** register P3 and fall through to the next instruction.  */
55699     rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
55700     if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
55701       pc = pOp->p2 - 1;
55702     }else{
55703       pIn3->u.i = u.bc.r.rowid;
55704     }
55705   }
55706   break;
55707 }
55708
55709 /* Opcode: NotExists P1 P2 P3 * *
55710 **
55711 ** Use the content of register P3 as a integer key.  If a record 
55712 ** with that key does not exist in table of P1, then jump to P2. 
55713 ** If the record does exist, then fall thru.  The cursor is left 
55714 ** pointing to the record if it exists.
55715 **
55716 ** The difference between this operation and NotFound is that this
55717 ** operation assumes the key is an integer and that P1 is a table whereas
55718 ** NotFound assumes key is a blob constructed from MakeRecord and
55719 ** P1 is an index.
55720 **
55721 ** See also: Found, NotFound, IsUnique
55722 */
55723 case OP_NotExists: {        /* jump, in3 */
55724 #if 0  /* local variables moved into u.bd */
55725   VdbeCursor *pC;
55726   BtCursor *pCrsr;
55727   int res;
55728   u64 iKey;
55729 #endif /* local variables moved into u.bd */
55730
55731   pIn3 = &aMem[pOp->p3];
55732   assert( pIn3->flags & MEM_Int );
55733   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55734   u.bd.pC = p->apCsr[pOp->p1];
55735   assert( u.bd.pC!=0 );
55736   assert( u.bd.pC->isTable );
55737   assert( u.bd.pC->pseudoTableReg==0 );
55738   u.bd.pCrsr = u.bd.pC->pCursor;
55739   if( u.bd.pCrsr!=0 ){
55740     u.bd.res = 0;
55741     u.bd.iKey = pIn3->u.i;
55742     rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
55743     u.bd.pC->lastRowid = pIn3->u.i;
55744     u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
55745     u.bd.pC->nullRow = 0;
55746     u.bd.pC->cacheStatus = CACHE_STALE;
55747     u.bd.pC->deferredMoveto = 0;
55748     if( u.bd.res!=0 ){
55749       pc = pOp->p2 - 1;
55750       assert( u.bd.pC->rowidIsValid==0 );
55751     }
55752     u.bd.pC->seekResult = u.bd.res;
55753   }else{
55754     /* This happens when an attempt to open a read cursor on the
55755     ** sqlite_master table returns SQLITE_EMPTY.
55756     */
55757     pc = pOp->p2 - 1;
55758     assert( u.bd.pC->rowidIsValid==0 );
55759     u.bd.pC->seekResult = 0;
55760   }
55761   break;
55762 }
55763
55764 /* Opcode: Sequence P1 P2 * * *
55765 **
55766 ** Find the next available sequence number for cursor P1.
55767 ** Write the sequence number into register P2.
55768 ** The sequence number on the cursor is incremented after this
55769 ** instruction.  
55770 */
55771 case OP_Sequence: {           /* out2-prerelease */
55772   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55773   assert( p->apCsr[pOp->p1]!=0 );
55774   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
55775   break;
55776 }
55777
55778
55779 /* Opcode: NewRowid P1 P2 P3 * *
55780 **
55781 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
55782 ** The record number is not previously used as a key in the database
55783 ** table that cursor P1 points to.  The new record number is written
55784 ** written to register P2.
55785 **
55786 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
55787 ** the largest previously generated record number. No new record numbers are
55788 ** allowed to be less than this value. When this value reaches its maximum, 
55789 ** a SQLITE_FULL error is generated. The P3 register is updated with the '
55790 ** generated record number. This P3 mechanism is used to help implement the
55791 ** AUTOINCREMENT feature.
55792 */
55793 case OP_NewRowid: {           /* out2-prerelease */
55794 #if 0  /* local variables moved into u.be */
55795   i64 v;                 /* The new rowid */
55796   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
55797   int res;               /* Result of an sqlite3BtreeLast() */
55798   int cnt;               /* Counter to limit the number of searches */
55799   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
55800   VdbeFrame *pFrame;     /* Root frame of VDBE */
55801 #endif /* local variables moved into u.be */
55802
55803   u.be.v = 0;
55804   u.be.res = 0;
55805   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55806   u.be.pC = p->apCsr[pOp->p1];
55807   assert( u.be.pC!=0 );
55808   if( NEVER(u.be.pC->pCursor==0) ){
55809     /* The zero initialization above is all that is needed */
55810   }else{
55811     /* The next rowid or record number (different terms for the same
55812     ** thing) is obtained in a two-step algorithm.
55813     **
55814     ** First we attempt to find the largest existing rowid and add one
55815     ** to that.  But if the largest existing rowid is already the maximum
55816     ** positive integer, we have to fall through to the second
55817     ** probabilistic algorithm
55818     **
55819     ** The second algorithm is to select a rowid at random and see if
55820     ** it already exists in the table.  If it does not exist, we have
55821     ** succeeded.  If the random rowid does exist, we select a new one
55822     ** and try again, up to 100 times.
55823     */
55824     assert( u.be.pC->isTable );
55825     u.be.cnt = 0;
55826
55827 #ifdef SQLITE_32BIT_ROWID
55828 #   define MAX_ROWID 0x7fffffff
55829 #else
55830     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
55831     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
55832     ** to provide the constant while making all compilers happy.
55833     */
55834 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
55835 #endif
55836
55837     if( !u.be.pC->useRandomRowid ){
55838       u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
55839       if( u.be.v==0 ){
55840         rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
55841         if( rc!=SQLITE_OK ){
55842           goto abort_due_to_error;
55843         }
55844         if( u.be.res ){
55845           u.be.v = 1;   /* IMP: R-61914-48074 */
55846         }else{
55847           assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
55848           rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
55849           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
55850           if( u.be.v==MAX_ROWID ){
55851             u.be.pC->useRandomRowid = 1;
55852           }else{
55853             u.be.v++;   /* IMP: R-29538-34987 */
55854           }
55855         }
55856       }
55857
55858 #ifndef SQLITE_OMIT_AUTOINCREMENT
55859       if( pOp->p3 ){
55860         /* Assert that P3 is a valid memory cell. */
55861         assert( pOp->p3>0 );
55862         if( p->pFrame ){
55863           for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
55864           /* Assert that P3 is a valid memory cell. */
55865           assert( pOp->p3<=u.be.pFrame->nMem );
55866           u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
55867         }else{
55868           /* Assert that P3 is a valid memory cell. */
55869           assert( pOp->p3<=p->nMem );
55870           u.be.pMem = &aMem[pOp->p3];
55871         }
55872
55873         REGISTER_TRACE(pOp->p3, u.be.pMem);
55874         sqlite3VdbeMemIntegerify(u.be.pMem);
55875         assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
55876         if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
55877           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
55878           goto abort_due_to_error;
55879         }
55880         if( u.be.v<u.be.pMem->u.i+1 ){
55881           u.be.v = u.be.pMem->u.i + 1;
55882         }
55883         u.be.pMem->u.i = u.be.v;
55884       }
55885 #endif
55886
55887       sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
55888     }
55889     if( u.be.pC->useRandomRowid ){
55890       /* IMPLEMENTATION-OF: R-48598-02938 If the largest ROWID is equal to the
55891       ** largest possible integer (9223372036854775807) then the database
55892       ** engine starts picking candidate ROWIDs at random until it finds one
55893       ** that is not previously used.
55894       */
55895       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
55896                              ** an AUTOINCREMENT table. */
55897       u.be.v = db->lastRowid;
55898       u.be.cnt = 0;
55899       do{
55900         if( u.be.cnt==0 && (u.be.v&0xffffff)==u.be.v ){
55901           u.be.v++;
55902         }else{
55903           sqlite3_randomness(sizeof(u.be.v), &u.be.v);
55904           if( u.be.cnt<5 ) u.be.v &= 0xffffff;
55905         }
55906         rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v, 0, &u.be.res);
55907         u.be.cnt++;
55908       }while( u.be.cnt<100 && rc==SQLITE_OK && u.be.res==0 );
55909       if( rc==SQLITE_OK && u.be.res==0 ){
55910         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
55911         goto abort_due_to_error;
55912       }
55913     }
55914     u.be.pC->rowidIsValid = 0;
55915     u.be.pC->deferredMoveto = 0;
55916     u.be.pC->cacheStatus = CACHE_STALE;
55917   }
55918   pOut->u.i = u.be.v;
55919   break;
55920 }
55921
55922 /* Opcode: Insert P1 P2 P3 P4 P5
55923 **
55924 ** Write an entry into the table of cursor P1.  A new entry is
55925 ** created if it doesn't already exist or the data for an existing
55926 ** entry is overwritten.  The data is the value MEM_Blob stored in register
55927 ** number P2. The key is stored in register P3. The key must
55928 ** be a MEM_Int.
55929 **
55930 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
55931 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
55932 ** then rowid is stored for subsequent return by the
55933 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
55934 **
55935 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
55936 ** the last seek operation (OP_NotExists) was a success, then this
55937 ** operation will not attempt to find the appropriate row before doing
55938 ** the insert but will instead overwrite the row that the cursor is
55939 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
55940 ** has already positioned the cursor correctly.  This is an optimization
55941 ** that boosts performance by avoiding redundant seeks.
55942 **
55943 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
55944 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
55945 ** is part of an INSERT operation.  The difference is only important to
55946 ** the update hook.
55947 **
55948 ** Parameter P4 may point to a string containing the table-name, or
55949 ** may be NULL. If it is not NULL, then the update-hook 
55950 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
55951 **
55952 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
55953 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
55954 ** and register P2 becomes ephemeral.  If the cursor is changed, the
55955 ** value of register P2 will then change.  Make sure this does not
55956 ** cause any problems.)
55957 **
55958 ** This instruction only works on tables.  The equivalent instruction
55959 ** for indices is OP_IdxInsert.
55960 */
55961 /* Opcode: InsertInt P1 P2 P3 P4 P5
55962 **
55963 ** This works exactly like OP_Insert except that the key is the
55964 ** integer value P3, not the value of the integer stored in register P3.
55965 */
55966 case OP_Insert: 
55967 case OP_InsertInt: {
55968 #if 0  /* local variables moved into u.bf */
55969   Mem *pData;       /* MEM cell holding data for the record to be inserted */
55970   Mem *pKey;        /* MEM cell holding key  for the record */
55971   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
55972   VdbeCursor *pC;   /* Cursor to table into which insert is written */
55973   int nZero;        /* Number of zero-bytes to append */
55974   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
55975   const char *zDb;  /* database name - used by the update hook */
55976   const char *zTbl; /* Table name - used by the opdate hook */
55977   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
55978 #endif /* local variables moved into u.bf */
55979
55980   u.bf.pData = &aMem[pOp->p2];
55981   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55982   u.bf.pC = p->apCsr[pOp->p1];
55983   assert( u.bf.pC!=0 );
55984   assert( u.bf.pC->pCursor!=0 );
55985   assert( u.bf.pC->pseudoTableReg==0 );
55986   assert( u.bf.pC->isTable );
55987   REGISTER_TRACE(pOp->p2, u.bf.pData);
55988
55989   if( pOp->opcode==OP_Insert ){
55990     u.bf.pKey = &aMem[pOp->p3];
55991     assert( u.bf.pKey->flags & MEM_Int );
55992     REGISTER_TRACE(pOp->p3, u.bf.pKey);
55993     u.bf.iKey = u.bf.pKey->u.i;
55994   }else{
55995     assert( pOp->opcode==OP_InsertInt );
55996     u.bf.iKey = pOp->p3;
55997   }
55998
55999   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
56000   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
56001   if( u.bf.pData->flags & MEM_Null ){
56002     u.bf.pData->z = 0;
56003     u.bf.pData->n = 0;
56004   }else{
56005     assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
56006   }
56007   u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
56008   if( u.bf.pData->flags & MEM_Zero ){
56009     u.bf.nZero = u.bf.pData->u.nZero;
56010   }else{
56011     u.bf.nZero = 0;
56012   }
56013   sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
56014   rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
56015                           u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
56016                           pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
56017   );
56018   u.bf.pC->rowidIsValid = 0;
56019   u.bf.pC->deferredMoveto = 0;
56020   u.bf.pC->cacheStatus = CACHE_STALE;
56021
56022   /* Invoke the update-hook if required. */
56023   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
56024     u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
56025     u.bf.zTbl = pOp->p4.z;
56026     u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
56027     assert( u.bf.pC->isTable );
56028     db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
56029     assert( u.bf.pC->iDb>=0 );
56030   }
56031   break;
56032 }
56033
56034 /* Opcode: Delete P1 P2 * P4 *
56035 **
56036 ** Delete the record at which the P1 cursor is currently pointing.
56037 **
56038 ** The cursor will be left pointing at either the next or the previous
56039 ** record in the table. If it is left pointing at the next record, then
56040 ** the next Next instruction will be a no-op.  Hence it is OK to delete
56041 ** a record from within an Next loop.
56042 **
56043 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
56044 ** incremented (otherwise not).
56045 **
56046 ** P1 must not be pseudo-table.  It has to be a real table with
56047 ** multiple rows.
56048 **
56049 ** If P4 is not NULL, then it is the name of the table that P1 is
56050 ** pointing to.  The update hook will be invoked, if it exists.
56051 ** If P4 is not NULL then the P1 cursor must have been positioned
56052 ** using OP_NotFound prior to invoking this opcode.
56053 */
56054 case OP_Delete: {
56055 #if 0  /* local variables moved into u.bg */
56056   i64 iKey;
56057   VdbeCursor *pC;
56058 #endif /* local variables moved into u.bg */
56059
56060   u.bg.iKey = 0;
56061   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56062   u.bg.pC = p->apCsr[pOp->p1];
56063   assert( u.bg.pC!=0 );
56064   assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
56065
56066   /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
56067   ** row being deleted.
56068   */
56069   if( db->xUpdateCallback && pOp->p4.z ){
56070     assert( u.bg.pC->isTable );
56071     assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
56072     u.bg.iKey = u.bg.pC->lastRowid;
56073   }
56074
56075   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
56076   ** OP_Column on the same table without any intervening operations that
56077   ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
56078   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
56079   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
56080   ** to guard against future changes to the code generator.
56081   **/
56082   assert( u.bg.pC->deferredMoveto==0 );
56083   rc = sqlite3VdbeCursorMoveto(u.bg.pC);
56084   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
56085
56086   sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
56087   rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
56088   u.bg.pC->cacheStatus = CACHE_STALE;
56089
56090   /* Invoke the update-hook if required. */
56091   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
56092     const char *zDb = db->aDb[u.bg.pC->iDb].zName;
56093     const char *zTbl = pOp->p4.z;
56094     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
56095     assert( u.bg.pC->iDb>=0 );
56096   }
56097   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
56098   break;
56099 }
56100 /* Opcode: ResetCount * * * * *
56101 **
56102 ** The value of the change counter is copied to the database handle
56103 ** change counter (returned by subsequent calls to sqlite3_changes()).
56104 ** Then the VMs internal change counter resets to 0.
56105 ** This is used by trigger programs.
56106 */
56107 case OP_ResetCount: {
56108   sqlite3VdbeSetChanges(db, p->nChange);
56109   p->nChange = 0;
56110   break;
56111 }
56112
56113 /* Opcode: RowData P1 P2 * * *
56114 **
56115 ** Write into register P2 the complete row data for cursor P1.
56116 ** There is no interpretation of the data.  
56117 ** It is just copied onto the P2 register exactly as 
56118 ** it is found in the database file.
56119 **
56120 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
56121 ** of a real table, not a pseudo-table.
56122 */
56123 /* Opcode: RowKey P1 P2 * * *
56124 **
56125 ** Write into register P2 the complete row key for cursor P1.
56126 ** There is no interpretation of the data.  
56127 ** The key is copied onto the P3 register exactly as 
56128 ** it is found in the database file.
56129 **
56130 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
56131 ** of a real table, not a pseudo-table.
56132 */
56133 case OP_RowKey:
56134 case OP_RowData: {
56135 #if 0  /* local variables moved into u.bh */
56136   VdbeCursor *pC;
56137   BtCursor *pCrsr;
56138   u32 n;
56139   i64 n64;
56140 #endif /* local variables moved into u.bh */
56141
56142   pOut = &aMem[pOp->p2];
56143
56144   /* Note that RowKey and RowData are really exactly the same instruction */
56145   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56146   u.bh.pC = p->apCsr[pOp->p1];
56147   assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
56148   assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
56149   assert( u.bh.pC!=0 );
56150   assert( u.bh.pC->nullRow==0 );
56151   assert( u.bh.pC->pseudoTableReg==0 );
56152   assert( u.bh.pC->pCursor!=0 );
56153   u.bh.pCrsr = u.bh.pC->pCursor;
56154   assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
56155
56156   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
56157   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
56158   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
56159   ** a no-op and can never fail.  But we leave it in place as a safety.
56160   */
56161   assert( u.bh.pC->deferredMoveto==0 );
56162   rc = sqlite3VdbeCursorMoveto(u.bh.pC);
56163   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
56164
56165   if( u.bh.pC->isIndex ){
56166     assert( !u.bh.pC->isTable );
56167     rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
56168     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
56169     if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
56170       goto too_big;
56171     }
56172     u.bh.n = (u32)u.bh.n64;
56173   }else{
56174     rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
56175     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
56176     if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
56177       goto too_big;
56178     }
56179   }
56180   if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
56181     goto no_mem;
56182   }
56183   pOut->n = u.bh.n;
56184   MemSetTypeFlag(pOut, MEM_Blob);
56185   if( u.bh.pC->isIndex ){
56186     rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
56187   }else{
56188     rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
56189   }
56190   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
56191   UPDATE_MAX_BLOBSIZE(pOut);
56192   break;
56193 }
56194
56195 /* Opcode: Rowid P1 P2 * * *
56196 **
56197 ** Store in register P2 an integer which is the key of the table entry that
56198 ** P1 is currently point to.
56199 **
56200 ** P1 can be either an ordinary table or a virtual table.  There used to
56201 ** be a separate OP_VRowid opcode for use with virtual tables, but this
56202 ** one opcode now works for both table types.
56203 */
56204 case OP_Rowid: {                 /* out2-prerelease */
56205 #if 0  /* local variables moved into u.bi */
56206   VdbeCursor *pC;
56207   i64 v;
56208   sqlite3_vtab *pVtab;
56209   const sqlite3_module *pModule;
56210 #endif /* local variables moved into u.bi */
56211
56212   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56213   u.bi.pC = p->apCsr[pOp->p1];
56214   assert( u.bi.pC!=0 );
56215   assert( u.bi.pC->pseudoTableReg==0 );
56216   if( u.bi.pC->nullRow ){
56217     pOut->flags = MEM_Null;
56218     break;
56219   }else if( u.bi.pC->deferredMoveto ){
56220     u.bi.v = u.bi.pC->movetoTarget;
56221 #ifndef SQLITE_OMIT_VIRTUALTABLE
56222   }else if( u.bi.pC->pVtabCursor ){
56223     u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
56224     u.bi.pModule = u.bi.pVtab->pModule;
56225     assert( u.bi.pModule->xRowid );
56226     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
56227     rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
56228     sqlite3DbFree(db, p->zErrMsg);
56229     p->zErrMsg = u.bi.pVtab->zErrMsg;
56230     u.bi.pVtab->zErrMsg = 0;
56231     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
56232 #endif /* SQLITE_OMIT_VIRTUALTABLE */
56233   }else{
56234     assert( u.bi.pC->pCursor!=0 );
56235     rc = sqlite3VdbeCursorMoveto(u.bi.pC);
56236     if( rc ) goto abort_due_to_error;
56237     if( u.bi.pC->rowidIsValid ){
56238       u.bi.v = u.bi.pC->lastRowid;
56239     }else{
56240       rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
56241       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
56242     }
56243   }
56244   pOut->u.i = u.bi.v;
56245   break;
56246 }
56247
56248 /* Opcode: NullRow P1 * * * *
56249 **
56250 ** Move the cursor P1 to a null row.  Any OP_Column operations
56251 ** that occur while the cursor is on the null row will always
56252 ** write a NULL.
56253 */
56254 case OP_NullRow: {
56255 #if 0  /* local variables moved into u.bj */
56256   VdbeCursor *pC;
56257 #endif /* local variables moved into u.bj */
56258
56259   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56260   u.bj.pC = p->apCsr[pOp->p1];
56261   assert( u.bj.pC!=0 );
56262   u.bj.pC->nullRow = 1;
56263   u.bj.pC->rowidIsValid = 0;
56264   if( u.bj.pC->pCursor ){
56265     sqlite3BtreeClearCursor(u.bj.pC->pCursor);
56266   }
56267   break;
56268 }
56269
56270 /* Opcode: Last P1 P2 * * *
56271 **
56272 ** The next use of the Rowid or Column or Next instruction for P1 
56273 ** will refer to the last entry in the database table or index.
56274 ** If the table or index is empty and P2>0, then jump immediately to P2.
56275 ** If P2 is 0 or if the table or index is not empty, fall through
56276 ** to the following instruction.
56277 */
56278 case OP_Last: {        /* jump */
56279 #if 0  /* local variables moved into u.bk */
56280   VdbeCursor *pC;
56281   BtCursor *pCrsr;
56282   int res;
56283 #endif /* local variables moved into u.bk */
56284
56285   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56286   u.bk.pC = p->apCsr[pOp->p1];
56287   assert( u.bk.pC!=0 );
56288   u.bk.pCrsr = u.bk.pC->pCursor;
56289   if( u.bk.pCrsr==0 ){
56290     u.bk.res = 1;
56291   }else{
56292     rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
56293   }
56294   u.bk.pC->nullRow = (u8)u.bk.res;
56295   u.bk.pC->deferredMoveto = 0;
56296   u.bk.pC->rowidIsValid = 0;
56297   u.bk.pC->cacheStatus = CACHE_STALE;
56298   if( pOp->p2>0 && u.bk.res ){
56299     pc = pOp->p2 - 1;
56300   }
56301   break;
56302 }
56303
56304
56305 /* Opcode: Sort P1 P2 * * *
56306 **
56307 ** This opcode does exactly the same thing as OP_Rewind except that
56308 ** it increments an undocumented global variable used for testing.
56309 **
56310 ** Sorting is accomplished by writing records into a sorting index,
56311 ** then rewinding that index and playing it back from beginning to
56312 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
56313 ** rewinding so that the global variable will be incremented and
56314 ** regression tests can determine whether or not the optimizer is
56315 ** correctly optimizing out sorts.
56316 */
56317 case OP_Sort: {        /* jump */
56318 #ifdef SQLITE_TEST
56319   sqlite3_sort_count++;
56320   sqlite3_search_count--;
56321 #endif
56322   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
56323   /* Fall through into OP_Rewind */
56324 }
56325 /* Opcode: Rewind P1 P2 * * *
56326 **
56327 ** The next use of the Rowid or Column or Next instruction for P1 
56328 ** will refer to the first entry in the database table or index.
56329 ** If the table or index is empty and P2>0, then jump immediately to P2.
56330 ** If P2 is 0 or if the table or index is not empty, fall through
56331 ** to the following instruction.
56332 */
56333 case OP_Rewind: {        /* jump */
56334 #if 0  /* local variables moved into u.bl */
56335   VdbeCursor *pC;
56336   BtCursor *pCrsr;
56337   int res;
56338 #endif /* local variables moved into u.bl */
56339
56340   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56341   u.bl.pC = p->apCsr[pOp->p1];
56342   assert( u.bl.pC!=0 );
56343   if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
56344     rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
56345     u.bl.pC->atFirst = u.bl.res==0 ?1:0;
56346     u.bl.pC->deferredMoveto = 0;
56347     u.bl.pC->cacheStatus = CACHE_STALE;
56348     u.bl.pC->rowidIsValid = 0;
56349   }else{
56350     u.bl.res = 1;
56351   }
56352   u.bl.pC->nullRow = (u8)u.bl.res;
56353   assert( pOp->p2>0 && pOp->p2<p->nOp );
56354   if( u.bl.res ){
56355     pc = pOp->p2 - 1;
56356   }
56357   break;
56358 }
56359
56360 /* Opcode: Next P1 P2 * * *
56361 **
56362 ** Advance cursor P1 so that it points to the next key/data pair in its
56363 ** table or index.  If there are no more key/value pairs then fall through
56364 ** to the following instruction.  But if the cursor advance was successful,
56365 ** jump immediately to P2.
56366 **
56367 ** The P1 cursor must be for a real table, not a pseudo-table.
56368 **
56369 ** See also: Prev
56370 */
56371 /* Opcode: Prev P1 P2 * * *
56372 **
56373 ** Back up cursor P1 so that it points to the previous key/data pair in its
56374 ** table or index.  If there is no previous key/value pairs then fall through
56375 ** to the following instruction.  But if the cursor backup was successful,
56376 ** jump immediately to P2.
56377 **
56378 ** The P1 cursor must be for a real table, not a pseudo-table.
56379 */
56380 case OP_Prev:          /* jump */
56381 case OP_Next: {        /* jump */
56382 #if 0  /* local variables moved into u.bm */
56383   VdbeCursor *pC;
56384   BtCursor *pCrsr;
56385   int res;
56386 #endif /* local variables moved into u.bm */
56387
56388   CHECK_FOR_INTERRUPT;
56389   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56390   u.bm.pC = p->apCsr[pOp->p1];
56391   if( u.bm.pC==0 ){
56392     break;  /* See ticket #2273 */
56393   }
56394   u.bm.pCrsr = u.bm.pC->pCursor;
56395   if( u.bm.pCrsr==0 ){
56396     u.bm.pC->nullRow = 1;
56397     break;
56398   }
56399   u.bm.res = 1;
56400   assert( u.bm.pC->deferredMoveto==0 );
56401   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
56402                               sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
56403   u.bm.pC->nullRow = (u8)u.bm.res;
56404   u.bm.pC->cacheStatus = CACHE_STALE;
56405   if( u.bm.res==0 ){
56406     pc = pOp->p2 - 1;
56407     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
56408 #ifdef SQLITE_TEST
56409     sqlite3_search_count++;
56410 #endif
56411   }
56412   u.bm.pC->rowidIsValid = 0;
56413   break;
56414 }
56415
56416 /* Opcode: IdxInsert P1 P2 P3 * P5
56417 **
56418 ** Register P2 holds a SQL index key made using the
56419 ** MakeRecord instructions.  This opcode writes that key
56420 ** into the index P1.  Data for the entry is nil.
56421 **
56422 ** P3 is a flag that provides a hint to the b-tree layer that this
56423 ** insert is likely to be an append.
56424 **
56425 ** This instruction only works for indices.  The equivalent instruction
56426 ** for tables is OP_Insert.
56427 */
56428 case OP_IdxInsert: {        /* in2 */
56429 #if 0  /* local variables moved into u.bn */
56430   VdbeCursor *pC;
56431   BtCursor *pCrsr;
56432   int nKey;
56433   const char *zKey;
56434 #endif /* local variables moved into u.bn */
56435
56436   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56437   u.bn.pC = p->apCsr[pOp->p1];
56438   assert( u.bn.pC!=0 );
56439   pIn2 = &aMem[pOp->p2];
56440   assert( pIn2->flags & MEM_Blob );
56441   u.bn.pCrsr = u.bn.pC->pCursor;
56442   if( ALWAYS(u.bn.pCrsr!=0) ){
56443     assert( u.bn.pC->isTable==0 );
56444     rc = ExpandBlob(pIn2);
56445     if( rc==SQLITE_OK ){
56446       u.bn.nKey = pIn2->n;
56447       u.bn.zKey = pIn2->z;
56448       rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
56449           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
56450       );
56451       assert( u.bn.pC->deferredMoveto==0 );
56452       u.bn.pC->cacheStatus = CACHE_STALE;
56453     }
56454   }
56455   break;
56456 }
56457
56458 /* Opcode: IdxDelete P1 P2 P3 * *
56459 **
56460 ** The content of P3 registers starting at register P2 form
56461 ** an unpacked index key. This opcode removes that entry from the 
56462 ** index opened by cursor P1.
56463 */
56464 case OP_IdxDelete: {
56465 #if 0  /* local variables moved into u.bo */
56466   VdbeCursor *pC;
56467   BtCursor *pCrsr;
56468   int res;
56469   UnpackedRecord r;
56470 #endif /* local variables moved into u.bo */
56471
56472   assert( pOp->p3>0 );
56473   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
56474   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56475   u.bo.pC = p->apCsr[pOp->p1];
56476   assert( u.bo.pC!=0 );
56477   u.bo.pCrsr = u.bo.pC->pCursor;
56478   if( ALWAYS(u.bo.pCrsr!=0) ){
56479     u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
56480     u.bo.r.nField = (u16)pOp->p3;
56481     u.bo.r.flags = 0;
56482     u.bo.r.aMem = &aMem[pOp->p2];
56483     rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
56484     if( rc==SQLITE_OK && u.bo.res==0 ){
56485       rc = sqlite3BtreeDelete(u.bo.pCrsr);
56486     }
56487     assert( u.bo.pC->deferredMoveto==0 );
56488     u.bo.pC->cacheStatus = CACHE_STALE;
56489   }
56490   break;
56491 }
56492
56493 /* Opcode: IdxRowid P1 P2 * * *
56494 **
56495 ** Write into register P2 an integer which is the last entry in the record at
56496 ** the end of the index key pointed to by cursor P1.  This integer should be
56497 ** the rowid of the table entry to which this index entry points.
56498 **
56499 ** See also: Rowid, MakeRecord.
56500 */
56501 case OP_IdxRowid: {              /* out2-prerelease */
56502 #if 0  /* local variables moved into u.bp */
56503   BtCursor *pCrsr;
56504   VdbeCursor *pC;
56505   i64 rowid;
56506 #endif /* local variables moved into u.bp */
56507
56508   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56509   u.bp.pC = p->apCsr[pOp->p1];
56510   assert( u.bp.pC!=0 );
56511   u.bp.pCrsr = u.bp.pC->pCursor;
56512   pOut->flags = MEM_Null;
56513   if( ALWAYS(u.bp.pCrsr!=0) ){
56514     rc = sqlite3VdbeCursorMoveto(u.bp.pC);
56515     if( NEVER(rc) ) goto abort_due_to_error;
56516     assert( u.bp.pC->deferredMoveto==0 );
56517     assert( u.bp.pC->isTable==0 );
56518     if( !u.bp.pC->nullRow ){
56519       rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
56520       if( rc!=SQLITE_OK ){
56521         goto abort_due_to_error;
56522       }
56523       pOut->u.i = u.bp.rowid;
56524       pOut->flags = MEM_Int;
56525     }
56526   }
56527   break;
56528 }
56529
56530 /* Opcode: IdxGE P1 P2 P3 P4 P5
56531 **
56532 ** The P4 register values beginning with P3 form an unpacked index 
56533 ** key that omits the ROWID.  Compare this key value against the index 
56534 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
56535 **
56536 ** If the P1 index entry is greater than or equal to the key value
56537 ** then jump to P2.  Otherwise fall through to the next instruction.
56538 **
56539 ** If P5 is non-zero then the key value is increased by an epsilon 
56540 ** prior to the comparison.  This make the opcode work like IdxGT except
56541 ** that if the key from register P3 is a prefix of the key in the cursor,
56542 ** the result is false whereas it would be true with IdxGT.
56543 */
56544 /* Opcode: IdxLT P1 P2 P3 * P5
56545 **
56546 ** The P4 register values beginning with P3 form an unpacked index 
56547 ** key that omits the ROWID.  Compare this key value against the index 
56548 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
56549 **
56550 ** If the P1 index entry is less than the key value then jump to P2.
56551 ** Otherwise fall through to the next instruction.
56552 **
56553 ** If P5 is non-zero then the key value is increased by an epsilon prior 
56554 ** to the comparison.  This makes the opcode work like IdxLE.
56555 */
56556 case OP_IdxLT:          /* jump */
56557 case OP_IdxGE: {        /* jump */
56558 #if 0  /* local variables moved into u.bq */
56559   VdbeCursor *pC;
56560   int res;
56561   UnpackedRecord r;
56562 #endif /* local variables moved into u.bq */
56563
56564   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56565   u.bq.pC = p->apCsr[pOp->p1];
56566   assert( u.bq.pC!=0 );
56567   if( ALWAYS(u.bq.pC->pCursor!=0) ){
56568     assert( u.bq.pC->deferredMoveto==0 );
56569     assert( pOp->p5==0 || pOp->p5==1 );
56570     assert( pOp->p4type==P4_INT32 );
56571     u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
56572     u.bq.r.nField = (u16)pOp->p4.i;
56573     if( pOp->p5 ){
56574       u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
56575     }else{
56576       u.bq.r.flags = UNPACKED_IGNORE_ROWID;
56577     }
56578     u.bq.r.aMem = &aMem[pOp->p3];
56579     rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
56580     if( pOp->opcode==OP_IdxLT ){
56581       u.bq.res = -u.bq.res;
56582     }else{
56583       assert( pOp->opcode==OP_IdxGE );
56584       u.bq.res++;
56585     }
56586     if( u.bq.res>0 ){
56587       pc = pOp->p2 - 1 ;
56588     }
56589   }
56590   break;
56591 }
56592
56593 /* Opcode: Destroy P1 P2 P3 * *
56594 **
56595 ** Delete an entire database table or index whose root page in the database
56596 ** file is given by P1.
56597 **
56598 ** The table being destroyed is in the main database file if P3==0.  If
56599 ** P3==1 then the table to be clear is in the auxiliary database file
56600 ** that is used to store tables create using CREATE TEMPORARY TABLE.
56601 **
56602 ** If AUTOVACUUM is enabled then it is possible that another root page
56603 ** might be moved into the newly deleted root page in order to keep all
56604 ** root pages contiguous at the beginning of the database.  The former
56605 ** value of the root page that moved - its value before the move occurred -
56606 ** is stored in register P2.  If no page 
56607 ** movement was required (because the table being dropped was already 
56608 ** the last one in the database) then a zero is stored in register P2.
56609 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
56610 **
56611 ** See also: Clear
56612 */
56613 case OP_Destroy: {     /* out2-prerelease */
56614 #if 0  /* local variables moved into u.br */
56615   int iMoved;
56616   int iCnt;
56617   Vdbe *pVdbe;
56618   int iDb;
56619 #endif /* local variables moved into u.br */
56620 #ifndef SQLITE_OMIT_VIRTUALTABLE
56621   u.br.iCnt = 0;
56622   for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
56623     if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
56624       u.br.iCnt++;
56625     }
56626   }
56627 #else
56628   u.br.iCnt = db->activeVdbeCnt;
56629 #endif
56630   pOut->flags = MEM_Null;
56631   if( u.br.iCnt>1 ){
56632     rc = SQLITE_LOCKED;
56633     p->errorAction = OE_Abort;
56634   }else{
56635     u.br.iDb = pOp->p3;
56636     assert( u.br.iCnt==1 );
56637     assert( (p->btreeMask & (1<<u.br.iDb))!=0 );
56638     rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
56639     pOut->flags = MEM_Int;
56640     pOut->u.i = u.br.iMoved;
56641 #ifndef SQLITE_OMIT_AUTOVACUUM
56642     if( rc==SQLITE_OK && u.br.iMoved!=0 ){
56643       sqlite3RootPageMoved(&db->aDb[u.br.iDb], u.br.iMoved, pOp->p1);
56644       resetSchemaOnFault = 1;
56645     }
56646 #endif
56647   }
56648   break;
56649 }
56650
56651 /* Opcode: Clear P1 P2 P3
56652 **
56653 ** Delete all contents of the database table or index whose root page
56654 ** in the database file is given by P1.  But, unlike Destroy, do not
56655 ** remove the table or index from the database file.
56656 **
56657 ** The table being clear is in the main database file if P2==0.  If
56658 ** P2==1 then the table to be clear is in the auxiliary database file
56659 ** that is used to store tables create using CREATE TEMPORARY TABLE.
56660 **
56661 ** If the P3 value is non-zero, then the table referred to must be an
56662 ** intkey table (an SQL table, not an index). In this case the row change 
56663 ** count is incremented by the number of rows in the table being cleared. 
56664 ** If P3 is greater than zero, then the value stored in register P3 is
56665 ** also incremented by the number of rows in the table being cleared.
56666 **
56667 ** See also: Destroy
56668 */
56669 case OP_Clear: {
56670 #if 0  /* local variables moved into u.bs */
56671   int nChange;
56672 #endif /* local variables moved into u.bs */
56673
56674   u.bs.nChange = 0;
56675   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
56676   rc = sqlite3BtreeClearTable(
56677       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
56678   );
56679   if( pOp->p3 ){
56680     p->nChange += u.bs.nChange;
56681     if( pOp->p3>0 ){
56682       aMem[pOp->p3].u.i += u.bs.nChange;
56683     }
56684   }
56685   break;
56686 }
56687
56688 /* Opcode: CreateTable P1 P2 * * *
56689 **
56690 ** Allocate a new table in the main database file if P1==0 or in the
56691 ** auxiliary database file if P1==1 or in an attached database if
56692 ** P1>1.  Write the root page number of the new table into
56693 ** register P2
56694 **
56695 ** The difference between a table and an index is this:  A table must
56696 ** have a 4-byte integer key and can have arbitrary data.  An index
56697 ** has an arbitrary key but no data.
56698 **
56699 ** See also: CreateIndex
56700 */
56701 /* Opcode: CreateIndex P1 P2 * * *
56702 **
56703 ** Allocate a new index in the main database file if P1==0 or in the
56704 ** auxiliary database file if P1==1 or in an attached database if
56705 ** P1>1.  Write the root page number of the new table into
56706 ** register P2.
56707 **
56708 ** See documentation on OP_CreateTable for additional information.
56709 */
56710 case OP_CreateIndex:            /* out2-prerelease */
56711 case OP_CreateTable: {          /* out2-prerelease */
56712 #if 0  /* local variables moved into u.bt */
56713   int pgno;
56714   int flags;
56715   Db *pDb;
56716 #endif /* local variables moved into u.bt */
56717
56718   u.bt.pgno = 0;
56719   assert( pOp->p1>=0 && pOp->p1<db->nDb );
56720   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
56721   u.bt.pDb = &db->aDb[pOp->p1];
56722   assert( u.bt.pDb->pBt!=0 );
56723   if( pOp->opcode==OP_CreateTable ){
56724     /* u.bt.flags = BTREE_INTKEY; */
56725     u.bt.flags = BTREE_LEAFDATA|BTREE_INTKEY;
56726   }else{
56727     u.bt.flags = BTREE_ZERODATA;
56728   }
56729   rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
56730   pOut->u.i = u.bt.pgno;
56731   break;
56732 }
56733
56734 /* Opcode: ParseSchema P1 P2 * P4 *
56735 **
56736 ** Read and parse all entries from the SQLITE_MASTER table of database P1
56737 ** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
56738 ** the parsing if P2 is true.  If P2 is false, then this routine is a
56739 ** no-op if the schema is not currently loaded.  In other words, if P2
56740 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
56741 ** schema is already loaded into the symbol table.
56742 **
56743 ** This opcode invokes the parser to create a new virtual machine,
56744 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
56745 */
56746 case OP_ParseSchema: {
56747 #if 0  /* local variables moved into u.bu */
56748   int iDb;
56749   const char *zMaster;
56750   char *zSql;
56751   InitData initData;
56752 #endif /* local variables moved into u.bu */
56753
56754   u.bu.iDb = pOp->p1;
56755   assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
56756
56757   /* If pOp->p2 is 0, then this opcode is being executed to read a
56758   ** single row, for example the row corresponding to a new index
56759   ** created by this VDBE, from the sqlite_master table. It only
56760   ** does this if the corresponding in-memory schema is currently
56761   ** loaded. Otherwise, the new index definition can be loaded along
56762   ** with the rest of the schema when it is required.
56763   **
56764   ** Although the mutex on the BtShared object that corresponds to
56765   ** database u.bu.iDb (the database containing the sqlite_master table
56766   ** read by this instruction) is currently held, it is necessary to
56767   ** obtain the mutexes on all attached databases before checking if
56768   ** the schema of u.bu.iDb is loaded. This is because, at the start of
56769   ** the sqlite3_exec() call below, SQLite will invoke
56770   ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
56771   ** u.bu.iDb mutex may be temporarily released to avoid deadlock. If
56772   ** this happens, then some other thread may delete the in-memory
56773   ** schema of database u.bu.iDb before the SQL statement runs. The schema
56774   ** will not be reloaded becuase the db->init.busy flag is set. This
56775   ** can result in a "no such table: sqlite_master" or "malformed
56776   ** database schema" error being returned to the user.
56777   */
56778   assert( sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
56779   sqlite3BtreeEnterAll(db);
56780   if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){
56781     u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
56782     u.bu.initData.db = db;
56783     u.bu.initData.iDb = pOp->p1;
56784     u.bu.initData.pzErrMsg = &p->zErrMsg;
56785     u.bu.zSql = sqlite3MPrintf(db,
56786        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
56787        db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
56788     if( u.bu.zSql==0 ){
56789       rc = SQLITE_NOMEM;
56790     }else{
56791       (void)sqlite3SafetyOff(db);
56792       assert( db->init.busy==0 );
56793       db->init.busy = 1;
56794       u.bu.initData.rc = SQLITE_OK;
56795       assert( !db->mallocFailed );
56796       rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
56797       if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
56798       sqlite3DbFree(db, u.bu.zSql);
56799       db->init.busy = 0;
56800       (void)sqlite3SafetyOn(db);
56801     }
56802   }
56803   sqlite3BtreeLeaveAll(db);
56804   if( rc==SQLITE_NOMEM ){
56805     goto no_mem;
56806   }
56807   break;
56808 }
56809
56810 #if !defined(SQLITE_OMIT_ANALYZE)
56811 /* Opcode: LoadAnalysis P1 * * * *
56812 **
56813 ** Read the sqlite_stat1 table for database P1 and load the content
56814 ** of that table into the internal index hash table.  This will cause
56815 ** the analysis to be used when preparing all subsequent queries.
56816 */
56817 case OP_LoadAnalysis: {
56818   assert( pOp->p1>=0 && pOp->p1<db->nDb );
56819   rc = sqlite3AnalysisLoad(db, pOp->p1);
56820   break;  
56821 }
56822 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
56823
56824 /* Opcode: DropTable P1 * * P4 *
56825 **
56826 ** Remove the internal (in-memory) data structures that describe
56827 ** the table named P4 in database P1.  This is called after a table
56828 ** is dropped in order to keep the internal representation of the
56829 ** schema consistent with what is on disk.
56830 */
56831 case OP_DropTable: {
56832   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
56833   break;
56834 }
56835
56836 /* Opcode: DropIndex P1 * * P4 *
56837 **
56838 ** Remove the internal (in-memory) data structures that describe
56839 ** the index named P4 in database P1.  This is called after an index
56840 ** is dropped in order to keep the internal representation of the
56841 ** schema consistent with what is on disk.
56842 */
56843 case OP_DropIndex: {
56844   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
56845   break;
56846 }
56847
56848 /* Opcode: DropTrigger P1 * * P4 *
56849 **
56850 ** Remove the internal (in-memory) data structures that describe
56851 ** the trigger named P4 in database P1.  This is called after a trigger
56852 ** is dropped in order to keep the internal representation of the
56853 ** schema consistent with what is on disk.
56854 */
56855 case OP_DropTrigger: {
56856   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
56857   break;
56858 }
56859
56860
56861 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
56862 /* Opcode: IntegrityCk P1 P2 P3 * P5
56863 **
56864 ** Do an analysis of the currently open database.  Store in
56865 ** register P1 the text of an error message describing any problems.
56866 ** If no problems are found, store a NULL in register P1.
56867 **
56868 ** The register P3 contains the maximum number of allowed errors.
56869 ** At most reg(P3) errors will be reported.
56870 ** In other words, the analysis stops as soon as reg(P1) errors are 
56871 ** seen.  Reg(P1) is updated with the number of errors remaining.
56872 **
56873 ** The root page numbers of all tables in the database are integer
56874 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
56875 ** total.
56876 **
56877 ** If P5 is not zero, the check is done on the auxiliary database
56878 ** file, not the main database file.
56879 **
56880 ** This opcode is used to implement the integrity_check pragma.
56881 */
56882 case OP_IntegrityCk: {
56883 #if 0  /* local variables moved into u.bv */
56884   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
56885   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
56886   int j;          /* Loop counter */
56887   int nErr;       /* Number of errors reported */
56888   char *z;        /* Text of the error report */
56889   Mem *pnErr;     /* Register keeping track of errors remaining */
56890 #endif /* local variables moved into u.bv */
56891
56892   u.bv.nRoot = pOp->p2;
56893   assert( u.bv.nRoot>0 );
56894   u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
56895   if( u.bv.aRoot==0 ) goto no_mem;
56896   assert( pOp->p3>0 && pOp->p3<=p->nMem );
56897   u.bv.pnErr = &aMem[pOp->p3];
56898   assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
56899   assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
56900   pIn1 = &aMem[pOp->p1];
56901   for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
56902     u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
56903   }
56904   u.bv.aRoot[u.bv.j] = 0;
56905   assert( pOp->p5<db->nDb );
56906   assert( (p->btreeMask & (1<<pOp->p5))!=0 );
56907   u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
56908                                  (int)u.bv.pnErr->u.i, &u.bv.nErr);
56909   sqlite3DbFree(db, u.bv.aRoot);
56910   u.bv.pnErr->u.i -= u.bv.nErr;
56911   sqlite3VdbeMemSetNull(pIn1);
56912   if( u.bv.nErr==0 ){
56913     assert( u.bv.z==0 );
56914   }else if( u.bv.z==0 ){
56915     goto no_mem;
56916   }else{
56917     sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
56918   }
56919   UPDATE_MAX_BLOBSIZE(pIn1);
56920   sqlite3VdbeChangeEncoding(pIn1, encoding);
56921   break;
56922 }
56923 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56924
56925 /* Opcode: RowSetAdd P1 P2 * * *
56926 **
56927 ** Insert the integer value held by register P2 into a boolean index
56928 ** held in register P1.
56929 **
56930 ** An assertion fails if P2 is not an integer.
56931 */
56932 case OP_RowSetAdd: {       /* in1, in2 */
56933   pIn1 = &aMem[pOp->p1];
56934   pIn2 = &aMem[pOp->p2];
56935   assert( (pIn2->flags & MEM_Int)!=0 );
56936   if( (pIn1->flags & MEM_RowSet)==0 ){
56937     sqlite3VdbeMemSetRowSet(pIn1);
56938     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
56939   }
56940   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
56941   break;
56942 }
56943
56944 /* Opcode: RowSetRead P1 P2 P3 * *
56945 **
56946 ** Extract the smallest value from boolean index P1 and put that value into
56947 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
56948 ** unchanged and jump to instruction P2.
56949 */
56950 case OP_RowSetRead: {       /* jump, in1, out3 */
56951 #if 0  /* local variables moved into u.bw */
56952   i64 val;
56953 #endif /* local variables moved into u.bw */
56954   CHECK_FOR_INTERRUPT;
56955   pIn1 = &aMem[pOp->p1];
56956   if( (pIn1->flags & MEM_RowSet)==0
56957    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
56958   ){
56959     /* The boolean index is empty */
56960     sqlite3VdbeMemSetNull(pIn1);
56961     pc = pOp->p2 - 1;
56962   }else{
56963     /* A value was pulled from the index */
56964     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
56965   }
56966   break;
56967 }
56968
56969 /* Opcode: RowSetTest P1 P2 P3 P4
56970 **
56971 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
56972 ** contains a RowSet object and that RowSet object contains
56973 ** the value held in P3, jump to register P2. Otherwise, insert the
56974 ** integer in P3 into the RowSet and continue on to the
56975 ** next opcode.
56976 **
56977 ** The RowSet object is optimized for the case where successive sets
56978 ** of integers, where each set contains no duplicates. Each set
56979 ** of values is identified by a unique P4 value. The first set
56980 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
56981 ** non-negative.  For non-negative values of P4 only the lower 4
56982 ** bits are significant.
56983 **
56984 ** This allows optimizations: (a) when P4==0 there is no need to test
56985 ** the rowset object for P3, as it is guaranteed not to contain it,
56986 ** (b) when P4==-1 there is no need to insert the value, as it will
56987 ** never be tested for, and (c) when a value that is part of set X is
56988 ** inserted, there is no need to search to see if the same value was
56989 ** previously inserted as part of set X (only if it was previously
56990 ** inserted as part of some other set).
56991 */
56992 case OP_RowSetTest: {                     /* jump, in1, in3 */
56993 #if 0  /* local variables moved into u.bx */
56994   int iSet;
56995   int exists;
56996 #endif /* local variables moved into u.bx */
56997
56998   pIn1 = &aMem[pOp->p1];
56999   pIn3 = &aMem[pOp->p3];
57000   u.bx.iSet = pOp->p4.i;
57001   assert( pIn3->flags&MEM_Int );
57002
57003   /* If there is anything other than a rowset object in memory cell P1,
57004   ** delete it now and initialize P1 with an empty rowset
57005   */
57006   if( (pIn1->flags & MEM_RowSet)==0 ){
57007     sqlite3VdbeMemSetRowSet(pIn1);
57008     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
57009   }
57010
57011   assert( pOp->p4type==P4_INT32 );
57012   assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
57013   if( u.bx.iSet ){
57014     u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
57015                                (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
57016                                pIn3->u.i);
57017     if( u.bx.exists ){
57018       pc = pOp->p2 - 1;
57019       break;
57020     }
57021   }
57022   if( u.bx.iSet>=0 ){
57023     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
57024   }
57025   break;
57026 }
57027
57028
57029 #ifndef SQLITE_OMIT_TRIGGER
57030
57031 /* Opcode: Program P1 P2 P3 P4 *
57032 **
57033 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
57034 **
57035 ** P1 contains the address of the memory cell that contains the first memory 
57036 ** cell in an array of values used as arguments to the sub-program. P2 
57037 ** contains the address to jump to if the sub-program throws an IGNORE 
57038 ** exception using the RAISE() function. Register P3 contains the address 
57039 ** of a memory cell in this (the parent) VM that is used to allocate the 
57040 ** memory required by the sub-vdbe at runtime.
57041 **
57042 ** P4 is a pointer to the VM containing the trigger program.
57043 */
57044 case OP_Program: {        /* jump */
57045 #if 0  /* local variables moved into u.by */
57046   int nMem;               /* Number of memory registers for sub-program */
57047   int nByte;              /* Bytes of runtime space required for sub-program */
57048   Mem *pRt;               /* Register to allocate runtime space */
57049   Mem *pMem;              /* Used to iterate through memory cells */
57050   Mem *pEnd;              /* Last memory cell in new array */
57051   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
57052   SubProgram *pProgram;   /* Sub-program to execute */
57053   void *t;                /* Token identifying trigger */
57054 #endif /* local variables moved into u.by */
57055
57056   u.by.pProgram = pOp->p4.pProgram;
57057   u.by.pRt = &aMem[pOp->p3];
57058   assert( u.by.pProgram->nOp>0 );
57059
57060   /* If the p5 flag is clear, then recursive invocation of triggers is
57061   ** disabled for backwards compatibility (p5 is set if this sub-program
57062   ** is really a trigger, not a foreign key action, and the flag set
57063   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
57064   **
57065   ** It is recursive invocation of triggers, at the SQL level, that is
57066   ** disabled. In some cases a single trigger may generate more than one
57067   ** SubProgram (if the trigger may be executed with more than one different
57068   ** ON CONFLICT algorithm). SubProgram structures associated with a
57069   ** single trigger all have the same value for the SubProgram.token
57070   ** variable.  */
57071   if( pOp->p5 ){
57072     u.by.t = u.by.pProgram->token;
57073     for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
57074     if( u.by.pFrame ) break;
57075   }
57076
57077   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
57078     rc = SQLITE_ERROR;
57079     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
57080     break;
57081   }
57082
57083   /* Register u.by.pRt is used to store the memory required to save the state
57084   ** of the current program, and the memory required at runtime to execute
57085   ** the trigger program. If this trigger has been fired before, then u.by.pRt
57086   ** is already allocated. Otherwise, it must be initialized.  */
57087   if( (u.by.pRt->flags&MEM_Frame)==0 ){
57088     /* SubProgram.nMem is set to the number of memory cells used by the
57089     ** program stored in SubProgram.aOp. As well as these, one memory
57090     ** cell is required for each cursor used by the program. Set local
57091     ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
57092     */
57093     u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
57094     u.by.nByte = ROUND8(sizeof(VdbeFrame))
57095               + u.by.nMem * sizeof(Mem)
57096               + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
57097     u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
57098     if( !u.by.pFrame ){
57099       goto no_mem;
57100     }
57101     sqlite3VdbeMemRelease(u.by.pRt);
57102     u.by.pRt->flags = MEM_Frame;
57103     u.by.pRt->u.pFrame = u.by.pFrame;
57104
57105     u.by.pFrame->v = p;
57106     u.by.pFrame->nChildMem = u.by.nMem;
57107     u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
57108     u.by.pFrame->pc = pc;
57109     u.by.pFrame->aMem = p->aMem;
57110     u.by.pFrame->nMem = p->nMem;
57111     u.by.pFrame->apCsr = p->apCsr;
57112     u.by.pFrame->nCursor = p->nCursor;
57113     u.by.pFrame->aOp = p->aOp;
57114     u.by.pFrame->nOp = p->nOp;
57115     u.by.pFrame->token = u.by.pProgram->token;
57116
57117     u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
57118     for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
57119       u.by.pMem->flags = MEM_Null;
57120       u.by.pMem->db = db;
57121     }
57122   }else{
57123     u.by.pFrame = u.by.pRt->u.pFrame;
57124     assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
57125     assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
57126     assert( pc==u.by.pFrame->pc );
57127   }
57128
57129   p->nFrame++;
57130   u.by.pFrame->pParent = p->pFrame;
57131   u.by.pFrame->lastRowid = db->lastRowid;
57132   u.by.pFrame->nChange = p->nChange;
57133   p->nChange = 0;
57134   p->pFrame = u.by.pFrame;
57135   p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
57136   p->nMem = u.by.pFrame->nChildMem;
57137   p->nCursor = (u16)u.by.pFrame->nChildCsr;
57138   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
57139   p->aOp = aOp = u.by.pProgram->aOp;
57140   p->nOp = u.by.pProgram->nOp;
57141   pc = -1;
57142
57143   break;
57144 }
57145
57146 /* Opcode: Param P1 P2 * * *
57147 **
57148 ** This opcode is only ever present in sub-programs called via the 
57149 ** OP_Program instruction. Copy a value currently stored in a memory 
57150 ** cell of the calling (parent) frame to cell P2 in the current frames 
57151 ** address space. This is used by trigger programs to access the new.* 
57152 ** and old.* values.
57153 **
57154 ** The address of the cell in the parent frame is determined by adding
57155 ** the value of the P1 argument to the value of the P1 argument to the
57156 ** calling OP_Program instruction.
57157 */
57158 case OP_Param: {           /* out2-prerelease */
57159 #if 0  /* local variables moved into u.bz */
57160   VdbeFrame *pFrame;
57161   Mem *pIn;
57162 #endif /* local variables moved into u.bz */
57163   u.bz.pFrame = p->pFrame;
57164   u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
57165   sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
57166   break;
57167 }
57168
57169 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
57170
57171 #ifndef SQLITE_OMIT_FOREIGN_KEY
57172 /* Opcode: FkCounter P1 P2 * * *
57173 **
57174 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
57175 ** If P1 is non-zero, the database constraint counter is incremented 
57176 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
57177 ** statement counter is incremented (immediate foreign key constraints).
57178 */
57179 case OP_FkCounter: {
57180   if( pOp->p1 ){
57181     db->nDeferredCons += pOp->p2;
57182   }else{
57183     p->nFkConstraint += pOp->p2;
57184   }
57185   break;
57186 }
57187
57188 /* Opcode: FkIfZero P1 P2 * * *
57189 **
57190 ** This opcode tests if a foreign key constraint-counter is currently zero.
57191 ** If so, jump to instruction P2. Otherwise, fall through to the next 
57192 ** instruction.
57193 **
57194 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
57195 ** is zero (the one that counts deferred constraint violations). If P1 is
57196 ** zero, the jump is taken if the statement constraint-counter is zero
57197 ** (immediate foreign key constraint violations).
57198 */
57199 case OP_FkIfZero: {         /* jump */
57200   if( pOp->p1 ){
57201     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
57202   }else{
57203     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
57204   }
57205   break;
57206 }
57207 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
57208
57209 #ifndef SQLITE_OMIT_AUTOINCREMENT
57210 /* Opcode: MemMax P1 P2 * * *
57211 **
57212 ** P1 is a register in the root frame of this VM (the root frame is
57213 ** different from the current frame if this instruction is being executed
57214 ** within a sub-program). Set the value of register P1 to the maximum of 
57215 ** its current value and the value in register P2.
57216 **
57217 ** This instruction throws an error if the memory cell is not initially
57218 ** an integer.
57219 */
57220 case OP_MemMax: {        /* in2 */
57221 #if 0  /* local variables moved into u.ca */
57222   Mem *pIn1;
57223   VdbeFrame *pFrame;
57224 #endif /* local variables moved into u.ca */
57225   if( p->pFrame ){
57226     for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
57227     u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
57228   }else{
57229     u.ca.pIn1 = &aMem[pOp->p1];
57230   }
57231   sqlite3VdbeMemIntegerify(u.ca.pIn1);
57232   pIn2 = &aMem[pOp->p2];
57233   sqlite3VdbeMemIntegerify(pIn2);
57234   if( u.ca.pIn1->u.i<pIn2->u.i){
57235     u.ca.pIn1->u.i = pIn2->u.i;
57236   }
57237   break;
57238 }
57239 #endif /* SQLITE_OMIT_AUTOINCREMENT */
57240
57241 /* Opcode: IfPos P1 P2 * * *
57242 **
57243 ** If the value of register P1 is 1 or greater, jump to P2.
57244 **
57245 ** It is illegal to use this instruction on a register that does
57246 ** not contain an integer.  An assertion fault will result if you try.
57247 */
57248 case OP_IfPos: {        /* jump, in1 */
57249   pIn1 = &aMem[pOp->p1];
57250   assert( pIn1->flags&MEM_Int );
57251   if( pIn1->u.i>0 ){
57252      pc = pOp->p2 - 1;
57253   }
57254   break;
57255 }
57256
57257 /* Opcode: IfNeg P1 P2 * * *
57258 **
57259 ** If the value of register P1 is less than zero, jump to P2. 
57260 **
57261 ** It is illegal to use this instruction on a register that does
57262 ** not contain an integer.  An assertion fault will result if you try.
57263 */
57264 case OP_IfNeg: {        /* jump, in1 */
57265   pIn1 = &aMem[pOp->p1];
57266   assert( pIn1->flags&MEM_Int );
57267   if( pIn1->u.i<0 ){
57268      pc = pOp->p2 - 1;
57269   }
57270   break;
57271 }
57272
57273 /* Opcode: IfZero P1 P2 P3 * *
57274 **
57275 ** The register P1 must contain an integer.  Add literal P3 to the
57276 ** value in register P1.  If the result is exactly 0, jump to P2. 
57277 **
57278 ** It is illegal to use this instruction on a register that does
57279 ** not contain an integer.  An assertion fault will result if you try.
57280 */
57281 case OP_IfZero: {        /* jump, in1 */
57282   pIn1 = &aMem[pOp->p1];
57283   assert( pIn1->flags&MEM_Int );
57284   pIn1->u.i += pOp->p3;
57285   if( pIn1->u.i==0 ){
57286      pc = pOp->p2 - 1;
57287   }
57288   break;
57289 }
57290
57291 /* Opcode: AggStep * P2 P3 P4 P5
57292 **
57293 ** Execute the step function for an aggregate.  The
57294 ** function has P5 arguments.   P4 is a pointer to the FuncDef
57295 ** structure that specifies the function.  Use register
57296 ** P3 as the accumulator.
57297 **
57298 ** The P5 arguments are taken from register P2 and its
57299 ** successors.
57300 */
57301 case OP_AggStep: {
57302 #if 0  /* local variables moved into u.cb */
57303   int n;
57304   int i;
57305   Mem *pMem;
57306   Mem *pRec;
57307   sqlite3_context ctx;
57308   sqlite3_value **apVal;
57309 #endif /* local variables moved into u.cb */
57310
57311   u.cb.n = pOp->p5;
57312   assert( u.cb.n>=0 );
57313   u.cb.pRec = &aMem[pOp->p2];
57314   u.cb.apVal = p->apArg;
57315   assert( u.cb.apVal || u.cb.n==0 );
57316   for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
57317     u.cb.apVal[u.cb.i] = u.cb.pRec;
57318     sqlite3VdbeMemStoreType(u.cb.pRec);
57319   }
57320   u.cb.ctx.pFunc = pOp->p4.pFunc;
57321   assert( pOp->p3>0 && pOp->p3<=p->nMem );
57322   u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
57323   u.cb.pMem->n++;
57324   u.cb.ctx.s.flags = MEM_Null;
57325   u.cb.ctx.s.z = 0;
57326   u.cb.ctx.s.zMalloc = 0;
57327   u.cb.ctx.s.xDel = 0;
57328   u.cb.ctx.s.db = db;
57329   u.cb.ctx.isError = 0;
57330   u.cb.ctx.pColl = 0;
57331   if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
57332     assert( pOp>p->aOp );
57333     assert( pOp[-1].p4type==P4_COLLSEQ );
57334     assert( pOp[-1].opcode==OP_CollSeq );
57335     u.cb.ctx.pColl = pOp[-1].p4.pColl;
57336   }
57337   (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal);
57338   if( u.cb.ctx.isError ){
57339     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
57340     rc = u.cb.ctx.isError;
57341   }
57342   sqlite3VdbeMemRelease(&u.cb.ctx.s);
57343   break;
57344 }
57345
57346 /* Opcode: AggFinal P1 P2 * P4 *
57347 **
57348 ** Execute the finalizer function for an aggregate.  P1 is
57349 ** the memory location that is the accumulator for the aggregate.
57350 **
57351 ** P2 is the number of arguments that the step function takes and
57352 ** P4 is a pointer to the FuncDef for this function.  The P2
57353 ** argument is not used by this opcode.  It is only there to disambiguate
57354 ** functions that can take varying numbers of arguments.  The
57355 ** P4 argument is only needed for the degenerate case where
57356 ** the step function was not previously called.
57357 */
57358 case OP_AggFinal: {
57359 #if 0  /* local variables moved into u.cc */
57360   Mem *pMem;
57361 #endif /* local variables moved into u.cc */
57362   assert( pOp->p1>0 && pOp->p1<=p->nMem );
57363   u.cc.pMem = &aMem[pOp->p1];
57364   assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
57365   rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
57366   if( rc ){
57367     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
57368   }
57369   sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
57370   UPDATE_MAX_BLOBSIZE(u.cc.pMem);
57371   if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
57372     goto too_big;
57373   }
57374   break;
57375 }
57376
57377
57378 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
57379 /* Opcode: Vacuum * * * * *
57380 **
57381 ** Vacuum the entire database.  This opcode will cause other virtual
57382 ** machines to be created and run.  It may not be called from within
57383 ** a transaction.
57384 */
57385 case OP_Vacuum: {
57386   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; 
57387   rc = sqlite3RunVacuum(&p->zErrMsg, db);
57388   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57389   break;
57390 }
57391 #endif
57392
57393 #if !defined(SQLITE_OMIT_AUTOVACUUM)
57394 /* Opcode: IncrVacuum P1 P2 * * *
57395 **
57396 ** Perform a single step of the incremental vacuum procedure on
57397 ** the P1 database. If the vacuum has finished, jump to instruction
57398 ** P2. Otherwise, fall through to the next instruction.
57399 */
57400 case OP_IncrVacuum: {        /* jump */
57401 #if 0  /* local variables moved into u.cd */
57402   Btree *pBt;
57403 #endif /* local variables moved into u.cd */
57404
57405   assert( pOp->p1>=0 && pOp->p1<db->nDb );
57406   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
57407   u.cd.pBt = db->aDb[pOp->p1].pBt;
57408   rc = sqlite3BtreeIncrVacuum(u.cd.pBt);
57409   if( rc==SQLITE_DONE ){
57410     pc = pOp->p2 - 1;
57411     rc = SQLITE_OK;
57412   }
57413   break;
57414 }
57415 #endif
57416
57417 /* Opcode: Expire P1 * * * *
57418 **
57419 ** Cause precompiled statements to become expired. An expired statement
57420 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
57421 ** (via sqlite3_step()).
57422 ** 
57423 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
57424 ** then only the currently executing statement is affected. 
57425 */
57426 case OP_Expire: {
57427   if( !pOp->p1 ){
57428     sqlite3ExpirePreparedStatements(db);
57429   }else{
57430     p->expired = 1;
57431   }
57432   break;
57433 }
57434
57435 #ifndef SQLITE_OMIT_SHARED_CACHE
57436 /* Opcode: TableLock P1 P2 P3 P4 *
57437 **
57438 ** Obtain a lock on a particular table. This instruction is only used when
57439 ** the shared-cache feature is enabled. 
57440 **
57441 ** P1 is the index of the database in sqlite3.aDb[] of the database
57442 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
57443 ** a write lock if P3==1.
57444 **
57445 ** P2 contains the root-page of the table to lock.
57446 **
57447 ** P4 contains a pointer to the name of the table being locked. This is only
57448 ** used to generate an error message if the lock cannot be obtained.
57449 */
57450 case OP_TableLock: {
57451   u8 isWriteLock = (u8)pOp->p3;
57452   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
57453     int p1 = pOp->p1; 
57454     assert( p1>=0 && p1<db->nDb );
57455     assert( (p->btreeMask & (1<<p1))!=0 );
57456     assert( isWriteLock==0 || isWriteLock==1 );
57457     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
57458     if( (rc&0xFF)==SQLITE_LOCKED ){
57459       const char *z = pOp->p4.z;
57460       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
57461     }
57462   }
57463   break;
57464 }
57465 #endif /* SQLITE_OMIT_SHARED_CACHE */
57466
57467 #ifndef SQLITE_OMIT_VIRTUALTABLE
57468 /* Opcode: VBegin * * * P4 *
57469 **
57470 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
57471 ** xBegin method for that table.
57472 **
57473 ** Also, whether or not P4 is set, check that this is not being called from
57474 ** within a callback to a virtual table xSync() method. If it is, the error
57475 ** code will be set to SQLITE_LOCKED.
57476 */
57477 case OP_VBegin: {
57478 #if 0  /* local variables moved into u.ce */
57479   VTable *pVTab;
57480 #endif /* local variables moved into u.ce */
57481   u.ce.pVTab = pOp->p4.pVtab;
57482   rc = sqlite3VtabBegin(db, u.ce.pVTab);
57483   if( u.ce.pVTab ){
57484     sqlite3DbFree(db, p->zErrMsg);
57485     p->zErrMsg = u.ce.pVTab->pVtab->zErrMsg;
57486     u.ce.pVTab->pVtab->zErrMsg = 0;
57487   }
57488   break;
57489 }
57490 #endif /* SQLITE_OMIT_VIRTUALTABLE */
57491
57492 #ifndef SQLITE_OMIT_VIRTUALTABLE
57493 /* Opcode: VCreate P1 * * P4 *
57494 **
57495 ** P4 is the name of a virtual table in database P1. Call the xCreate method
57496 ** for that table.
57497 */
57498 case OP_VCreate: {
57499   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
57500   break;
57501 }
57502 #endif /* SQLITE_OMIT_VIRTUALTABLE */
57503
57504 #ifndef SQLITE_OMIT_VIRTUALTABLE
57505 /* Opcode: VDestroy P1 * * P4 *
57506 **
57507 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
57508 ** of that table.
57509 */
57510 case OP_VDestroy: {
57511   p->inVtabMethod = 2;
57512   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
57513   p->inVtabMethod = 0;
57514   break;
57515 }
57516 #endif /* SQLITE_OMIT_VIRTUALTABLE */
57517
57518 #ifndef SQLITE_OMIT_VIRTUALTABLE
57519 /* Opcode: VOpen P1 * * P4 *
57520 **
57521 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
57522 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
57523 ** table and stores that cursor in P1.
57524 */
57525 case OP_VOpen: {
57526 #if 0  /* local variables moved into u.cf */
57527   VdbeCursor *pCur;
57528   sqlite3_vtab_cursor *pVtabCursor;
57529   sqlite3_vtab *pVtab;
57530   sqlite3_module *pModule;
57531 #endif /* local variables moved into u.cf */
57532
57533   u.cf.pCur = 0;
57534   u.cf.pVtabCursor = 0;
57535   u.cf.pVtab = pOp->p4.pVtab->pVtab;
57536   u.cf.pModule = (sqlite3_module *)u.cf.pVtab->pModule;
57537   assert(u.cf.pVtab && u.cf.pModule);
57538   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57539   rc = u.cf.pModule->xOpen(u.cf.pVtab, &u.cf.pVtabCursor);
57540   sqlite3DbFree(db, p->zErrMsg);
57541   p->zErrMsg = u.cf.pVtab->zErrMsg;
57542   u.cf.pVtab->zErrMsg = 0;
57543   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57544   if( SQLITE_OK==rc ){
57545     /* Initialize sqlite3_vtab_cursor base class */
57546     u.cf.pVtabCursor->pVtab = u.cf.pVtab;
57547
57548     /* Initialise vdbe cursor object */
57549     u.cf.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
57550     if( u.cf.pCur ){
57551       u.cf.pCur->pVtabCursor = u.cf.pVtabCursor;
57552       u.cf.pCur->pModule = u.cf.pVtabCursor->pVtab->pModule;
57553     }else{
57554       db->mallocFailed = 1;
57555       u.cf.pModule->xClose(u.cf.pVtabCursor);
57556     }
57557   }
57558   break;
57559 }
57560 #endif /* SQLITE_OMIT_VIRTUALTABLE */
57561
57562 #ifndef SQLITE_OMIT_VIRTUALTABLE
57563 /* Opcode: VFilter P1 P2 P3 P4 *
57564 **
57565 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
57566 ** the filtered result set is empty.
57567 **
57568 ** P4 is either NULL or a string that was generated by the xBestIndex
57569 ** method of the module.  The interpretation of the P4 string is left
57570 ** to the module implementation.
57571 **
57572 ** This opcode invokes the xFilter method on the virtual table specified
57573 ** by P1.  The integer query plan parameter to xFilter is stored in register
57574 ** P3. Register P3+1 stores the argc parameter to be passed to the
57575 ** xFilter method. Registers P3+2..P3+1+argc are the argc
57576 ** additional parameters which are passed to
57577 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
57578 **
57579 ** A jump is made to P2 if the result set after filtering would be empty.
57580 */
57581 case OP_VFilter: {   /* jump */
57582 #if 0  /* local variables moved into u.cg */
57583   int nArg;
57584   int iQuery;
57585   const sqlite3_module *pModule;
57586   Mem *pQuery;
57587   Mem *pArgc;
57588   sqlite3_vtab_cursor *pVtabCursor;
57589   sqlite3_vtab *pVtab;
57590   VdbeCursor *pCur;
57591   int res;
57592   int i;
57593   Mem **apArg;
57594 #endif /* local variables moved into u.cg */
57595
57596   u.cg.pQuery = &aMem[pOp->p3];
57597   u.cg.pArgc = &u.cg.pQuery[1];
57598   u.cg.pCur = p->apCsr[pOp->p1];
57599   REGISTER_TRACE(pOp->p3, u.cg.pQuery);
57600   assert( u.cg.pCur->pVtabCursor );
57601   u.cg.pVtabCursor = u.cg.pCur->pVtabCursor;
57602   u.cg.pVtab = u.cg.pVtabCursor->pVtab;
57603   u.cg.pModule = u.cg.pVtab->pModule;
57604
57605   /* Grab the index number and argc parameters */
57606   assert( (u.cg.pQuery->flags&MEM_Int)!=0 && u.cg.pArgc->flags==MEM_Int );
57607   u.cg.nArg = (int)u.cg.pArgc->u.i;
57608   u.cg.iQuery = (int)u.cg.pQuery->u.i;
57609
57610   /* Invoke the xFilter method */
57611   {
57612     u.cg.res = 0;
57613     u.cg.apArg = p->apArg;
57614     for(u.cg.i = 0; u.cg.i<u.cg.nArg; u.cg.i++){
57615       u.cg.apArg[u.cg.i] = &u.cg.pArgc[u.cg.i+1];
57616       sqlite3VdbeMemStoreType(u.cg.apArg[u.cg.i]);
57617     }
57618
57619     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57620     p->inVtabMethod = 1;
57621     rc = u.cg.pModule->xFilter(u.cg.pVtabCursor, u.cg.iQuery, pOp->p4.z, u.cg.nArg, u.cg.apArg);
57622     p->inVtabMethod = 0;
57623     sqlite3DbFree(db, p->zErrMsg);
57624     p->zErrMsg = u.cg.pVtab->zErrMsg;
57625     u.cg.pVtab->zErrMsg = 0;
57626     if( rc==SQLITE_OK ){
57627       u.cg.res = u.cg.pModule->xEof(u.cg.pVtabCursor);
57628     }
57629     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57630
57631     if( u.cg.res ){
57632       pc = pOp->p2 - 1;
57633     }
57634   }
57635   u.cg.pCur->nullRow = 0;
57636
57637   break;
57638 }
57639 #endif /* SQLITE_OMIT_VIRTUALTABLE */
57640
57641 #ifndef SQLITE_OMIT_VIRTUALTABLE
57642 /* Opcode: VColumn P1 P2 P3 * *
57643 **
57644 ** Store the value of the P2-th column of
57645 ** the row of the virtual-table that the 
57646 ** P1 cursor is pointing to into register P3.
57647 */
57648 case OP_VColumn: {
57649 #if 0  /* local variables moved into u.ch */
57650   sqlite3_vtab *pVtab;
57651   const sqlite3_module *pModule;
57652   Mem *pDest;
57653   sqlite3_context sContext;
57654 #endif /* local variables moved into u.ch */
57655
57656   VdbeCursor *pCur = p->apCsr[pOp->p1];
57657   assert( pCur->pVtabCursor );
57658   assert( pOp->p3>0 && pOp->p3<=p->nMem );
57659   u.ch.pDest = &aMem[pOp->p3];
57660   if( pCur->nullRow ){
57661     sqlite3VdbeMemSetNull(u.ch.pDest);
57662     break;
57663   }
57664   u.ch.pVtab = pCur->pVtabCursor->pVtab;
57665   u.ch.pModule = u.ch.pVtab->pModule;
57666   assert( u.ch.pModule->xColumn );
57667   memset(&u.ch.sContext, 0, sizeof(u.ch.sContext));
57668
57669   /* The output cell may already have a buffer allocated. Move
57670   ** the current contents to u.ch.sContext.s so in case the user-function
57671   ** can use the already allocated buffer instead of allocating a
57672   ** new one.
57673   */
57674   sqlite3VdbeMemMove(&u.ch.sContext.s, u.ch.pDest);
57675   MemSetTypeFlag(&u.ch.sContext.s, MEM_Null);
57676
57677   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57678   rc = u.ch.pModule->xColumn(pCur->pVtabCursor, &u.ch.sContext, pOp->p2);
57679   sqlite3DbFree(db, p->zErrMsg);
57680   p->zErrMsg = u.ch.pVtab->zErrMsg;
57681   u.ch.pVtab->zErrMsg = 0;
57682   if( u.ch.sContext.isError ){
57683     rc = u.ch.sContext.isError;
57684   }
57685
57686   /* Copy the result of the function to the P3 register. We
57687   ** do this regardless of whether or not an error occurred to ensure any
57688   ** dynamic allocation in u.ch.sContext.s (a Mem struct) is  released.
57689   */
57690   sqlite3VdbeChangeEncoding(&u.ch.sContext.s, encoding);
57691   sqlite3VdbeMemMove(u.ch.pDest, &u.ch.sContext.s);
57692   REGISTER_TRACE(pOp->p3, u.ch.pDest);
57693   UPDATE_MAX_BLOBSIZE(u.ch.pDest);
57694
57695   if( sqlite3SafetyOn(db) ){
57696     goto abort_due_to_misuse;
57697   }
57698   if( sqlite3VdbeMemTooBig(u.ch.pDest) ){
57699     goto too_big;
57700   }
57701   break;
57702 }
57703 #endif /* SQLITE_OMIT_VIRTUALTABLE */
57704
57705 #ifndef SQLITE_OMIT_VIRTUALTABLE
57706 /* Opcode: VNext P1 P2 * * *
57707 **
57708 ** Advance virtual table P1 to the next row in its result set and
57709 ** jump to instruction P2.  Or, if the virtual table has reached
57710 ** the end of its result set, then fall through to the next instruction.
57711 */
57712 case OP_VNext: {   /* jump */
57713 #if 0  /* local variables moved into u.ci */
57714   sqlite3_vtab *pVtab;
57715   const sqlite3_module *pModule;
57716   int res;
57717   VdbeCursor *pCur;
57718 #endif /* local variables moved into u.ci */
57719
57720   u.ci.res = 0;
57721   u.ci.pCur = p->apCsr[pOp->p1];
57722   assert( u.ci.pCur->pVtabCursor );
57723   if( u.ci.pCur->nullRow ){
57724     break;
57725   }
57726   u.ci.pVtab = u.ci.pCur->pVtabCursor->pVtab;
57727   u.ci.pModule = u.ci.pVtab->pModule;
57728   assert( u.ci.pModule->xNext );
57729
57730   /* Invoke the xNext() method of the module. There is no way for the
57731   ** underlying implementation to return an error if one occurs during
57732   ** xNext(). Instead, if an error occurs, true is returned (indicating that
57733   ** data is available) and the error code returned when xColumn or
57734   ** some other method is next invoked on the save virtual table cursor.
57735   */
57736   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57737   p->inVtabMethod = 1;
57738   rc = u.ci.pModule->xNext(u.ci.pCur->pVtabCursor);
57739   p->inVtabMethod = 0;
57740   sqlite3DbFree(db, p->zErrMsg);
57741   p->zErrMsg = u.ci.pVtab->zErrMsg;
57742   u.ci.pVtab->zErrMsg = 0;
57743   if( rc==SQLITE_OK ){
57744     u.ci.res = u.ci.pModule->xEof(u.ci.pCur->pVtabCursor);
57745   }
57746   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57747
57748   if( !u.ci.res ){
57749     /* If there is data, jump to P2 */
57750     pc = pOp->p2 - 1;
57751   }
57752   break;
57753 }
57754 #endif /* SQLITE_OMIT_VIRTUALTABLE */
57755
57756 #ifndef SQLITE_OMIT_VIRTUALTABLE
57757 /* Opcode: VRename P1 * * P4 *
57758 **
57759 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
57760 ** This opcode invokes the corresponding xRename method. The value
57761 ** in register P1 is passed as the zName argument to the xRename method.
57762 */
57763 case OP_VRename: {
57764 #if 0  /* local variables moved into u.cj */
57765   sqlite3_vtab *pVtab;
57766   Mem *pName;
57767 #endif /* local variables moved into u.cj */
57768
57769   u.cj.pVtab = pOp->p4.pVtab->pVtab;
57770   u.cj.pName = &aMem[pOp->p1];
57771   assert( u.cj.pVtab->pModule->xRename );
57772   REGISTER_TRACE(pOp->p1, u.cj.pName);
57773   assert( u.cj.pName->flags & MEM_Str );
57774   if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57775   rc = u.cj.pVtab->pModule->xRename(u.cj.pVtab, u.cj.pName->z);
57776   sqlite3DbFree(db, p->zErrMsg);
57777   p->zErrMsg = u.cj.pVtab->zErrMsg;
57778   u.cj.pVtab->zErrMsg = 0;
57779   if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57780
57781   break;
57782 }
57783 #endif
57784
57785 #ifndef SQLITE_OMIT_VIRTUALTABLE
57786 /* Opcode: VUpdate P1 P2 P3 P4 *
57787 **
57788 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
57789 ** This opcode invokes the corresponding xUpdate method. P2 values
57790 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
57791 ** invocation. The value in register (P3+P2-1) corresponds to the 
57792 ** p2th element of the argv array passed to xUpdate.
57793 **
57794 ** The xUpdate method will do a DELETE or an INSERT or both.
57795 ** The argv[0] element (which corresponds to memory cell P3)
57796 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
57797 ** deletion occurs.  The argv[1] element is the rowid of the new 
57798 ** row.  This can be NULL to have the virtual table select the new 
57799 ** rowid for itself.  The subsequent elements in the array are 
57800 ** the values of columns in the new row.
57801 **
57802 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
57803 ** a row to delete.
57804 **
57805 ** P1 is a boolean flag. If it is set to true and the xUpdate call
57806 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
57807 ** is set to the value of the rowid for the row just inserted.
57808 */
57809 case OP_VUpdate: {
57810 #if 0  /* local variables moved into u.ck */
57811   sqlite3_vtab *pVtab;
57812   sqlite3_module *pModule;
57813   int nArg;
57814   int i;
57815   sqlite_int64 rowid;
57816   Mem **apArg;
57817   Mem *pX;
57818 #endif /* local variables moved into u.ck */
57819
57820   u.ck.pVtab = pOp->p4.pVtab->pVtab;
57821   u.ck.pModule = (sqlite3_module *)u.ck.pVtab->pModule;
57822   u.ck.nArg = pOp->p2;
57823   assert( pOp->p4type==P4_VTAB );
57824   if( ALWAYS(u.ck.pModule->xUpdate) ){
57825     u.ck.apArg = p->apArg;
57826     u.ck.pX = &aMem[pOp->p3];
57827     for(u.ck.i=0; u.ck.i<u.ck.nArg; u.ck.i++){
57828       sqlite3VdbeMemStoreType(u.ck.pX);
57829       u.ck.apArg[u.ck.i] = u.ck.pX;
57830       u.ck.pX++;
57831     }
57832     if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57833     rc = u.ck.pModule->xUpdate(u.ck.pVtab, u.ck.nArg, u.ck.apArg, &u.ck.rowid);
57834     sqlite3DbFree(db, p->zErrMsg);
57835     p->zErrMsg = u.ck.pVtab->zErrMsg;
57836     u.ck.pVtab->zErrMsg = 0;
57837     if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57838     if( rc==SQLITE_OK && pOp->p1 ){
57839       assert( u.ck.nArg>1 && u.ck.apArg[0] && (u.ck.apArg[0]->flags&MEM_Null) );
57840       db->lastRowid = u.ck.rowid;
57841     }
57842     p->nChange++;
57843   }
57844   break;
57845 }
57846 #endif /* SQLITE_OMIT_VIRTUALTABLE */
57847
57848 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
57849 /* Opcode: Pagecount P1 P2 * * *
57850 **
57851 ** Write the current number of pages in database P1 to memory cell P2.
57852 */
57853 case OP_Pagecount: {            /* out2-prerelease */
57854 #if 0  /* local variables moved into u.cl */
57855   int p1;
57856   int nPage;
57857   Pager *pPager;
57858 #endif /* local variables moved into u.cl */
57859
57860   u.cl.p1 = pOp->p1;
57861   u.cl.pPager = sqlite3BtreePager(db->aDb[u.cl.p1].pBt);
57862   rc = sqlite3PagerPagecount(u.cl.pPager, &u.cl.nPage);
57863   /* OP_Pagecount is always called from within a read transaction.  The
57864   ** page count has already been successfully read and cached.  So the
57865   ** sqlite3PagerPagecount() call above cannot fail. */
57866   if( ALWAYS(rc==SQLITE_OK) ){
57867     pOut->u.i = u.cl.nPage;
57868   }
57869   break;
57870 }
57871 #endif
57872
57873 #ifndef SQLITE_OMIT_TRACE
57874 /* Opcode: Trace * * * P4 *
57875 **
57876 ** If tracing is enabled (by the sqlite3_trace()) interface, then
57877 ** the UTF-8 string contained in P4 is emitted on the trace callback.
57878 */
57879 case OP_Trace: {
57880 #if 0  /* local variables moved into u.cm */
57881   char *zTrace;
57882 #endif /* local variables moved into u.cm */
57883
57884   u.cm.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
57885   if( u.cm.zTrace ){
57886     if( db->xTrace ){
57887       char *z = sqlite3VdbeExpandSql(p, u.cm.zTrace);
57888       db->xTrace(db->pTraceArg, z);
57889       sqlite3DbFree(db, z);
57890     }
57891 #ifdef SQLITE_DEBUG
57892     if( (db->flags & SQLITE_SqlTrace)!=0 ){
57893       sqlite3DebugPrintf("SQL-trace: %s\n", u.cm.zTrace);
57894     }
57895 #endif /* SQLITE_DEBUG */
57896   }
57897   break;
57898 }
57899 #endif
57900
57901
57902 /* Opcode: Noop * * * * *
57903 **
57904 ** Do nothing.  This instruction is often useful as a jump
57905 ** destination.
57906 */
57907 /*
57908 ** The magic Explain opcode are only inserted when explain==2 (which
57909 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
57910 ** This opcode records information from the optimizer.  It is the
57911 ** the same as a no-op.  This opcodesnever appears in a real VM program.
57912 */
57913 default: {          /* This is really OP_Noop and OP_Explain */
57914   break;
57915 }
57916
57917 /*****************************************************************************
57918 ** The cases of the switch statement above this line should all be indented
57919 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
57920 ** readability.  From this point on down, the normal indentation rules are
57921 ** restored.
57922 *****************************************************************************/
57923     }
57924
57925 #ifdef VDBE_PROFILE
57926     {
57927       u64 elapsed = sqlite3Hwtime() - start;
57928       pOp->cycles += elapsed;
57929       pOp->cnt++;
57930 #if 0
57931         fprintf(stdout, "%10llu ", elapsed);
57932         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
57933 #endif
57934     }
57935 #endif
57936
57937     /* The following code adds nothing to the actual functionality
57938     ** of the program.  It is only here for testing and debugging.
57939     ** On the other hand, it does burn CPU cycles every time through
57940     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
57941     */
57942 #ifndef NDEBUG
57943     assert( pc>=-1 && pc<p->nOp );
57944
57945 #ifdef SQLITE_DEBUG
57946     if( p->trace ){
57947       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
57948       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
57949         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
57950       }
57951       if( pOp->opflags & OPFLG_OUT3 ){
57952         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
57953       }
57954     }
57955 #endif  /* SQLITE_DEBUG */
57956 #endif  /* NDEBUG */
57957   }  /* The end of the for(;;) loop the loops through opcodes */
57958
57959   /* If we reach this point, it means that execution is finished with
57960   ** an error of some kind.
57961   */
57962 vdbe_error_halt:
57963   assert( rc );
57964   p->rc = rc;
57965   sqlite3VdbeHalt(p);
57966   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
57967   rc = SQLITE_ERROR;
57968   if( resetSchemaOnFault ) sqlite3ResetInternalSchema(db, 0);
57969
57970   /* This is the only way out of this procedure.  We have to
57971   ** release the mutexes on btrees that were acquired at the
57972   ** top. */
57973 vdbe_return:
57974   sqlite3BtreeMutexArrayLeave(&p->aMutex);
57975   return rc;
57976
57977   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
57978   ** is encountered.
57979   */
57980 too_big:
57981   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
57982   rc = SQLITE_TOOBIG;
57983   goto vdbe_error_halt;
57984
57985   /* Jump to here if a malloc() fails.
57986   */
57987 no_mem:
57988   db->mallocFailed = 1;
57989   sqlite3SetString(&p->zErrMsg, db, "out of memory");
57990   rc = SQLITE_NOMEM;
57991   goto vdbe_error_halt;
57992
57993   /* Jump to here for an SQLITE_MISUSE error.
57994   */
57995 abort_due_to_misuse:
57996   rc = SQLITE_MISUSE;
57997   /* Fall thru into abort_due_to_error */
57998
57999   /* Jump to here for any other kind of fatal error.  The "rc" variable
58000   ** should hold the error number.
58001   */
58002 abort_due_to_error:
58003   assert( p->zErrMsg==0 );
58004   if( db->mallocFailed ) rc = SQLITE_NOMEM;
58005   if( rc!=SQLITE_IOERR_NOMEM ){
58006     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
58007   }
58008   goto vdbe_error_halt;
58009
58010   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
58011   ** flag.
58012   */
58013 abort_due_to_interrupt:
58014   assert( db->u1.isInterrupted );
58015   rc = SQLITE_INTERRUPT;
58016   p->rc = rc;
58017   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
58018   goto vdbe_error_halt;
58019 }
58020
58021 /************** End of vdbe.c ************************************************/
58022 /************** Begin file vdbeblob.c ****************************************/
58023 /*
58024 ** 2007 May 1
58025 **
58026 ** The author disclaims copyright to this source code.  In place of
58027 ** a legal notice, here is a blessing:
58028 **
58029 **    May you do good and not evil.
58030 **    May you find forgiveness for yourself and forgive others.
58031 **    May you share freely, never taking more than you give.
58032 **
58033 *************************************************************************
58034 **
58035 ** This file contains code used to implement incremental BLOB I/O.
58036 */
58037
58038
58039 #ifndef SQLITE_OMIT_INCRBLOB
58040
58041 /*
58042 ** Valid sqlite3_blob* handles point to Incrblob structures.
58043 */
58044 typedef struct Incrblob Incrblob;
58045 struct Incrblob {
58046   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
58047   int nByte;              /* Size of open blob, in bytes */
58048   int iOffset;            /* Byte offset of blob in cursor data */
58049   BtCursor *pCsr;         /* Cursor pointing at blob row */
58050   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
58051   sqlite3 *db;            /* The associated database */
58052 };
58053
58054 /*
58055 ** Open a blob handle.
58056 */
58057 SQLITE_API int sqlite3_blob_open(
58058   sqlite3* db,            /* The database connection */
58059   const char *zDb,        /* The attached database containing the blob */
58060   const char *zTable,     /* The table containing the blob */
58061   const char *zColumn,    /* The column containing the blob */
58062   sqlite_int64 iRow,      /* The row containing the glob */
58063   int flags,              /* True -> read/write access, false -> read-only */
58064   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
58065 ){
58066   int nAttempt = 0;
58067   int iCol;               /* Index of zColumn in row-record */
58068
58069   /* This VDBE program seeks a btree cursor to the identified 
58070   ** db/table/row entry. The reason for using a vdbe program instead
58071   ** of writing code to use the b-tree layer directly is that the
58072   ** vdbe program will take advantage of the various transaction,
58073   ** locking and error handling infrastructure built into the vdbe.
58074   **
58075   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
58076   ** Code external to the Vdbe then "borrows" the b-tree cursor and
58077   ** uses it to implement the blob_read(), blob_write() and 
58078   ** blob_bytes() functions.
58079   **
58080   ** The sqlite3_blob_close() function finalizes the vdbe program,
58081   ** which closes the b-tree cursor and (possibly) commits the 
58082   ** transaction.
58083   */
58084   static const VdbeOpList openBlob[] = {
58085     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
58086     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
58087     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
58088
58089     /* One of the following two instructions is replaced by an OP_Noop. */
58090     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
58091     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
58092
58093     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
58094     {OP_NotExists, 0, 9, 1},       /* 6: Seek the cursor */
58095     {OP_Column, 0, 0, 1},          /* 7  */
58096     {OP_ResultRow, 1, 0, 0},       /* 8  */
58097     {OP_Close, 0, 0, 0},           /* 9  */
58098     {OP_Halt, 0, 0, 0},            /* 10 */
58099   };
58100
58101   Vdbe *v = 0;
58102   int rc = SQLITE_OK;
58103   char *zErr = 0;
58104   Table *pTab;
58105   Parse *pParse;
58106
58107   *ppBlob = 0;
58108   sqlite3_mutex_enter(db->mutex);
58109   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
58110   if( pParse==0 ){
58111     rc = SQLITE_NOMEM;
58112     goto blob_open_out;
58113   }
58114   do {
58115     memset(pParse, 0, sizeof(Parse));
58116     pParse->db = db;
58117
58118     if( sqlite3SafetyOn(db) ){
58119       sqlite3DbFree(db, zErr);
58120       sqlite3StackFree(db, pParse);
58121       sqlite3_mutex_leave(db->mutex);
58122       return SQLITE_MISUSE;
58123     }
58124
58125     sqlite3BtreeEnterAll(db);
58126     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
58127     if( pTab && IsVirtual(pTab) ){
58128       pTab = 0;
58129       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
58130     }
58131 #ifndef SQLITE_OMIT_VIEW
58132     if( pTab && pTab->pSelect ){
58133       pTab = 0;
58134       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
58135     }
58136 #endif
58137     if( !pTab ){
58138       if( pParse->zErrMsg ){
58139         sqlite3DbFree(db, zErr);
58140         zErr = pParse->zErrMsg;
58141         pParse->zErrMsg = 0;
58142       }
58143       rc = SQLITE_ERROR;
58144       (void)sqlite3SafetyOff(db);
58145       sqlite3BtreeLeaveAll(db);
58146       goto blob_open_out;
58147     }
58148
58149     /* Now search pTab for the exact column. */
58150     for(iCol=0; iCol < pTab->nCol; iCol++) {
58151       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
58152         break;
58153       }
58154     }
58155     if( iCol==pTab->nCol ){
58156       sqlite3DbFree(db, zErr);
58157       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
58158       rc = SQLITE_ERROR;
58159       (void)sqlite3SafetyOff(db);
58160       sqlite3BtreeLeaveAll(db);
58161       goto blob_open_out;
58162     }
58163
58164     /* If the value is being opened for writing, check that the
58165     ** column is not indexed, and that it is not part of a foreign key. 
58166     ** It is against the rules to open a column to which either of these
58167     ** descriptions applies for writing.  */
58168     if( flags ){
58169       const char *zFault = 0;
58170       Index *pIdx;
58171 #ifndef SQLITE_OMIT_FOREIGN_KEY
58172       if( db->flags&SQLITE_ForeignKeys ){
58173         /* Check that the column is not part of an FK child key definition. It
58174         ** is not necessary to check if it is part of a parent key, as parent
58175         ** key columns must be indexed. The check below will pick up this 
58176         ** case.  */
58177         FKey *pFKey;
58178         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
58179           int j;
58180           for(j=0; j<pFKey->nCol; j++){
58181             if( pFKey->aCol[j].iFrom==iCol ){
58182               zFault = "foreign key";
58183             }
58184           }
58185         }
58186       }
58187 #endif
58188       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
58189         int j;
58190         for(j=0; j<pIdx->nColumn; j++){
58191           if( pIdx->aiColumn[j]==iCol ){
58192             zFault = "indexed";
58193           }
58194         }
58195       }
58196       if( zFault ){
58197         sqlite3DbFree(db, zErr);
58198         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
58199         rc = SQLITE_ERROR;
58200         (void)sqlite3SafetyOff(db);
58201         sqlite3BtreeLeaveAll(db);
58202         goto blob_open_out;
58203       }
58204     }
58205
58206     v = sqlite3VdbeCreate(db);
58207     if( v ){
58208       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
58209       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
58210       flags = !!flags;                 /* flags = (flags ? 1 : 0); */
58211
58212       /* Configure the OP_Transaction */
58213       sqlite3VdbeChangeP1(v, 0, iDb);
58214       sqlite3VdbeChangeP2(v, 0, flags);
58215
58216       /* Configure the OP_VerifyCookie */
58217       sqlite3VdbeChangeP1(v, 1, iDb);
58218       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
58219
58220       /* Make sure a mutex is held on the table to be accessed */
58221       sqlite3VdbeUsesBtree(v, iDb); 
58222
58223       /* Configure the OP_TableLock instruction */
58224       sqlite3VdbeChangeP1(v, 2, iDb);
58225       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
58226       sqlite3VdbeChangeP3(v, 2, flags);
58227       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
58228
58229       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
58230       ** parameter of the other to pTab->tnum.  */
58231       sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
58232       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
58233       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
58234
58235       /* Configure the number of columns. Configure the cursor to
58236       ** think that the table has one more column than it really
58237       ** does. An OP_Column to retrieve this imaginary column will
58238       ** always return an SQL NULL. This is useful because it means
58239       ** we can invoke OP_Column to fill in the vdbe cursors type 
58240       ** and offset cache without causing any IO.
58241       */
58242       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
58243       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
58244       if( !db->mallocFailed ){
58245         sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
58246       }
58247     }
58248    
58249     sqlite3BtreeLeaveAll(db);
58250     rc = sqlite3SafetyOff(db);
58251     if( NEVER(rc!=SQLITE_OK) || db->mallocFailed ){
58252       goto blob_open_out;
58253     }
58254
58255     sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
58256     rc = sqlite3_step((sqlite3_stmt *)v);
58257     if( rc!=SQLITE_ROW ){
58258       nAttempt++;
58259       rc = sqlite3_finalize((sqlite3_stmt *)v);
58260       sqlite3DbFree(db, zErr);
58261       zErr = sqlite3MPrintf(db, sqlite3_errmsg(db));
58262       v = 0;
58263     }
58264   } while( nAttempt<5 && rc==SQLITE_SCHEMA );
58265
58266   if( rc==SQLITE_ROW ){
58267     /* The row-record has been opened successfully. Check that the
58268     ** column in question contains text or a blob. If it contains
58269     ** text, it is up to the caller to get the encoding right.
58270     */
58271     Incrblob *pBlob;
58272     u32 type = v->apCsr[0]->aType[iCol];
58273
58274     if( type<12 ){
58275       sqlite3DbFree(db, zErr);
58276       zErr = sqlite3MPrintf(db, "cannot open value of type %s",
58277           type==0?"null": type==7?"real": "integer"
58278       );
58279       rc = SQLITE_ERROR;
58280       goto blob_open_out;
58281     }
58282     pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
58283     if( db->mallocFailed ){
58284       sqlite3DbFree(db, pBlob);
58285       goto blob_open_out;
58286     }
58287     pBlob->flags = flags;
58288     pBlob->pCsr =  v->apCsr[0]->pCursor;
58289     sqlite3BtreeEnterCursor(pBlob->pCsr);
58290     sqlite3BtreeCacheOverflow(pBlob->pCsr);
58291     sqlite3BtreeLeaveCursor(pBlob->pCsr);
58292     pBlob->pStmt = (sqlite3_stmt *)v;
58293     pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
58294     pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
58295     pBlob->db = db;
58296     *ppBlob = (sqlite3_blob *)pBlob;
58297     rc = SQLITE_OK;
58298   }else if( rc==SQLITE_OK ){
58299     sqlite3DbFree(db, zErr);
58300     zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow);
58301     rc = SQLITE_ERROR;
58302   }
58303
58304 blob_open_out:
58305   if( v && (rc!=SQLITE_OK || db->mallocFailed) ){
58306     sqlite3VdbeFinalize(v);
58307   }
58308   sqlite3Error(db, rc, zErr);
58309   sqlite3DbFree(db, zErr);
58310   sqlite3StackFree(db, pParse);
58311   rc = sqlite3ApiExit(db, rc);
58312   sqlite3_mutex_leave(db->mutex);
58313   return rc;
58314 }
58315
58316 /*
58317 ** Close a blob handle that was previously created using
58318 ** sqlite3_blob_open().
58319 */
58320 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
58321   Incrblob *p = (Incrblob *)pBlob;
58322   int rc;
58323   sqlite3 *db;
58324
58325   if( p ){
58326     db = p->db;
58327     sqlite3_mutex_enter(db->mutex);
58328     rc = sqlite3_finalize(p->pStmt);
58329     sqlite3DbFree(db, p);
58330     sqlite3_mutex_leave(db->mutex);
58331   }else{
58332     rc = SQLITE_OK;
58333   }
58334   return rc;
58335 }
58336
58337 /*
58338 ** Perform a read or write operation on a blob
58339 */
58340 static int blobReadWrite(
58341   sqlite3_blob *pBlob, 
58342   void *z, 
58343   int n, 
58344   int iOffset, 
58345   int (*xCall)(BtCursor*, u32, u32, void*)
58346 ){
58347   int rc;
58348   Incrblob *p = (Incrblob *)pBlob;
58349   Vdbe *v;
58350   sqlite3 *db;
58351
58352   if( p==0 ) return SQLITE_MISUSE;
58353   db = p->db;
58354   sqlite3_mutex_enter(db->mutex);
58355   v = (Vdbe*)p->pStmt;
58356
58357   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
58358     /* Request is out of range. Return a transient error. */
58359     rc = SQLITE_ERROR;
58360     sqlite3Error(db, SQLITE_ERROR, 0);
58361   } else if( v==0 ){
58362     /* If there is no statement handle, then the blob-handle has
58363     ** already been invalidated. Return SQLITE_ABORT in this case.
58364     */
58365     rc = SQLITE_ABORT;
58366   }else{
58367     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
58368     ** returned, clean-up the statement handle.
58369     */
58370     assert( db == v->db );
58371     sqlite3BtreeEnterCursor(p->pCsr);
58372     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
58373     sqlite3BtreeLeaveCursor(p->pCsr);
58374     if( rc==SQLITE_ABORT ){
58375       sqlite3VdbeFinalize(v);
58376       p->pStmt = 0;
58377     }else{
58378       db->errCode = rc;
58379       v->rc = rc;
58380     }
58381   }
58382   rc = sqlite3ApiExit(db, rc);
58383   sqlite3_mutex_leave(db->mutex);
58384   return rc;
58385 }
58386
58387 /*
58388 ** Read data from a blob handle.
58389 */
58390 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
58391   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
58392 }
58393
58394 /*
58395 ** Write data to a blob handle.
58396 */
58397 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
58398   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
58399 }
58400
58401 /*
58402 ** Query a blob handle for the size of the data.
58403 **
58404 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
58405 ** so no mutex is required for access.
58406 */
58407 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
58408   Incrblob *p = (Incrblob *)pBlob;
58409   return p ? p->nByte : 0;
58410 }
58411
58412 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
58413
58414 /************** End of vdbeblob.c ********************************************/
58415 /************** Begin file journal.c *****************************************/
58416 /*
58417 ** 2007 August 22
58418 **
58419 ** The author disclaims copyright to this source code.  In place of
58420 ** a legal notice, here is a blessing:
58421 **
58422 **    May you do good and not evil.
58423 **    May you find forgiveness for yourself and forgive others.
58424 **    May you share freely, never taking more than you give.
58425 **
58426 *************************************************************************
58427 **
58428 ** This file implements a special kind of sqlite3_file object used
58429 ** by SQLite to create journal files if the atomic-write optimization
58430 ** is enabled.
58431 **
58432 ** The distinctive characteristic of this sqlite3_file is that the
58433 ** actual on disk file is created lazily. When the file is created,
58434 ** the caller specifies a buffer size for an in-memory buffer to
58435 ** be used to service read() and write() requests. The actual file
58436 ** on disk is not created or populated until either:
58437 **
58438 **   1) The in-memory representation grows too large for the allocated 
58439 **      buffer, or
58440 **   2) The sqlite3JournalCreate() function is called.
58441 */
58442 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
58443
58444
58445 /*
58446 ** A JournalFile object is a subclass of sqlite3_file used by
58447 ** as an open file handle for journal files.
58448 */
58449 struct JournalFile {
58450   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
58451   int nBuf;                       /* Size of zBuf[] in bytes */
58452   char *zBuf;                     /* Space to buffer journal writes */
58453   int iSize;                      /* Amount of zBuf[] currently used */
58454   int flags;                      /* xOpen flags */
58455   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
58456   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
58457   const char *zJournal;           /* Name of the journal file */
58458 };
58459 typedef struct JournalFile JournalFile;
58460
58461 /*
58462 ** If it does not already exists, create and populate the on-disk file 
58463 ** for JournalFile p.
58464 */
58465 static int createFile(JournalFile *p){
58466   int rc = SQLITE_OK;
58467   if( !p->pReal ){
58468     sqlite3_file *pReal = (sqlite3_file *)&p[1];
58469     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
58470     if( rc==SQLITE_OK ){
58471       p->pReal = pReal;
58472       if( p->iSize>0 ){
58473         assert(p->iSize<=p->nBuf);
58474         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
58475       }
58476     }
58477   }
58478   return rc;
58479 }
58480
58481 /*
58482 ** Close the file.
58483 */
58484 static int jrnlClose(sqlite3_file *pJfd){
58485   JournalFile *p = (JournalFile *)pJfd;
58486   if( p->pReal ){
58487     sqlite3OsClose(p->pReal);
58488   }
58489   sqlite3_free(p->zBuf);
58490   return SQLITE_OK;
58491 }
58492
58493 /*
58494 ** Read data from the file.
58495 */
58496 static int jrnlRead(
58497   sqlite3_file *pJfd,    /* The journal file from which to read */
58498   void *zBuf,            /* Put the results here */
58499   int iAmt,              /* Number of bytes to read */
58500   sqlite_int64 iOfst     /* Begin reading at this offset */
58501 ){
58502   int rc = SQLITE_OK;
58503   JournalFile *p = (JournalFile *)pJfd;
58504   if( p->pReal ){
58505     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
58506   }else if( (iAmt+iOfst)>p->iSize ){
58507     rc = SQLITE_IOERR_SHORT_READ;
58508   }else{
58509     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
58510   }
58511   return rc;
58512 }
58513
58514 /*
58515 ** Write data to the file.
58516 */
58517 static int jrnlWrite(
58518   sqlite3_file *pJfd,    /* The journal file into which to write */
58519   const void *zBuf,      /* Take data to be written from here */
58520   int iAmt,              /* Number of bytes to write */
58521   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
58522 ){
58523   int rc = SQLITE_OK;
58524   JournalFile *p = (JournalFile *)pJfd;
58525   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
58526     rc = createFile(p);
58527   }
58528   if( rc==SQLITE_OK ){
58529     if( p->pReal ){
58530       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
58531     }else{
58532       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
58533       if( p->iSize<(iOfst+iAmt) ){
58534         p->iSize = (iOfst+iAmt);
58535       }
58536     }
58537   }
58538   return rc;
58539 }
58540
58541 /*
58542 ** Truncate the file.
58543 */
58544 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
58545   int rc = SQLITE_OK;
58546   JournalFile *p = (JournalFile *)pJfd;
58547   if( p->pReal ){
58548     rc = sqlite3OsTruncate(p->pReal, size);
58549   }else if( size<p->iSize ){
58550     p->iSize = size;
58551   }
58552   return rc;
58553 }
58554
58555 /*
58556 ** Sync the file.
58557 */
58558 static int jrnlSync(sqlite3_file *pJfd, int flags){
58559   int rc;
58560   JournalFile *p = (JournalFile *)pJfd;
58561   if( p->pReal ){
58562     rc = sqlite3OsSync(p->pReal, flags);
58563   }else{
58564     rc = SQLITE_OK;
58565   }
58566   return rc;
58567 }
58568
58569 /*
58570 ** Query the size of the file in bytes.
58571 */
58572 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
58573   int rc = SQLITE_OK;
58574   JournalFile *p = (JournalFile *)pJfd;
58575   if( p->pReal ){
58576     rc = sqlite3OsFileSize(p->pReal, pSize);
58577   }else{
58578     *pSize = (sqlite_int64) p->iSize;
58579   }
58580   return rc;
58581 }
58582
58583 /*
58584 ** Table of methods for JournalFile sqlite3_file object.
58585 */
58586 static struct sqlite3_io_methods JournalFileMethods = {
58587   1,             /* iVersion */
58588   jrnlClose,     /* xClose */
58589   jrnlRead,      /* xRead */
58590   jrnlWrite,     /* xWrite */
58591   jrnlTruncate,  /* xTruncate */
58592   jrnlSync,      /* xSync */
58593   jrnlFileSize,  /* xFileSize */
58594   0,             /* xLock */
58595   0,             /* xUnlock */
58596   0,             /* xCheckReservedLock */
58597   0,             /* xFileControl */
58598   0,             /* xSectorSize */
58599   0              /* xDeviceCharacteristics */
58600 };
58601
58602 /* 
58603 ** Open a journal file.
58604 */
58605 SQLITE_PRIVATE int sqlite3JournalOpen(
58606   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
58607   const char *zName,         /* Name of the journal file */
58608   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
58609   int flags,                 /* Opening flags */
58610   int nBuf                   /* Bytes buffered before opening the file */
58611 ){
58612   JournalFile *p = (JournalFile *)pJfd;
58613   memset(p, 0, sqlite3JournalSize(pVfs));
58614   if( nBuf>0 ){
58615     p->zBuf = sqlite3MallocZero(nBuf);
58616     if( !p->zBuf ){
58617       return SQLITE_NOMEM;
58618     }
58619   }else{
58620     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
58621   }
58622   p->pMethod = &JournalFileMethods;
58623   p->nBuf = nBuf;
58624   p->flags = flags;
58625   p->zJournal = zName;
58626   p->pVfs = pVfs;
58627   return SQLITE_OK;
58628 }
58629
58630 /*
58631 ** If the argument p points to a JournalFile structure, and the underlying
58632 ** file has not yet been created, create it now.
58633 */
58634 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
58635   if( p->pMethods!=&JournalFileMethods ){
58636     return SQLITE_OK;
58637   }
58638   return createFile((JournalFile *)p);
58639 }
58640
58641 /* 
58642 ** Return the number of bytes required to store a JournalFile that uses vfs
58643 ** pVfs to create the underlying on-disk files.
58644 */
58645 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
58646   return (pVfs->szOsFile+sizeof(JournalFile));
58647 }
58648 #endif
58649
58650 /************** End of journal.c *********************************************/
58651 /************** Begin file memjournal.c **************************************/
58652 /*
58653 ** 2008 October 7
58654 **
58655 ** The author disclaims copyright to this source code.  In place of
58656 ** a legal notice, here is a blessing:
58657 **
58658 **    May you do good and not evil.
58659 **    May you find forgiveness for yourself and forgive others.
58660 **    May you share freely, never taking more than you give.
58661 **
58662 *************************************************************************
58663 **
58664 ** This file contains code use to implement an in-memory rollback journal.
58665 ** The in-memory rollback journal is used to journal transactions for
58666 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
58667 */
58668
58669 /* Forward references to internal structures */
58670 typedef struct MemJournal MemJournal;
58671 typedef struct FilePoint FilePoint;
58672 typedef struct FileChunk FileChunk;
58673
58674 /* Space to hold the rollback journal is allocated in increments of
58675 ** this many bytes.
58676 **
58677 ** The size chosen is a little less than a power of two.  That way,
58678 ** the FileChunk object will have a size that almost exactly fills
58679 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
58680 ** memory allocators.
58681 */
58682 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
58683
58684 /* Macro to find the minimum of two numeric values.
58685 */
58686 #ifndef MIN
58687 # define MIN(x,y) ((x)<(y)?(x):(y))
58688 #endif
58689
58690 /*
58691 ** The rollback journal is composed of a linked list of these structures.
58692 */
58693 struct FileChunk {
58694   FileChunk *pNext;               /* Next chunk in the journal */
58695   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
58696 };
58697
58698 /*
58699 ** An instance of this object serves as a cursor into the rollback journal.
58700 ** The cursor can be either for reading or writing.
58701 */
58702 struct FilePoint {
58703   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
58704   FileChunk *pChunk;              /* Specific chunk into which cursor points */
58705 };
58706
58707 /*
58708 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
58709 ** is an instance of this class.
58710 */
58711 struct MemJournal {
58712   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
58713   FileChunk *pFirst;              /* Head of in-memory chunk-list */
58714   FilePoint endpoint;             /* Pointer to the end of the file */
58715   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
58716 };
58717
58718 /*
58719 ** Read data from the in-memory journal file.  This is the implementation
58720 ** of the sqlite3_vfs.xRead method.
58721 */
58722 static int memjrnlRead(
58723   sqlite3_file *pJfd,    /* The journal file from which to read */
58724   void *zBuf,            /* Put the results here */
58725   int iAmt,              /* Number of bytes to read */
58726   sqlite_int64 iOfst     /* Begin reading at this offset */
58727 ){
58728   MemJournal *p = (MemJournal *)pJfd;
58729   u8 *zOut = zBuf;
58730   int nRead = iAmt;
58731   int iChunkOffset;
58732   FileChunk *pChunk;
58733
58734   /* SQLite never tries to read past the end of a rollback journal file */
58735   assert( iOfst+iAmt<=p->endpoint.iOffset );
58736
58737   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
58738     sqlite3_int64 iOff = 0;
58739     for(pChunk=p->pFirst; 
58740         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
58741         pChunk=pChunk->pNext
58742     ){
58743       iOff += JOURNAL_CHUNKSIZE;
58744     }
58745   }else{
58746     pChunk = p->readpoint.pChunk;
58747   }
58748
58749   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
58750   do {
58751     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
58752     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
58753     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
58754     zOut += nCopy;
58755     nRead -= iSpace;
58756     iChunkOffset = 0;
58757   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
58758   p->readpoint.iOffset = iOfst+iAmt;
58759   p->readpoint.pChunk = pChunk;
58760
58761   return SQLITE_OK;
58762 }
58763
58764 /*
58765 ** Write data to the file.
58766 */
58767 static int memjrnlWrite(
58768   sqlite3_file *pJfd,    /* The journal file into which to write */
58769   const void *zBuf,      /* Take data to be written from here */
58770   int iAmt,              /* Number of bytes to write */
58771   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
58772 ){
58773   MemJournal *p = (MemJournal *)pJfd;
58774   int nWrite = iAmt;
58775   u8 *zWrite = (u8 *)zBuf;
58776
58777   /* An in-memory journal file should only ever be appended to. Random
58778   ** access writes are not required by sqlite.
58779   */
58780   assert( iOfst==p->endpoint.iOffset );
58781   UNUSED_PARAMETER(iOfst);
58782
58783   while( nWrite>0 ){
58784     FileChunk *pChunk = p->endpoint.pChunk;
58785     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
58786     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
58787
58788     if( iChunkOffset==0 ){
58789       /* New chunk is required to extend the file. */
58790       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
58791       if( !pNew ){
58792         return SQLITE_IOERR_NOMEM;
58793       }
58794       pNew->pNext = 0;
58795       if( pChunk ){
58796         assert( p->pFirst );
58797         pChunk->pNext = pNew;
58798       }else{
58799         assert( !p->pFirst );
58800         p->pFirst = pNew;
58801       }
58802       p->endpoint.pChunk = pNew;
58803     }
58804
58805     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
58806     zWrite += iSpace;
58807     nWrite -= iSpace;
58808     p->endpoint.iOffset += iSpace;
58809   }
58810
58811   return SQLITE_OK;
58812 }
58813
58814 /*
58815 ** Truncate the file.
58816 */
58817 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
58818   MemJournal *p = (MemJournal *)pJfd;
58819   FileChunk *pChunk;
58820   assert(size==0);
58821   UNUSED_PARAMETER(size);
58822   pChunk = p->pFirst;
58823   while( pChunk ){
58824     FileChunk *pTmp = pChunk;
58825     pChunk = pChunk->pNext;
58826     sqlite3_free(pTmp);
58827   }
58828   sqlite3MemJournalOpen(pJfd);
58829   return SQLITE_OK;
58830 }
58831
58832 /*
58833 ** Close the file.
58834 */
58835 static int memjrnlClose(sqlite3_file *pJfd){
58836   memjrnlTruncate(pJfd, 0);
58837   return SQLITE_OK;
58838 }
58839
58840
58841 /*
58842 ** Sync the file.
58843 **
58844 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
58845 ** is never called in a working implementation.  This implementation
58846 ** exists purely as a contingency, in case some malfunction in some other
58847 ** part of SQLite causes Sync to be called by mistake.
58848 */
58849 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){   /*NO_TEST*/
58850   UNUSED_PARAMETER2(NotUsed, NotUsed2);                        /*NO_TEST*/
58851   assert( 0 );                                                 /*NO_TEST*/
58852   return SQLITE_OK;                                            /*NO_TEST*/
58853 }                                                              /*NO_TEST*/
58854
58855 /*
58856 ** Query the size of the file in bytes.
58857 */
58858 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
58859   MemJournal *p = (MemJournal *)pJfd;
58860   *pSize = (sqlite_int64) p->endpoint.iOffset;
58861   return SQLITE_OK;
58862 }
58863
58864 /*
58865 ** Table of methods for MemJournal sqlite3_file object.
58866 */
58867 static struct sqlite3_io_methods MemJournalMethods = {
58868   1,                /* iVersion */
58869   memjrnlClose,     /* xClose */
58870   memjrnlRead,      /* xRead */
58871   memjrnlWrite,     /* xWrite */
58872   memjrnlTruncate,  /* xTruncate */
58873   memjrnlSync,      /* xSync */
58874   memjrnlFileSize,  /* xFileSize */
58875   0,                /* xLock */
58876   0,                /* xUnlock */
58877   0,                /* xCheckReservedLock */
58878   0,                /* xFileControl */
58879   0,                /* xSectorSize */
58880   0                 /* xDeviceCharacteristics */
58881 };
58882
58883 /* 
58884 ** Open a journal file.
58885 */
58886 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
58887   MemJournal *p = (MemJournal *)pJfd;
58888   assert( EIGHT_BYTE_ALIGNMENT(p) );
58889   memset(p, 0, sqlite3MemJournalSize());
58890   p->pMethod = &MemJournalMethods;
58891 }
58892
58893 /*
58894 ** Return true if the file-handle passed as an argument is 
58895 ** an in-memory journal 
58896 */
58897 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
58898   return pJfd->pMethods==&MemJournalMethods;
58899 }
58900
58901 /* 
58902 ** Return the number of bytes required to store a MemJournal that uses vfs
58903 ** pVfs to create the underlying on-disk files.
58904 */
58905 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
58906   return sizeof(MemJournal);
58907 }
58908
58909 /************** End of memjournal.c ******************************************/
58910 /************** Begin file walker.c ******************************************/
58911 /*
58912 ** 2008 August 16
58913 **
58914 ** The author disclaims copyright to this source code.  In place of
58915 ** a legal notice, here is a blessing:
58916 **
58917 **    May you do good and not evil.
58918 **    May you find forgiveness for yourself and forgive others.
58919 **    May you share freely, never taking more than you give.
58920 **
58921 *************************************************************************
58922 ** This file contains routines used for walking the parser tree for
58923 ** an SQL statement.
58924 */
58925
58926
58927 /*
58928 ** Walk an expression tree.  Invoke the callback once for each node
58929 ** of the expression, while decending.  (In other words, the callback
58930 ** is invoked before visiting children.)
58931 **
58932 ** The return value from the callback should be one of the WRC_*
58933 ** constants to specify how to proceed with the walk.
58934 **
58935 **    WRC_Continue      Continue descending down the tree.
58936 **
58937 **    WRC_Prune         Do not descend into child nodes.  But allow
58938 **                      the walk to continue with sibling nodes.
58939 **
58940 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
58941 **                      return the top-level walk call.
58942 **
58943 ** The return value from this routine is WRC_Abort to abandon the tree walk
58944 ** and WRC_Continue to continue.
58945 */
58946 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
58947   int rc;
58948   if( pExpr==0 ) return WRC_Continue;
58949   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
58950   testcase( ExprHasProperty(pExpr, EP_Reduced) );
58951   rc = pWalker->xExprCallback(pWalker, pExpr);
58952   if( rc==WRC_Continue
58953               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
58954     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
58955     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
58956     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
58957       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
58958     }else{
58959       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
58960     }
58961   }
58962   return rc & WRC_Abort;
58963 }
58964
58965 /*
58966 ** Call sqlite3WalkExpr() for every expression in list p or until
58967 ** an abort request is seen.
58968 */
58969 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
58970   int i;
58971   struct ExprList_item *pItem;
58972   if( p ){
58973     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
58974       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
58975     }
58976   }
58977   return WRC_Continue;
58978 }
58979
58980 /*
58981 ** Walk all expressions associated with SELECT statement p.  Do
58982 ** not invoke the SELECT callback on p, but do (of course) invoke
58983 ** any expr callbacks and SELECT callbacks that come from subqueries.
58984 ** Return WRC_Abort or WRC_Continue.
58985 */
58986 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
58987   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
58988   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
58989   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
58990   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
58991   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
58992   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
58993   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
58994   return WRC_Continue;
58995 }
58996
58997 /*
58998 ** Walk the parse trees associated with all subqueries in the
58999 ** FROM clause of SELECT statement p.  Do not invoke the select
59000 ** callback on p, but do invoke it on each FROM clause subquery
59001 ** and on any subqueries further down in the tree.  Return 
59002 ** WRC_Abort or WRC_Continue;
59003 */
59004 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
59005   SrcList *pSrc;
59006   int i;
59007   struct SrcList_item *pItem;
59008
59009   pSrc = p->pSrc;
59010   if( ALWAYS(pSrc) ){
59011     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
59012       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
59013         return WRC_Abort;
59014       }
59015     }
59016   }
59017   return WRC_Continue;
59018
59019
59020 /*
59021 ** Call sqlite3WalkExpr() for every expression in Select statement p.
59022 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
59023 ** on the compound select chain, p->pPrior.
59024 **
59025 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
59026 ** there is an abort request.
59027 **
59028 ** If the Walker does not have an xSelectCallback() then this routine
59029 ** is a no-op returning WRC_Continue.
59030 */
59031 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
59032   int rc;
59033   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
59034   rc = WRC_Continue;
59035   while( p  ){
59036     rc = pWalker->xSelectCallback(pWalker, p);
59037     if( rc ) break;
59038     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
59039     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
59040     p = p->pPrior;
59041   }
59042   return rc & WRC_Abort;
59043 }
59044
59045 /************** End of walker.c **********************************************/
59046 /************** Begin file resolve.c *****************************************/
59047 /*
59048 ** 2008 August 18
59049 **
59050 ** The author disclaims copyright to this source code.  In place of
59051 ** a legal notice, here is a blessing:
59052 **
59053 **    May you do good and not evil.
59054 **    May you find forgiveness for yourself and forgive others.
59055 **    May you share freely, never taking more than you give.
59056 **
59057 *************************************************************************
59058 **
59059 ** This file contains routines used for walking the parser tree and
59060 ** resolve all identifiers by associating them with a particular
59061 ** table and column.
59062 */
59063
59064 /*
59065 ** Turn the pExpr expression into an alias for the iCol-th column of the
59066 ** result set in pEList.
59067 **
59068 ** If the result set column is a simple column reference, then this routine
59069 ** makes an exact copy.  But for any other kind of expression, this
59070 ** routine make a copy of the result set column as the argument to the
59071 ** TK_AS operator.  The TK_AS operator causes the expression to be
59072 ** evaluated just once and then reused for each alias.
59073 **
59074 ** The reason for suppressing the TK_AS term when the expression is a simple
59075 ** column reference is so that the column reference will be recognized as
59076 ** usable by indices within the WHERE clause processing logic. 
59077 **
59078 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
59079 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
59080 **
59081 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
59082 **
59083 ** Is equivalent to:
59084 **
59085 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
59086 **
59087 ** The result of random()%5 in the GROUP BY clause is probably different
59088 ** from the result in the result-set.  We might fix this someday.  Or
59089 ** then again, we might not...
59090 */
59091 static void resolveAlias(
59092   Parse *pParse,         /* Parsing context */
59093   ExprList *pEList,      /* A result set */
59094   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
59095   Expr *pExpr,           /* Transform this into an alias to the result set */
59096   const char *zType      /* "GROUP" or "ORDER" or "" */
59097 ){
59098   Expr *pOrig;           /* The iCol-th column of the result set */
59099   Expr *pDup;            /* Copy of pOrig */
59100   sqlite3 *db;           /* The database connection */
59101
59102   assert( iCol>=0 && iCol<pEList->nExpr );
59103   pOrig = pEList->a[iCol].pExpr;
59104   assert( pOrig!=0 );
59105   assert( pOrig->flags & EP_Resolved );
59106   db = pParse->db;
59107   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
59108     pDup = sqlite3ExprDup(db, pOrig, 0);
59109     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
59110     if( pDup==0 ) return;
59111     if( pEList->a[iCol].iAlias==0 ){
59112       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
59113     }
59114     pDup->iTable = pEList->a[iCol].iAlias;
59115   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
59116     pDup = sqlite3ExprDup(db, pOrig, 0);
59117     if( pDup==0 ) return;
59118   }else{
59119     char *zToken = pOrig->u.zToken;
59120     assert( zToken!=0 );
59121     pOrig->u.zToken = 0;
59122     pDup = sqlite3ExprDup(db, pOrig, 0);
59123     pOrig->u.zToken = zToken;
59124     if( pDup==0 ) return;
59125     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
59126     pDup->flags2 |= EP2_MallocedToken;
59127     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
59128   }
59129   if( pExpr->flags & EP_ExpCollate ){
59130     pDup->pColl = pExpr->pColl;
59131     pDup->flags |= EP_ExpCollate;
59132   }
59133
59134   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
59135   ** prevents ExprDelete() from deleting the Expr structure itself,
59136   ** allowing it to be repopulated by the memcpy() on the following line.
59137   */
59138   ExprSetProperty(pExpr, EP_Static);
59139   sqlite3ExprDelete(db, pExpr);
59140   memcpy(pExpr, pDup, sizeof(*pExpr));
59141   sqlite3DbFree(db, pDup);
59142 }
59143
59144 /*
59145 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
59146 ** that name in the set of source tables in pSrcList and make the pExpr 
59147 ** expression node refer back to that source column.  The following changes
59148 ** are made to pExpr:
59149 **
59150 **    pExpr->iDb           Set the index in db->aDb[] of the database X
59151 **                         (even if X is implied).
59152 **    pExpr->iTable        Set to the cursor number for the table obtained
59153 **                         from pSrcList.
59154 **    pExpr->pTab          Points to the Table structure of X.Y (even if
59155 **                         X and/or Y are implied.)
59156 **    pExpr->iColumn       Set to the column number within the table.
59157 **    pExpr->op            Set to TK_COLUMN.
59158 **    pExpr->pLeft         Any expression this points to is deleted
59159 **    pExpr->pRight        Any expression this points to is deleted.
59160 **
59161 ** The zDb variable is the name of the database (the "X").  This value may be
59162 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
59163 ** can be used.  The zTable variable is the name of the table (the "Y").  This
59164 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
59165 ** means that the form of the name is Z and that columns from any table
59166 ** can be used.
59167 **
59168 ** If the name cannot be resolved unambiguously, leave an error message
59169 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
59170 */
59171 static int lookupName(
59172   Parse *pParse,       /* The parsing context */
59173   const char *zDb,     /* Name of the database containing table, or NULL */
59174   const char *zTab,    /* Name of table containing column, or NULL */
59175   const char *zCol,    /* Name of the column. */
59176   NameContext *pNC,    /* The name context used to resolve the name */
59177   Expr *pExpr          /* Make this EXPR node point to the selected column */
59178 ){
59179   int i, j;            /* Loop counters */
59180   int cnt = 0;                      /* Number of matching column names */
59181   int cntTab = 0;                   /* Number of matching table names */
59182   sqlite3 *db = pParse->db;         /* The database connection */
59183   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
59184   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
59185   NameContext *pTopNC = pNC;        /* First namecontext in the list */
59186   Schema *pSchema = 0;              /* Schema of the expression */
59187   int isTrigger = 0;
59188
59189   assert( pNC );     /* the name context cannot be NULL. */
59190   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
59191   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
59192
59193   /* Initialize the node to no-match */
59194   pExpr->iTable = -1;
59195   pExpr->pTab = 0;
59196   ExprSetIrreducible(pExpr);
59197
59198   /* Start at the inner-most context and move outward until a match is found */
59199   while( pNC && cnt==0 ){
59200     ExprList *pEList;
59201     SrcList *pSrcList = pNC->pSrcList;
59202
59203     if( pSrcList ){
59204       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
59205         Table *pTab;
59206         int iDb;
59207         Column *pCol;
59208   
59209         pTab = pItem->pTab;
59210         assert( pTab!=0 && pTab->zName!=0 );
59211         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
59212         assert( pTab->nCol>0 );
59213         if( zTab ){
59214           if( pItem->zAlias ){
59215             char *zTabName = pItem->zAlias;
59216             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
59217           }else{
59218             char *zTabName = pTab->zName;
59219             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
59220               continue;
59221             }
59222             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
59223               continue;
59224             }
59225           }
59226         }
59227         if( 0==(cntTab++) ){
59228           pExpr->iTable = pItem->iCursor;
59229           pExpr->pTab = pTab;
59230           pSchema = pTab->pSchema;
59231           pMatch = pItem;
59232         }
59233         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
59234           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
59235             IdList *pUsing;
59236             cnt++;
59237             pExpr->iTable = pItem->iCursor;
59238             pExpr->pTab = pTab;
59239             pMatch = pItem;
59240             pSchema = pTab->pSchema;
59241             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
59242             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
59243             if( i<pSrcList->nSrc-1 ){
59244               if( pItem[1].jointype & JT_NATURAL ){
59245                 /* If this match occurred in the left table of a natural join,
59246                 ** then skip the right table to avoid a duplicate match */
59247                 pItem++;
59248                 i++;
59249               }else if( (pUsing = pItem[1].pUsing)!=0 ){
59250                 /* If this match occurs on a column that is in the USING clause
59251                 ** of a join, skip the search of the right table of the join
59252                 ** to avoid a duplicate match there. */
59253                 int k;
59254                 for(k=0; k<pUsing->nId; k++){
59255                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
59256                     pItem++;
59257                     i++;
59258                     break;
59259                   }
59260                 }
59261               }
59262             }
59263             break;
59264           }
59265         }
59266       }
59267     }
59268
59269 #ifndef SQLITE_OMIT_TRIGGER
59270     /* If we have not already resolved the name, then maybe 
59271     ** it is a new.* or old.* trigger argument reference
59272     */
59273     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
59274       int op = pParse->eTriggerOp;
59275       Table *pTab = 0;
59276       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
59277       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
59278         pExpr->iTable = 1;
59279         pTab = pParse->pTriggerTab;
59280       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
59281         pExpr->iTable = 0;
59282         pTab = pParse->pTriggerTab;
59283       }
59284
59285       if( pTab ){ 
59286         int iCol;
59287         pSchema = pTab->pSchema;
59288         cntTab++;
59289         for(iCol=0; iCol<pTab->nCol; iCol++){
59290           Column *pCol = &pTab->aCol[iCol];
59291           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
59292             if( iCol==pTab->iPKey ){
59293               iCol = -1;
59294             }
59295             break;
59296           }
59297         }
59298         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
59299           iCol = -1;        /* IMP: R-44911-55124 */
59300         }
59301         if( iCol<pTab->nCol ){
59302           cnt++;
59303           if( iCol<0 ){
59304             pExpr->affinity = SQLITE_AFF_INTEGER;
59305           }else if( pExpr->iTable==0 ){
59306             testcase( iCol==31 );
59307             testcase( iCol==32 );
59308             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
59309           }else{
59310             testcase( iCol==31 );
59311             testcase( iCol==32 );
59312             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
59313           }
59314           pExpr->iColumn = (i16)iCol;
59315           pExpr->pTab = pTab;
59316           isTrigger = 1;
59317         }
59318       }
59319     }
59320 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
59321
59322     /*
59323     ** Perhaps the name is a reference to the ROWID
59324     */
59325     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
59326       cnt = 1;
59327       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
59328       pExpr->affinity = SQLITE_AFF_INTEGER;
59329     }
59330
59331     /*
59332     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
59333     ** might refer to an result-set alias.  This happens, for example, when
59334     ** we are resolving names in the WHERE clause of the following command:
59335     **
59336     **     SELECT a+b AS x FROM table WHERE x<10;
59337     **
59338     ** In cases like this, replace pExpr with a copy of the expression that
59339     ** forms the result set entry ("a+b" in the example) and return immediately.
59340     ** Note that the expression in the result set should have already been
59341     ** resolved by the time the WHERE clause is resolved.
59342     */
59343     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
59344       for(j=0; j<pEList->nExpr; j++){
59345         char *zAs = pEList->a[j].zName;
59346         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
59347           Expr *pOrig;
59348           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
59349           assert( pExpr->x.pList==0 );
59350           assert( pExpr->x.pSelect==0 );
59351           pOrig = pEList->a[j].pExpr;
59352           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
59353             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
59354             return WRC_Abort;
59355           }
59356           resolveAlias(pParse, pEList, j, pExpr, "");
59357           cnt = 1;
59358           pMatch = 0;
59359           assert( zTab==0 && zDb==0 );
59360           goto lookupname_end;
59361         }
59362       } 
59363     }
59364
59365     /* Advance to the next name context.  The loop will exit when either
59366     ** we have a match (cnt>0) or when we run out of name contexts.
59367     */
59368     if( cnt==0 ){
59369       pNC = pNC->pNext;
59370     }
59371   }
59372
59373   /*
59374   ** If X and Y are NULL (in other words if only the column name Z is
59375   ** supplied) and the value of Z is enclosed in double-quotes, then
59376   ** Z is a string literal if it doesn't match any column names.  In that
59377   ** case, we need to return right away and not make any changes to
59378   ** pExpr.
59379   **
59380   ** Because no reference was made to outer contexts, the pNC->nRef
59381   ** fields are not changed in any context.
59382   */
59383   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
59384     pExpr->op = TK_STRING;
59385     pExpr->pTab = 0;
59386     return WRC_Prune;
59387   }
59388
59389   /*
59390   ** cnt==0 means there was not match.  cnt>1 means there were two or
59391   ** more matches.  Either way, we have an error.
59392   */
59393   if( cnt!=1 ){
59394     const char *zErr;
59395     zErr = cnt==0 ? "no such column" : "ambiguous column name";
59396     if( zDb ){
59397       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
59398     }else if( zTab ){
59399       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
59400     }else{
59401       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
59402     }
59403     pTopNC->nErr++;
59404   }
59405
59406   /* If a column from a table in pSrcList is referenced, then record
59407   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
59408   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
59409   ** column number is greater than the number of bits in the bitmask
59410   ** then set the high-order bit of the bitmask.
59411   */
59412   if( pExpr->iColumn>=0 && pMatch!=0 ){
59413     int n = pExpr->iColumn;
59414     testcase( n==BMS-1 );
59415     if( n>=BMS ){
59416       n = BMS-1;
59417     }
59418     assert( pMatch->iCursor==pExpr->iTable );
59419     pMatch->colUsed |= ((Bitmask)1)<<n;
59420   }
59421
59422   /* Clean up and return
59423   */
59424   sqlite3ExprDelete(db, pExpr->pLeft);
59425   pExpr->pLeft = 0;
59426   sqlite3ExprDelete(db, pExpr->pRight);
59427   pExpr->pRight = 0;
59428   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
59429 lookupname_end:
59430   if( cnt==1 ){
59431     assert( pNC!=0 );
59432     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
59433     /* Increment the nRef value on all name contexts from TopNC up to
59434     ** the point where the name matched. */
59435     for(;;){
59436       assert( pTopNC!=0 );
59437       pTopNC->nRef++;
59438       if( pTopNC==pNC ) break;
59439       pTopNC = pTopNC->pNext;
59440     }
59441     return WRC_Prune;
59442   } else {
59443     return WRC_Abort;
59444   }
59445 }
59446
59447 /*
59448 ** Allocate and return a pointer to an expression to load the column iCol
59449 ** from datasource iSrc datasource in SrcList pSrc.
59450 */
59451 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
59452   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
59453   if( p ){
59454     struct SrcList_item *pItem = &pSrc->a[iSrc];
59455     p->pTab = pItem->pTab;
59456     p->iTable = pItem->iCursor;
59457     if( p->pTab->iPKey==iCol ){
59458       p->iColumn = -1;
59459     }else{
59460       p->iColumn = (ynVar)iCol;
59461       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
59462     }
59463     ExprSetProperty(p, EP_Resolved);
59464   }
59465   return p;
59466 }
59467
59468 /*
59469 ** This routine is callback for sqlite3WalkExpr().
59470 **
59471 ** Resolve symbolic names into TK_COLUMN operators for the current
59472 ** node in the expression tree.  Return 0 to continue the search down
59473 ** the tree or 2 to abort the tree walk.
59474 **
59475 ** This routine also does error checking and name resolution for
59476 ** function names.  The operator for aggregate functions is changed
59477 ** to TK_AGG_FUNCTION.
59478 */
59479 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
59480   NameContext *pNC;
59481   Parse *pParse;
59482
59483   pNC = pWalker->u.pNC;
59484   assert( pNC!=0 );
59485   pParse = pNC->pParse;
59486   assert( pParse==pWalker->pParse );
59487
59488   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
59489   ExprSetProperty(pExpr, EP_Resolved);
59490 #ifndef NDEBUG
59491   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
59492     SrcList *pSrcList = pNC->pSrcList;
59493     int i;
59494     for(i=0; i<pNC->pSrcList->nSrc; i++){
59495       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
59496     }
59497   }
59498 #endif
59499   switch( pExpr->op ){
59500
59501 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
59502     /* The special operator TK_ROW means use the rowid for the first
59503     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
59504     ** clause processing on UPDATE and DELETE statements.
59505     */
59506     case TK_ROW: {
59507       SrcList *pSrcList = pNC->pSrcList;
59508       struct SrcList_item *pItem;
59509       assert( pSrcList && pSrcList->nSrc==1 );
59510       pItem = pSrcList->a; 
59511       pExpr->op = TK_COLUMN;
59512       pExpr->pTab = pItem->pTab;
59513       pExpr->iTable = pItem->iCursor;
59514       pExpr->iColumn = -1;
59515       pExpr->affinity = SQLITE_AFF_INTEGER;
59516       break;
59517     }
59518 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
59519
59520     /* A lone identifier is the name of a column.
59521     */
59522     case TK_ID: {
59523       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
59524     }
59525   
59526     /* A table name and column name:     ID.ID
59527     ** Or a database, table and column:  ID.ID.ID
59528     */
59529     case TK_DOT: {
59530       const char *zColumn;
59531       const char *zTable;
59532       const char *zDb;
59533       Expr *pRight;
59534
59535       /* if( pSrcList==0 ) break; */
59536       pRight = pExpr->pRight;
59537       if( pRight->op==TK_ID ){
59538         zDb = 0;
59539         zTable = pExpr->pLeft->u.zToken;
59540         zColumn = pRight->u.zToken;
59541       }else{
59542         assert( pRight->op==TK_DOT );
59543         zDb = pExpr->pLeft->u.zToken;
59544         zTable = pRight->pLeft->u.zToken;
59545         zColumn = pRight->pRight->u.zToken;
59546       }
59547       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
59548     }
59549
59550     /* Resolve function names
59551     */
59552     case TK_CONST_FUNC:
59553     case TK_FUNCTION: {
59554       ExprList *pList = pExpr->x.pList;    /* The argument list */
59555       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
59556       int no_such_func = 0;       /* True if no such function exists */
59557       int wrong_num_args = 0;     /* True if wrong number of arguments */
59558       int is_agg = 0;             /* True if is an aggregate function */
59559       int auth;                   /* Authorization to use the function */
59560       int nId;                    /* Number of characters in function name */
59561       const char *zId;            /* The function name. */
59562       FuncDef *pDef;              /* Information about the function */
59563       u8 enc = ENC(pParse->db);   /* The database encoding */
59564
59565       testcase( pExpr->op==TK_CONST_FUNC );
59566       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
59567       zId = pExpr->u.zToken;
59568       nId = sqlite3Strlen30(zId);
59569       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
59570       if( pDef==0 ){
59571         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
59572         if( pDef==0 ){
59573           no_such_func = 1;
59574         }else{
59575           wrong_num_args = 1;
59576         }
59577       }else{
59578         is_agg = pDef->xFunc==0;
59579       }
59580 #ifndef SQLITE_OMIT_AUTHORIZATION
59581       if( pDef ){
59582         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
59583         if( auth!=SQLITE_OK ){
59584           if( auth==SQLITE_DENY ){
59585             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
59586                                     pDef->zName);
59587             pNC->nErr++;
59588           }
59589           pExpr->op = TK_NULL;
59590           return WRC_Prune;
59591         }
59592       }
59593 #endif
59594       if( is_agg && !pNC->allowAgg ){
59595         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
59596         pNC->nErr++;
59597         is_agg = 0;
59598       }else if( no_such_func ){
59599         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
59600         pNC->nErr++;
59601       }else if( wrong_num_args ){
59602         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
59603              nId, zId);
59604         pNC->nErr++;
59605       }
59606       if( is_agg ){
59607         pExpr->op = TK_AGG_FUNCTION;
59608         pNC->hasAgg = 1;
59609       }
59610       if( is_agg ) pNC->allowAgg = 0;
59611       sqlite3WalkExprList(pWalker, pList);
59612       if( is_agg ) pNC->allowAgg = 1;
59613       /* FIX ME:  Compute pExpr->affinity based on the expected return
59614       ** type of the function 
59615       */
59616       return WRC_Prune;
59617     }
59618 #ifndef SQLITE_OMIT_SUBQUERY
59619     case TK_SELECT:
59620     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
59621 #endif
59622     case TK_IN: {
59623       testcase( pExpr->op==TK_IN );
59624       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
59625         int nRef = pNC->nRef;
59626 #ifndef SQLITE_OMIT_CHECK
59627         if( pNC->isCheck ){
59628           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
59629         }
59630 #endif
59631         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
59632         assert( pNC->nRef>=nRef );
59633         if( nRef!=pNC->nRef ){
59634           ExprSetProperty(pExpr, EP_VarSelect);
59635         }
59636       }
59637       break;
59638     }
59639 #ifndef SQLITE_OMIT_CHECK
59640     case TK_VARIABLE: {
59641       if( pNC->isCheck ){
59642         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
59643       }
59644       break;
59645     }
59646 #endif
59647   }
59648   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
59649 }
59650
59651 /*
59652 ** pEList is a list of expressions which are really the result set of the
59653 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
59654 ** This routine checks to see if pE is a simple identifier which corresponds
59655 ** to the AS-name of one of the terms of the expression list.  If it is,
59656 ** this routine return an integer between 1 and N where N is the number of
59657 ** elements in pEList, corresponding to the matching entry.  If there is
59658 ** no match, or if pE is not a simple identifier, then this routine
59659 ** return 0.
59660 **
59661 ** pEList has been resolved.  pE has not.
59662 */
59663 static int resolveAsName(
59664   Parse *pParse,     /* Parsing context for error messages */
59665   ExprList *pEList,  /* List of expressions to scan */
59666   Expr *pE           /* Expression we are trying to match */
59667 ){
59668   int i;             /* Loop counter */
59669
59670   UNUSED_PARAMETER(pParse);
59671
59672   if( pE->op==TK_ID ){
59673     char *zCol = pE->u.zToken;
59674     for(i=0; i<pEList->nExpr; i++){
59675       char *zAs = pEList->a[i].zName;
59676       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
59677         return i+1;
59678       }
59679     }
59680   }
59681   return 0;
59682 }
59683
59684 /*
59685 ** pE is a pointer to an expression which is a single term in the
59686 ** ORDER BY of a compound SELECT.  The expression has not been
59687 ** name resolved.
59688 **
59689 ** At the point this routine is called, we already know that the
59690 ** ORDER BY term is not an integer index into the result set.  That
59691 ** case is handled by the calling routine.
59692 **
59693 ** Attempt to match pE against result set columns in the left-most
59694 ** SELECT statement.  Return the index i of the matching column,
59695 ** as an indication to the caller that it should sort by the i-th column.
59696 ** The left-most column is 1.  In other words, the value returned is the
59697 ** same integer value that would be used in the SQL statement to indicate
59698 ** the column.
59699 **
59700 ** If there is no match, return 0.  Return -1 if an error occurs.
59701 */
59702 static int resolveOrderByTermToExprList(
59703   Parse *pParse,     /* Parsing context for error messages */
59704   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
59705   Expr *pE           /* The specific ORDER BY term */
59706 ){
59707   int i;             /* Loop counter */
59708   ExprList *pEList;  /* The columns of the result set */
59709   NameContext nc;    /* Name context for resolving pE */
59710
59711   assert( sqlite3ExprIsInteger(pE, &i)==0 );
59712   pEList = pSelect->pEList;
59713
59714   /* Resolve all names in the ORDER BY term expression
59715   */
59716   memset(&nc, 0, sizeof(nc));
59717   nc.pParse = pParse;
59718   nc.pSrcList = pSelect->pSrc;
59719   nc.pEList = pEList;
59720   nc.allowAgg = 1;
59721   nc.nErr = 0;
59722   if( sqlite3ResolveExprNames(&nc, pE) ){
59723     sqlite3ErrorClear(pParse);
59724     return 0;
59725   }
59726
59727   /* Try to match the ORDER BY expression against an expression
59728   ** in the result set.  Return an 1-based index of the matching
59729   ** result-set entry.
59730   */
59731   for(i=0; i<pEList->nExpr; i++){
59732     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
59733       return i+1;
59734     }
59735   }
59736
59737   /* If no match, return 0. */
59738   return 0;
59739 }
59740
59741 /*
59742 ** Generate an ORDER BY or GROUP BY term out-of-range error.
59743 */
59744 static void resolveOutOfRangeError(
59745   Parse *pParse,         /* The error context into which to write the error */
59746   const char *zType,     /* "ORDER" or "GROUP" */
59747   int i,                 /* The index (1-based) of the term out of range */
59748   int mx                 /* Largest permissible value of i */
59749 ){
59750   sqlite3ErrorMsg(pParse, 
59751     "%r %s BY term out of range - should be "
59752     "between 1 and %d", i, zType, mx);
59753 }
59754
59755 /*
59756 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
59757 ** each term of the ORDER BY clause is a constant integer between 1
59758 ** and N where N is the number of columns in the compound SELECT.
59759 **
59760 ** ORDER BY terms that are already an integer between 1 and N are
59761 ** unmodified.  ORDER BY terms that are integers outside the range of
59762 ** 1 through N generate an error.  ORDER BY terms that are expressions
59763 ** are matched against result set expressions of compound SELECT
59764 ** beginning with the left-most SELECT and working toward the right.
59765 ** At the first match, the ORDER BY expression is transformed into
59766 ** the integer column number.
59767 **
59768 ** Return the number of errors seen.
59769 */
59770 static int resolveCompoundOrderBy(
59771   Parse *pParse,        /* Parsing context.  Leave error messages here */
59772   Select *pSelect       /* The SELECT statement containing the ORDER BY */
59773 ){
59774   int i;
59775   ExprList *pOrderBy;
59776   ExprList *pEList;
59777   sqlite3 *db;
59778   int moreToDo = 1;
59779
59780   pOrderBy = pSelect->pOrderBy;
59781   if( pOrderBy==0 ) return 0;
59782   db = pParse->db;
59783 #if SQLITE_MAX_COLUMN
59784   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
59785     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
59786     return 1;
59787   }
59788 #endif
59789   for(i=0; i<pOrderBy->nExpr; i++){
59790     pOrderBy->a[i].done = 0;
59791   }
59792   pSelect->pNext = 0;
59793   while( pSelect->pPrior ){
59794     pSelect->pPrior->pNext = pSelect;
59795     pSelect = pSelect->pPrior;
59796   }
59797   while( pSelect && moreToDo ){
59798     struct ExprList_item *pItem;
59799     moreToDo = 0;
59800     pEList = pSelect->pEList;
59801     assert( pEList!=0 );
59802     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
59803       int iCol = -1;
59804       Expr *pE, *pDup;
59805       if( pItem->done ) continue;
59806       pE = pItem->pExpr;
59807       if( sqlite3ExprIsInteger(pE, &iCol) ){
59808         if( iCol<=0 || iCol>pEList->nExpr ){
59809           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
59810           return 1;
59811         }
59812       }else{
59813         iCol = resolveAsName(pParse, pEList, pE);
59814         if( iCol==0 ){
59815           pDup = sqlite3ExprDup(db, pE, 0);
59816           if( !db->mallocFailed ){
59817             assert(pDup);
59818             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
59819           }
59820           sqlite3ExprDelete(db, pDup);
59821         }
59822       }
59823       if( iCol>0 ){
59824         CollSeq *pColl = pE->pColl;
59825         int flags = pE->flags & EP_ExpCollate;
59826         sqlite3ExprDelete(db, pE);
59827         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
59828         if( pE==0 ) return 1;
59829         pE->pColl = pColl;
59830         pE->flags |= EP_IntValue | flags;
59831         pE->u.iValue = iCol;
59832         pItem->iCol = (u16)iCol;
59833         pItem->done = 1;
59834       }else{
59835         moreToDo = 1;
59836       }
59837     }
59838     pSelect = pSelect->pNext;
59839   }
59840   for(i=0; i<pOrderBy->nExpr; i++){
59841     if( pOrderBy->a[i].done==0 ){
59842       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
59843             "column in the result set", i+1);
59844       return 1;
59845     }
59846   }
59847   return 0;
59848 }
59849
59850 /*
59851 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
59852 ** the SELECT statement pSelect.  If any term is reference to a
59853 ** result set expression (as determined by the ExprList.a.iCol field)
59854 ** then convert that term into a copy of the corresponding result set
59855 ** column.
59856 **
59857 ** If any errors are detected, add an error message to pParse and
59858 ** return non-zero.  Return zero if no errors are seen.
59859 */
59860 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
59861   Parse *pParse,        /* Parsing context.  Leave error messages here */
59862   Select *pSelect,      /* The SELECT statement containing the clause */
59863   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
59864   const char *zType     /* "ORDER" or "GROUP" */
59865 ){
59866   int i;
59867   sqlite3 *db = pParse->db;
59868   ExprList *pEList;
59869   struct ExprList_item *pItem;
59870
59871   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
59872 #if SQLITE_MAX_COLUMN
59873   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
59874     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
59875     return 1;
59876   }
59877 #endif
59878   pEList = pSelect->pEList;
59879   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
59880   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
59881     if( pItem->iCol ){
59882       if( pItem->iCol>pEList->nExpr ){
59883         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
59884         return 1;
59885       }
59886       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
59887     }
59888   }
59889   return 0;
59890 }
59891
59892 /*
59893 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
59894 ** The Name context of the SELECT statement is pNC.  zType is either
59895 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
59896 **
59897 ** This routine resolves each term of the clause into an expression.
59898 ** If the order-by term is an integer I between 1 and N (where N is the
59899 ** number of columns in the result set of the SELECT) then the expression
59900 ** in the resolution is a copy of the I-th result-set expression.  If
59901 ** the order-by term is an identify that corresponds to the AS-name of
59902 ** a result-set expression, then the term resolves to a copy of the
59903 ** result-set expression.  Otherwise, the expression is resolved in
59904 ** the usual way - using sqlite3ResolveExprNames().
59905 **
59906 ** This routine returns the number of errors.  If errors occur, then
59907 ** an appropriate error message might be left in pParse.  (OOM errors
59908 ** excepted.)
59909 */
59910 static int resolveOrderGroupBy(
59911   NameContext *pNC,     /* The name context of the SELECT statement */
59912   Select *pSelect,      /* The SELECT statement holding pOrderBy */
59913   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
59914   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
59915 ){
59916   int i;                         /* Loop counter */
59917   int iCol;                      /* Column number */
59918   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
59919   Parse *pParse;                 /* Parsing context */
59920   int nResult;                   /* Number of terms in the result set */
59921
59922   if( pOrderBy==0 ) return 0;
59923   nResult = pSelect->pEList->nExpr;
59924   pParse = pNC->pParse;
59925   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
59926     Expr *pE = pItem->pExpr;
59927     iCol = resolveAsName(pParse, pSelect->pEList, pE);
59928     if( iCol>0 ){
59929       /* If an AS-name match is found, mark this ORDER BY column as being
59930       ** a copy of the iCol-th result-set column.  The subsequent call to
59931       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
59932       ** copy of the iCol-th result-set expression. */
59933       pItem->iCol = (u16)iCol;
59934       continue;
59935     }
59936     if( sqlite3ExprIsInteger(pE, &iCol) ){
59937       /* The ORDER BY term is an integer constant.  Again, set the column
59938       ** number so that sqlite3ResolveOrderGroupBy() will convert the
59939       ** order-by term to a copy of the result-set expression */
59940       if( iCol<1 ){
59941         resolveOutOfRangeError(pParse, zType, i+1, nResult);
59942         return 1;
59943       }
59944       pItem->iCol = (u16)iCol;
59945       continue;
59946     }
59947
59948     /* Otherwise, treat the ORDER BY term as an ordinary expression */
59949     pItem->iCol = 0;
59950     if( sqlite3ResolveExprNames(pNC, pE) ){
59951       return 1;
59952     }
59953   }
59954   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
59955 }
59956
59957 /*
59958 ** Resolve names in the SELECT statement p and all of its descendents.
59959 */
59960 static int resolveSelectStep(Walker *pWalker, Select *p){
59961   NameContext *pOuterNC;  /* Context that contains this SELECT */
59962   NameContext sNC;        /* Name context of this SELECT */
59963   int isCompound;         /* True if p is a compound select */
59964   int nCompound;          /* Number of compound terms processed so far */
59965   Parse *pParse;          /* Parsing context */
59966   ExprList *pEList;       /* Result set expression list */
59967   int i;                  /* Loop counter */
59968   ExprList *pGroupBy;     /* The GROUP BY clause */
59969   Select *pLeftmost;      /* Left-most of SELECT of a compound */
59970   sqlite3 *db;            /* Database connection */
59971   
59972
59973   assert( p!=0 );
59974   if( p->selFlags & SF_Resolved ){
59975     return WRC_Prune;
59976   }
59977   pOuterNC = pWalker->u.pNC;
59978   pParse = pWalker->pParse;
59979   db = pParse->db;
59980
59981   /* Normally sqlite3SelectExpand() will be called first and will have
59982   ** already expanded this SELECT.  However, if this is a subquery within
59983   ** an expression, sqlite3ResolveExprNames() will be called without a
59984   ** prior call to sqlite3SelectExpand().  When that happens, let
59985   ** sqlite3SelectPrep() do all of the processing for this SELECT.
59986   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
59987   ** this routine in the correct order.
59988   */
59989   if( (p->selFlags & SF_Expanded)==0 ){
59990     sqlite3SelectPrep(pParse, p, pOuterNC);
59991     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
59992   }
59993
59994   isCompound = p->pPrior!=0;
59995   nCompound = 0;
59996   pLeftmost = p;
59997   while( p ){
59998     assert( (p->selFlags & SF_Expanded)!=0 );
59999     assert( (p->selFlags & SF_Resolved)==0 );
60000     p->selFlags |= SF_Resolved;
60001
60002     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
60003     ** are not allowed to refer to any names, so pass an empty NameContext.
60004     */
60005     memset(&sNC, 0, sizeof(sNC));
60006     sNC.pParse = pParse;
60007     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
60008         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
60009       return WRC_Abort;
60010     }
60011   
60012     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
60013     ** resolve the result-set expression list.
60014     */
60015     sNC.allowAgg = 1;
60016     sNC.pSrcList = p->pSrc;
60017     sNC.pNext = pOuterNC;
60018   
60019     /* Resolve names in the result set. */
60020     pEList = p->pEList;
60021     assert( pEList!=0 );
60022     for(i=0; i<pEList->nExpr; i++){
60023       Expr *pX = pEList->a[i].pExpr;
60024       if( sqlite3ResolveExprNames(&sNC, pX) ){
60025         return WRC_Abort;
60026       }
60027     }
60028   
60029     /* Recursively resolve names in all subqueries
60030     */
60031     for(i=0; i<p->pSrc->nSrc; i++){
60032       struct SrcList_item *pItem = &p->pSrc->a[i];
60033       if( pItem->pSelect ){
60034         const char *zSavedContext = pParse->zAuthContext;
60035         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
60036         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
60037         pParse->zAuthContext = zSavedContext;
60038         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
60039       }
60040     }
60041   
60042     /* If there are no aggregate functions in the result-set, and no GROUP BY 
60043     ** expression, do not allow aggregates in any of the other expressions.
60044     */
60045     assert( (p->selFlags & SF_Aggregate)==0 );
60046     pGroupBy = p->pGroupBy;
60047     if( pGroupBy || sNC.hasAgg ){
60048       p->selFlags |= SF_Aggregate;
60049     }else{
60050       sNC.allowAgg = 0;
60051     }
60052   
60053     /* If a HAVING clause is present, then there must be a GROUP BY clause.
60054     */
60055     if( p->pHaving && !pGroupBy ){
60056       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
60057       return WRC_Abort;
60058     }
60059   
60060     /* Add the expression list to the name-context before parsing the
60061     ** other expressions in the SELECT statement. This is so that
60062     ** expressions in the WHERE clause (etc.) can refer to expressions by
60063     ** aliases in the result set.
60064     **
60065     ** Minor point: If this is the case, then the expression will be
60066     ** re-evaluated for each reference to it.
60067     */
60068     sNC.pEList = p->pEList;
60069     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
60070        sqlite3ResolveExprNames(&sNC, p->pHaving)
60071     ){
60072       return WRC_Abort;
60073     }
60074
60075     /* The ORDER BY and GROUP BY clauses may not refer to terms in
60076     ** outer queries 
60077     */
60078     sNC.pNext = 0;
60079     sNC.allowAgg = 1;
60080
60081     /* Process the ORDER BY clause for singleton SELECT statements.
60082     ** The ORDER BY clause for compounds SELECT statements is handled
60083     ** below, after all of the result-sets for all of the elements of
60084     ** the compound have been resolved.
60085     */
60086     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
60087       return WRC_Abort;
60088     }
60089     if( db->mallocFailed ){
60090       return WRC_Abort;
60091     }
60092   
60093     /* Resolve the GROUP BY clause.  At the same time, make sure 
60094     ** the GROUP BY clause does not contain aggregate functions.
60095     */
60096     if( pGroupBy ){
60097       struct ExprList_item *pItem;
60098     
60099       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
60100         return WRC_Abort;
60101       }
60102       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
60103         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
60104           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
60105               "the GROUP BY clause");
60106           return WRC_Abort;
60107         }
60108       }
60109     }
60110
60111     /* Advance to the next term of the compound
60112     */
60113     p = p->pPrior;
60114     nCompound++;
60115   }
60116
60117   /* Resolve the ORDER BY on a compound SELECT after all terms of
60118   ** the compound have been resolved.
60119   */
60120   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
60121     return WRC_Abort;
60122   }
60123
60124   return WRC_Prune;
60125 }
60126
60127 /*
60128 ** This routine walks an expression tree and resolves references to
60129 ** table columns and result-set columns.  At the same time, do error
60130 ** checking on function usage and set a flag if any aggregate functions
60131 ** are seen.
60132 **
60133 ** To resolve table columns references we look for nodes (or subtrees) of the 
60134 ** form X.Y.Z or Y.Z or just Z where
60135 **
60136 **      X:   The name of a database.  Ex:  "main" or "temp" or
60137 **           the symbolic name assigned to an ATTACH-ed database.
60138 **
60139 **      Y:   The name of a table in a FROM clause.  Or in a trigger
60140 **           one of the special names "old" or "new".
60141 **
60142 **      Z:   The name of a column in table Y.
60143 **
60144 ** The node at the root of the subtree is modified as follows:
60145 **
60146 **    Expr.op        Changed to TK_COLUMN
60147 **    Expr.pTab      Points to the Table object for X.Y
60148 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
60149 **    Expr.iTable    The VDBE cursor number for X.Y
60150 **
60151 **
60152 ** To resolve result-set references, look for expression nodes of the
60153 ** form Z (with no X and Y prefix) where the Z matches the right-hand
60154 ** size of an AS clause in the result-set of a SELECT.  The Z expression
60155 ** is replaced by a copy of the left-hand side of the result-set expression.
60156 ** Table-name and function resolution occurs on the substituted expression
60157 ** tree.  For example, in:
60158 **
60159 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
60160 **
60161 ** The "x" term of the order by is replaced by "a+b" to render:
60162 **
60163 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
60164 **
60165 ** Function calls are checked to make sure that the function is 
60166 ** defined and that the correct number of arguments are specified.
60167 ** If the function is an aggregate function, then the pNC->hasAgg is
60168 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
60169 ** If an expression contains aggregate functions then the EP_Agg
60170 ** property on the expression is set.
60171 **
60172 ** An error message is left in pParse if anything is amiss.  The number
60173 ** if errors is returned.
60174 */
60175 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
60176   NameContext *pNC,       /* Namespace to resolve expressions in. */
60177   Expr *pExpr             /* The expression to be analyzed. */
60178 ){
60179   int savedHasAgg;
60180   Walker w;
60181
60182   if( pExpr==0 ) return 0;
60183 #if SQLITE_MAX_EXPR_DEPTH>0
60184   {
60185     Parse *pParse = pNC->pParse;
60186     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
60187       return 1;
60188     }
60189     pParse->nHeight += pExpr->nHeight;
60190   }
60191 #endif
60192   savedHasAgg = pNC->hasAgg;
60193   pNC->hasAgg = 0;
60194   w.xExprCallback = resolveExprStep;
60195   w.xSelectCallback = resolveSelectStep;
60196   w.pParse = pNC->pParse;
60197   w.u.pNC = pNC;
60198   sqlite3WalkExpr(&w, pExpr);
60199 #if SQLITE_MAX_EXPR_DEPTH>0
60200   pNC->pParse->nHeight -= pExpr->nHeight;
60201 #endif
60202   if( pNC->nErr>0 || w.pParse->nErr>0 ){
60203     ExprSetProperty(pExpr, EP_Error);
60204   }
60205   if( pNC->hasAgg ){
60206     ExprSetProperty(pExpr, EP_Agg);
60207   }else if( savedHasAgg ){
60208     pNC->hasAgg = 1;
60209   }
60210   return ExprHasProperty(pExpr, EP_Error);
60211 }
60212
60213
60214 /*
60215 ** Resolve all names in all expressions of a SELECT and in all
60216 ** decendents of the SELECT, including compounds off of p->pPrior,
60217 ** subqueries in expressions, and subqueries used as FROM clause
60218 ** terms.
60219 **
60220 ** See sqlite3ResolveExprNames() for a description of the kinds of
60221 ** transformations that occur.
60222 **
60223 ** All SELECT statements should have been expanded using
60224 ** sqlite3SelectExpand() prior to invoking this routine.
60225 */
60226 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
60227   Parse *pParse,         /* The parser context */
60228   Select *p,             /* The SELECT statement being coded. */
60229   NameContext *pOuterNC  /* Name context for parent SELECT statement */
60230 ){
60231   Walker w;
60232
60233   assert( p!=0 );
60234   w.xExprCallback = resolveExprStep;
60235   w.xSelectCallback = resolveSelectStep;
60236   w.pParse = pParse;
60237   w.u.pNC = pOuterNC;
60238   sqlite3WalkSelect(&w, p);
60239 }
60240
60241 /************** End of resolve.c *********************************************/
60242 /************** Begin file expr.c ********************************************/
60243 /*
60244 ** 2001 September 15
60245 **
60246 ** The author disclaims copyright to this source code.  In place of
60247 ** a legal notice, here is a blessing:
60248 **
60249 **    May you do good and not evil.
60250 **    May you find forgiveness for yourself and forgive others.
60251 **    May you share freely, never taking more than you give.
60252 **
60253 *************************************************************************
60254 ** This file contains routines used for analyzing expressions and
60255 ** for generating VDBE code that evaluates expressions in SQLite.
60256 */
60257
60258 /*
60259 ** Return the 'affinity' of the expression pExpr if any.
60260 **
60261 ** If pExpr is a column, a reference to a column via an 'AS' alias,
60262 ** or a sub-select with a column as the return value, then the 
60263 ** affinity of that column is returned. Otherwise, 0x00 is returned,
60264 ** indicating no affinity for the expression.
60265 **
60266 ** i.e. the WHERE clause expresssions in the following statements all
60267 ** have an affinity:
60268 **
60269 ** CREATE TABLE t1(a);
60270 ** SELECT * FROM t1 WHERE a;
60271 ** SELECT a AS b FROM t1 WHERE b;
60272 ** SELECT * FROM t1 WHERE (select a from t1);
60273 */
60274 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
60275   int op = pExpr->op;
60276   if( op==TK_SELECT ){
60277     assert( pExpr->flags&EP_xIsSelect );
60278     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
60279   }
60280 #ifndef SQLITE_OMIT_CAST
60281   if( op==TK_CAST ){
60282     assert( !ExprHasProperty(pExpr, EP_IntValue) );
60283     return sqlite3AffinityType(pExpr->u.zToken);
60284   }
60285 #endif
60286   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
60287    && pExpr->pTab!=0
60288   ){
60289     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
60290     ** a TK_COLUMN but was previously evaluated and cached in a register */
60291     int j = pExpr->iColumn;
60292     if( j<0 ) return SQLITE_AFF_INTEGER;
60293     assert( pExpr->pTab && j<pExpr->pTab->nCol );
60294     return pExpr->pTab->aCol[j].affinity;
60295   }
60296   return pExpr->affinity;
60297 }
60298
60299 /*
60300 ** Set the collating sequence for expression pExpr to be the collating
60301 ** sequence named by pToken.   Return a pointer to the revised expression.
60302 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
60303 ** flag.  An explicit collating sequence will override implicit
60304 ** collating sequences.
60305 */
60306 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
60307   char *zColl = 0;            /* Dequoted name of collation sequence */
60308   CollSeq *pColl;
60309   sqlite3 *db = pParse->db;
60310   zColl = sqlite3NameFromToken(db, pCollName);
60311   if( pExpr && zColl ){
60312     pColl = sqlite3LocateCollSeq(pParse, zColl);
60313     if( pColl ){
60314       pExpr->pColl = pColl;
60315       pExpr->flags |= EP_ExpCollate;
60316     }
60317   }
60318   sqlite3DbFree(db, zColl);
60319   return pExpr;
60320 }
60321
60322 /*
60323 ** Return the default collation sequence for the expression pExpr. If
60324 ** there is no default collation type, return 0.
60325 */
60326 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
60327   CollSeq *pColl = 0;
60328   Expr *p = pExpr;
60329   while( ALWAYS(p) ){
60330     int op;
60331     pColl = p->pColl;
60332     if( pColl ) break;
60333     op = p->op;
60334     if( p->pTab!=0 && (
60335         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
60336     )){
60337       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
60338       ** a TK_COLUMN but was previously evaluated and cached in a register */
60339       const char *zColl;
60340       int j = p->iColumn;
60341       if( j>=0 ){
60342         sqlite3 *db = pParse->db;
60343         zColl = p->pTab->aCol[j].zColl;
60344         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
60345         pExpr->pColl = pColl;
60346       }
60347       break;
60348     }
60349     if( op!=TK_CAST && op!=TK_UPLUS ){
60350       break;
60351     }
60352     p = p->pLeft;
60353   }
60354   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
60355     pColl = 0;
60356   }
60357   return pColl;
60358 }
60359
60360 /*
60361 ** pExpr is an operand of a comparison operator.  aff2 is the
60362 ** type affinity of the other operand.  This routine returns the
60363 ** type affinity that should be used for the comparison operator.
60364 */
60365 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
60366   char aff1 = sqlite3ExprAffinity(pExpr);
60367   if( aff1 && aff2 ){
60368     /* Both sides of the comparison are columns. If one has numeric
60369     ** affinity, use that. Otherwise use no affinity.
60370     */
60371     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
60372       return SQLITE_AFF_NUMERIC;
60373     }else{
60374       return SQLITE_AFF_NONE;
60375     }
60376   }else if( !aff1 && !aff2 ){
60377     /* Neither side of the comparison is a column.  Compare the
60378     ** results directly.
60379     */
60380     return SQLITE_AFF_NONE;
60381   }else{
60382     /* One side is a column, the other is not. Use the columns affinity. */
60383     assert( aff1==0 || aff2==0 );
60384     return (aff1 + aff2);
60385   }
60386 }
60387
60388 /*
60389 ** pExpr is a comparison operator.  Return the type affinity that should
60390 ** be applied to both operands prior to doing the comparison.
60391 */
60392 static char comparisonAffinity(Expr *pExpr){
60393   char aff;
60394   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
60395           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
60396           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
60397   assert( pExpr->pLeft );
60398   aff = sqlite3ExprAffinity(pExpr->pLeft);
60399   if( pExpr->pRight ){
60400     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
60401   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
60402     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
60403   }else if( !aff ){
60404     aff = SQLITE_AFF_NONE;
60405   }
60406   return aff;
60407 }
60408
60409 /*
60410 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
60411 ** idx_affinity is the affinity of an indexed column. Return true
60412 ** if the index with affinity idx_affinity may be used to implement
60413 ** the comparison in pExpr.
60414 */
60415 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
60416   char aff = comparisonAffinity(pExpr);
60417   switch( aff ){
60418     case SQLITE_AFF_NONE:
60419       return 1;
60420     case SQLITE_AFF_TEXT:
60421       return idx_affinity==SQLITE_AFF_TEXT;
60422     default:
60423       return sqlite3IsNumericAffinity(idx_affinity);
60424   }
60425 }
60426
60427 /*
60428 ** Return the P5 value that should be used for a binary comparison
60429 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
60430 */
60431 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
60432   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
60433   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
60434   return aff;
60435 }
60436
60437 /*
60438 ** Return a pointer to the collation sequence that should be used by
60439 ** a binary comparison operator comparing pLeft and pRight.
60440 **
60441 ** If the left hand expression has a collating sequence type, then it is
60442 ** used. Otherwise the collation sequence for the right hand expression
60443 ** is used, or the default (BINARY) if neither expression has a collating
60444 ** type.
60445 **
60446 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
60447 ** it is not considered.
60448 */
60449 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
60450   Parse *pParse, 
60451   Expr *pLeft, 
60452   Expr *pRight
60453 ){
60454   CollSeq *pColl;
60455   assert( pLeft );
60456   if( pLeft->flags & EP_ExpCollate ){
60457     assert( pLeft->pColl );
60458     pColl = pLeft->pColl;
60459   }else if( pRight && pRight->flags & EP_ExpCollate ){
60460     assert( pRight->pColl );
60461     pColl = pRight->pColl;
60462   }else{
60463     pColl = sqlite3ExprCollSeq(pParse, pLeft);
60464     if( !pColl ){
60465       pColl = sqlite3ExprCollSeq(pParse, pRight);
60466     }
60467   }
60468   return pColl;
60469 }
60470
60471 /*
60472 ** Generate code for a comparison operator.
60473 */
60474 static int codeCompare(
60475   Parse *pParse,    /* The parsing (and code generating) context */
60476   Expr *pLeft,      /* The left operand */
60477   Expr *pRight,     /* The right operand */
60478   int opcode,       /* The comparison opcode */
60479   int in1, int in2, /* Register holding operands */
60480   int dest,         /* Jump here if true.  */
60481   int jumpIfNull    /* If true, jump if either operand is NULL */
60482 ){
60483   int p5;
60484   int addr;
60485   CollSeq *p4;
60486
60487   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
60488   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
60489   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
60490                            (void*)p4, P4_COLLSEQ);
60491   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
60492   if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
60493     sqlite3ExprCacheAffinityChange(pParse, in1, 1);
60494     sqlite3ExprCacheAffinityChange(pParse, in2, 1);
60495   }
60496   return addr;
60497 }
60498
60499 #if SQLITE_MAX_EXPR_DEPTH>0
60500 /*
60501 ** Check that argument nHeight is less than or equal to the maximum
60502 ** expression depth allowed. If it is not, leave an error message in
60503 ** pParse.
60504 */
60505 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
60506   int rc = SQLITE_OK;
60507   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
60508   if( nHeight>mxHeight ){
60509     sqlite3ErrorMsg(pParse, 
60510        "Expression tree is too large (maximum depth %d)", mxHeight
60511     );
60512     rc = SQLITE_ERROR;
60513   }
60514   return rc;
60515 }
60516
60517 /* The following three functions, heightOfExpr(), heightOfExprList()
60518 ** and heightOfSelect(), are used to determine the maximum height
60519 ** of any expression tree referenced by the structure passed as the
60520 ** first argument.
60521 **
60522 ** If this maximum height is greater than the current value pointed
60523 ** to by pnHeight, the second parameter, then set *pnHeight to that
60524 ** value.
60525 */
60526 static void heightOfExpr(Expr *p, int *pnHeight){
60527   if( p ){
60528     if( p->nHeight>*pnHeight ){
60529       *pnHeight = p->nHeight;
60530     }
60531   }
60532 }
60533 static void heightOfExprList(ExprList *p, int *pnHeight){
60534   if( p ){
60535     int i;
60536     for(i=0; i<p->nExpr; i++){
60537       heightOfExpr(p->a[i].pExpr, pnHeight);
60538     }
60539   }
60540 }
60541 static void heightOfSelect(Select *p, int *pnHeight){
60542   if( p ){
60543     heightOfExpr(p->pWhere, pnHeight);
60544     heightOfExpr(p->pHaving, pnHeight);
60545     heightOfExpr(p->pLimit, pnHeight);
60546     heightOfExpr(p->pOffset, pnHeight);
60547     heightOfExprList(p->pEList, pnHeight);
60548     heightOfExprList(p->pGroupBy, pnHeight);
60549     heightOfExprList(p->pOrderBy, pnHeight);
60550     heightOfSelect(p->pPrior, pnHeight);
60551   }
60552 }
60553
60554 /*
60555 ** Set the Expr.nHeight variable in the structure passed as an 
60556 ** argument. An expression with no children, Expr.pList or 
60557 ** Expr.pSelect member has a height of 1. Any other expression
60558 ** has a height equal to the maximum height of any other 
60559 ** referenced Expr plus one.
60560 */
60561 static void exprSetHeight(Expr *p){
60562   int nHeight = 0;
60563   heightOfExpr(p->pLeft, &nHeight);
60564   heightOfExpr(p->pRight, &nHeight);
60565   if( ExprHasProperty(p, EP_xIsSelect) ){
60566     heightOfSelect(p->x.pSelect, &nHeight);
60567   }else{
60568     heightOfExprList(p->x.pList, &nHeight);
60569   }
60570   p->nHeight = nHeight + 1;
60571 }
60572
60573 /*
60574 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
60575 ** the height is greater than the maximum allowed expression depth,
60576 ** leave an error in pParse.
60577 */
60578 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
60579   exprSetHeight(p);
60580   sqlite3ExprCheckHeight(pParse, p->nHeight);
60581 }
60582
60583 /*
60584 ** Return the maximum height of any expression tree referenced
60585 ** by the select statement passed as an argument.
60586 */
60587 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
60588   int nHeight = 0;
60589   heightOfSelect(p, &nHeight);
60590   return nHeight;
60591 }
60592 #else
60593   #define exprSetHeight(y)
60594 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
60595
60596 /*
60597 ** This routine is the core allocator for Expr nodes.
60598 **
60599 ** Construct a new expression node and return a pointer to it.  Memory
60600 ** for this node and for the pToken argument is a single allocation
60601 ** obtained from sqlite3DbMalloc().  The calling function
60602 ** is responsible for making sure the node eventually gets freed.
60603 **
60604 ** If dequote is true, then the token (if it exists) is dequoted.
60605 ** If dequote is false, no dequoting is performance.  The deQuote
60606 ** parameter is ignored if pToken is NULL or if the token does not
60607 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
60608 ** then the EP_DblQuoted flag is set on the expression node.
60609 **
60610 ** Special case:  If op==TK_INTEGER and pToken points to a string that
60611 ** can be translated into a 32-bit integer, then the token is not
60612 ** stored in u.zToken.  Instead, the integer values is written
60613 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
60614 ** is allocated to hold the integer text and the dequote flag is ignored.
60615 */
60616 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
60617   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
60618   int op,                 /* Expression opcode */
60619   const Token *pToken,    /* Token argument.  Might be NULL */
60620   int dequote             /* True to dequote */
60621 ){
60622   Expr *pNew;
60623   int nExtra = 0;
60624   int iValue = 0;
60625
60626   if( pToken ){
60627     if( op!=TK_INTEGER || pToken->z==0
60628           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
60629       nExtra = pToken->n+1;
60630     }
60631   }
60632   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
60633   if( pNew ){
60634     pNew->op = (u8)op;
60635     pNew->iAgg = -1;
60636     if( pToken ){
60637       if( nExtra==0 ){
60638         pNew->flags |= EP_IntValue;
60639         pNew->u.iValue = iValue;
60640       }else{
60641         int c;
60642         pNew->u.zToken = (char*)&pNew[1];
60643         memcpy(pNew->u.zToken, pToken->z, pToken->n);
60644         pNew->u.zToken[pToken->n] = 0;
60645         if( dequote && nExtra>=3 
60646              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
60647           sqlite3Dequote(pNew->u.zToken);
60648           if( c=='"' ) pNew->flags |= EP_DblQuoted;
60649         }
60650       }
60651     }
60652 #if SQLITE_MAX_EXPR_DEPTH>0
60653     pNew->nHeight = 1;
60654 #endif  
60655   }
60656   return pNew;
60657 }
60658
60659 /*
60660 ** Allocate a new expression node from a zero-terminated token that has
60661 ** already been dequoted.
60662 */
60663 SQLITE_PRIVATE Expr *sqlite3Expr(
60664   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
60665   int op,                 /* Expression opcode */
60666   const char *zToken      /* Token argument.  Might be NULL */
60667 ){
60668   Token x;
60669   x.z = zToken;
60670   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
60671   return sqlite3ExprAlloc(db, op, &x, 0);
60672 }
60673
60674 /*
60675 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
60676 **
60677 ** If pRoot==NULL that means that a memory allocation error has occurred.
60678 ** In that case, delete the subtrees pLeft and pRight.
60679 */
60680 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
60681   sqlite3 *db,
60682   Expr *pRoot,
60683   Expr *pLeft,
60684   Expr *pRight
60685 ){
60686   if( pRoot==0 ){
60687     assert( db->mallocFailed );
60688     sqlite3ExprDelete(db, pLeft);
60689     sqlite3ExprDelete(db, pRight);
60690   }else{
60691     if( pRight ){
60692       pRoot->pRight = pRight;
60693       if( pRight->flags & EP_ExpCollate ){
60694         pRoot->flags |= EP_ExpCollate;
60695         pRoot->pColl = pRight->pColl;
60696       }
60697     }
60698     if( pLeft ){
60699       pRoot->pLeft = pLeft;
60700       if( pLeft->flags & EP_ExpCollate ){
60701         pRoot->flags |= EP_ExpCollate;
60702         pRoot->pColl = pLeft->pColl;
60703       }
60704     }
60705     exprSetHeight(pRoot);
60706   }
60707 }
60708
60709 /*
60710 ** Allocate a Expr node which joins as many as two subtrees.
60711 **
60712 ** One or both of the subtrees can be NULL.  Return a pointer to the new
60713 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
60714 ** free the subtrees and return NULL.
60715 */
60716 SQLITE_PRIVATE Expr *sqlite3PExpr(
60717   Parse *pParse,          /* Parsing context */
60718   int op,                 /* Expression opcode */
60719   Expr *pLeft,            /* Left operand */
60720   Expr *pRight,           /* Right operand */
60721   const Token *pToken     /* Argument token */
60722 ){
60723   Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
60724   sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
60725   return p;
60726 }
60727
60728 /*
60729 ** Join two expressions using an AND operator.  If either expression is
60730 ** NULL, then just return the other expression.
60731 */
60732 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
60733   if( pLeft==0 ){
60734     return pRight;
60735   }else if( pRight==0 ){
60736     return pLeft;
60737   }else{
60738     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
60739     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
60740     return pNew;
60741   }
60742 }
60743
60744 /*
60745 ** Construct a new expression node for a function with multiple
60746 ** arguments.
60747 */
60748 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
60749   Expr *pNew;
60750   sqlite3 *db = pParse->db;
60751   assert( pToken );
60752   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
60753   if( pNew==0 ){
60754     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
60755     return 0;
60756   }
60757   pNew->x.pList = pList;
60758   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
60759   sqlite3ExprSetHeight(pParse, pNew);
60760   return pNew;
60761 }
60762
60763 /*
60764 ** Assign a variable number to an expression that encodes a wildcard
60765 ** in the original SQL statement.  
60766 **
60767 ** Wildcards consisting of a single "?" are assigned the next sequential
60768 ** variable number.
60769 **
60770 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
60771 ** sure "nnn" is not too be to avoid a denial of service attack when
60772 ** the SQL statement comes from an external source.
60773 **
60774 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
60775 ** as the previous instance of the same wildcard.  Or if this is the first
60776 ** instance of the wildcard, the next sequenial variable number is
60777 ** assigned.
60778 */
60779 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
60780   sqlite3 *db = pParse->db;
60781   const char *z;
60782
60783   if( pExpr==0 ) return;
60784   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
60785   z = pExpr->u.zToken;
60786   assert( z!=0 );
60787   assert( z[0]!=0 );
60788   if( z[1]==0 ){
60789     /* Wildcard of the form "?".  Assign the next variable number */
60790     assert( z[0]=='?' );
60791     pExpr->iColumn = (ynVar)(++pParse->nVar);
60792   }else if( z[0]=='?' ){
60793     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
60794     ** use it as the variable number */
60795     int i = atoi((char*)&z[1]);
60796     pExpr->iColumn = (ynVar)i;
60797     testcase( i==0 );
60798     testcase( i==1 );
60799     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
60800     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
60801     if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
60802       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
60803           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
60804     }
60805     if( i>pParse->nVar ){
60806       pParse->nVar = i;
60807     }
60808   }else{
60809     /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
60810     ** number as the prior appearance of the same name, or if the name
60811     ** has never appeared before, reuse the same variable number
60812     */
60813     int i;
60814     u32 n;
60815     n = sqlite3Strlen30(z);
60816     for(i=0; i<pParse->nVarExpr; i++){
60817       Expr *pE = pParse->apVarExpr[i];
60818       assert( pE!=0 );
60819       if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
60820         pExpr->iColumn = pE->iColumn;
60821         break;
60822       }
60823     }
60824     if( i>=pParse->nVarExpr ){
60825       pExpr->iColumn = (ynVar)(++pParse->nVar);
60826       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
60827         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
60828         pParse->apVarExpr =
60829             sqlite3DbReallocOrFree(
60830               db,
60831               pParse->apVarExpr,
60832               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
60833             );
60834       }
60835       if( !db->mallocFailed ){
60836         assert( pParse->apVarExpr!=0 );
60837         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
60838       }
60839     }
60840   } 
60841   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
60842     sqlite3ErrorMsg(pParse, "too many SQL variables");
60843   }
60844 }
60845
60846 /*
60847 ** Recursively delete an expression tree.
60848 */
60849 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
60850   if( p==0 ) return;
60851   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
60852     sqlite3ExprDelete(db, p->pLeft);
60853     sqlite3ExprDelete(db, p->pRight);
60854     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
60855       sqlite3DbFree(db, p->u.zToken);
60856     }
60857     if( ExprHasProperty(p, EP_xIsSelect) ){
60858       sqlite3SelectDelete(db, p->x.pSelect);
60859     }else{
60860       sqlite3ExprListDelete(db, p->x.pList);
60861     }
60862   }
60863   if( !ExprHasProperty(p, EP_Static) ){
60864     sqlite3DbFree(db, p);
60865   }
60866 }
60867
60868 /*
60869 ** Return the number of bytes allocated for the expression structure 
60870 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
60871 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
60872 */
60873 static int exprStructSize(Expr *p){
60874   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
60875   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
60876   return EXPR_FULLSIZE;
60877 }
60878
60879 /*
60880 ** The dupedExpr*Size() routines each return the number of bytes required
60881 ** to store a copy of an expression or expression tree.  They differ in
60882 ** how much of the tree is measured.
60883 **
60884 **     dupedExprStructSize()     Size of only the Expr structure 
60885 **     dupedExprNodeSize()       Size of Expr + space for token
60886 **     dupedExprSize()           Expr + token + subtree components
60887 **
60888 ***************************************************************************
60889 **
60890 ** The dupedExprStructSize() function returns two values OR-ed together:  
60891 ** (1) the space required for a copy of the Expr structure only and 
60892 ** (2) the EP_xxx flags that indicate what the structure size should be.
60893 ** The return values is always one of:
60894 **
60895 **      EXPR_FULLSIZE
60896 **      EXPR_REDUCEDSIZE   | EP_Reduced
60897 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
60898 **
60899 ** The size of the structure can be found by masking the return value
60900 ** of this routine with 0xfff.  The flags can be found by masking the
60901 ** return value with EP_Reduced|EP_TokenOnly.
60902 **
60903 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
60904 ** (unreduced) Expr objects as they or originally constructed by the parser.
60905 ** During expression analysis, extra information is computed and moved into
60906 ** later parts of teh Expr object and that extra information might get chopped
60907 ** off if the expression is reduced.  Note also that it does not work to
60908 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
60909 ** to reduce a pristine expression tree from the parser.  The implementation
60910 ** of dupedExprStructSize() contain multiple assert() statements that attempt
60911 ** to enforce this constraint.
60912 */
60913 static int dupedExprStructSize(Expr *p, int flags){
60914   int nSize;
60915   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
60916   if( 0==(flags&EXPRDUP_REDUCE) ){
60917     nSize = EXPR_FULLSIZE;
60918   }else{
60919     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
60920     assert( !ExprHasProperty(p, EP_FromJoin) ); 
60921     assert( (p->flags2 & EP2_MallocedToken)==0 );
60922     assert( (p->flags2 & EP2_Irreducible)==0 );
60923     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
60924       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
60925     }else{
60926       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
60927     }
60928   }
60929   return nSize;
60930 }
60931
60932 /*
60933 ** This function returns the space in bytes required to store the copy 
60934 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
60935 ** string is defined.)
60936 */
60937 static int dupedExprNodeSize(Expr *p, int flags){
60938   int nByte = dupedExprStructSize(p, flags) & 0xfff;
60939   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
60940     nByte += sqlite3Strlen30(p->u.zToken)+1;
60941   }
60942   return ROUND8(nByte);
60943 }
60944
60945 /*
60946 ** Return the number of bytes required to create a duplicate of the 
60947 ** expression passed as the first argument. The second argument is a
60948 ** mask containing EXPRDUP_XXX flags.
60949 **
60950 ** The value returned includes space to create a copy of the Expr struct
60951 ** itself and the buffer referred to by Expr.u.zToken, if any.
60952 **
60953 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
60954 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
60955 ** and Expr.pRight variables (but not for any structures pointed to or 
60956 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
60957 */
60958 static int dupedExprSize(Expr *p, int flags){
60959   int nByte = 0;
60960   if( p ){
60961     nByte = dupedExprNodeSize(p, flags);
60962     if( flags&EXPRDUP_REDUCE ){
60963       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
60964     }
60965   }
60966   return nByte;
60967 }
60968
60969 /*
60970 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
60971 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
60972 ** to store the copy of expression p, the copies of p->u.zToken
60973 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
60974 ** if any. Before returning, *pzBuffer is set to the first byte passed the
60975 ** portion of the buffer copied into by this function.
60976 */
60977 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
60978   Expr *pNew = 0;                      /* Value to return */
60979   if( p ){
60980     const int isReduced = (flags&EXPRDUP_REDUCE);
60981     u8 *zAlloc;
60982     u32 staticFlag = 0;
60983
60984     assert( pzBuffer==0 || isReduced );
60985
60986     /* Figure out where to write the new Expr structure. */
60987     if( pzBuffer ){
60988       zAlloc = *pzBuffer;
60989       staticFlag = EP_Static;
60990     }else{
60991       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
60992     }
60993     pNew = (Expr *)zAlloc;
60994
60995     if( pNew ){
60996       /* Set nNewSize to the size allocated for the structure pointed to
60997       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
60998       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
60999       ** by the copy of the p->u.zToken string (if any).
61000       */
61001       const unsigned nStructSize = dupedExprStructSize(p, flags);
61002       const int nNewSize = nStructSize & 0xfff;
61003       int nToken;
61004       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
61005         nToken = sqlite3Strlen30(p->u.zToken) + 1;
61006       }else{
61007         nToken = 0;
61008       }
61009       if( isReduced ){
61010         assert( ExprHasProperty(p, EP_Reduced)==0 );
61011         memcpy(zAlloc, p, nNewSize);
61012       }else{
61013         int nSize = exprStructSize(p);
61014         memcpy(zAlloc, p, nSize);
61015         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
61016       }
61017
61018       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
61019       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
61020       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
61021       pNew->flags |= staticFlag;
61022
61023       /* Copy the p->u.zToken string, if any. */
61024       if( nToken ){
61025         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
61026         memcpy(zToken, p->u.zToken, nToken);
61027       }
61028
61029       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
61030         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
61031         if( ExprHasProperty(p, EP_xIsSelect) ){
61032           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
61033         }else{
61034           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
61035         }
61036       }
61037
61038       /* Fill in pNew->pLeft and pNew->pRight. */
61039       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
61040         zAlloc += dupedExprNodeSize(p, flags);
61041         if( ExprHasProperty(pNew, EP_Reduced) ){
61042           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
61043           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
61044         }
61045         if( pzBuffer ){
61046           *pzBuffer = zAlloc;
61047         }
61048       }else{
61049         pNew->flags2 = 0;
61050         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
61051           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
61052           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
61053         }
61054       }
61055
61056     }
61057   }
61058   return pNew;
61059 }
61060
61061 /*
61062 ** The following group of routines make deep copies of expressions,
61063 ** expression lists, ID lists, and select statements.  The copies can
61064 ** be deleted (by being passed to their respective ...Delete() routines)
61065 ** without effecting the originals.
61066 **
61067 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
61068 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
61069 ** by subsequent calls to sqlite*ListAppend() routines.
61070 **
61071 ** Any tables that the SrcList might point to are not duplicated.
61072 **
61073 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
61074 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
61075 ** truncated version of the usual Expr structure that will be stored as
61076 ** part of the in-memory representation of the database schema.
61077 */
61078 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
61079   return exprDup(db, p, flags, 0);
61080 }
61081 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
61082   ExprList *pNew;
61083   struct ExprList_item *pItem, *pOldItem;
61084   int i;
61085   if( p==0 ) return 0;
61086   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
61087   if( pNew==0 ) return 0;
61088   pNew->iECursor = 0;
61089   pNew->nExpr = pNew->nAlloc = p->nExpr;
61090   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
61091   if( pItem==0 ){
61092     sqlite3DbFree(db, pNew);
61093     return 0;
61094   } 
61095   pOldItem = p->a;
61096   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
61097     Expr *pOldExpr = pOldItem->pExpr;
61098     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
61099     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
61100     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
61101     pItem->sortOrder = pOldItem->sortOrder;
61102     pItem->done = 0;
61103     pItem->iCol = pOldItem->iCol;
61104     pItem->iAlias = pOldItem->iAlias;
61105   }
61106   return pNew;
61107 }
61108
61109 /*
61110 ** If cursors, triggers, views and subqueries are all omitted from
61111 ** the build, then none of the following routines, except for 
61112 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
61113 ** called with a NULL argument.
61114 */
61115 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
61116  || !defined(SQLITE_OMIT_SUBQUERY)
61117 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
61118   SrcList *pNew;
61119   int i;
61120   int nByte;
61121   if( p==0 ) return 0;
61122   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
61123   pNew = sqlite3DbMallocRaw(db, nByte );
61124   if( pNew==0 ) return 0;
61125   pNew->nSrc = pNew->nAlloc = p->nSrc;
61126   for(i=0; i<p->nSrc; i++){
61127     struct SrcList_item *pNewItem = &pNew->a[i];
61128     struct SrcList_item *pOldItem = &p->a[i];
61129     Table *pTab;
61130     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
61131     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
61132     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
61133     pNewItem->jointype = pOldItem->jointype;
61134     pNewItem->iCursor = pOldItem->iCursor;
61135     pNewItem->isPopulated = pOldItem->isPopulated;
61136     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
61137     pNewItem->notIndexed = pOldItem->notIndexed;
61138     pNewItem->pIndex = pOldItem->pIndex;
61139     pTab = pNewItem->pTab = pOldItem->pTab;
61140     if( pTab ){
61141       pTab->nRef++;
61142     }
61143     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
61144     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
61145     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
61146     pNewItem->colUsed = pOldItem->colUsed;
61147   }
61148   return pNew;
61149 }
61150 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
61151   IdList *pNew;
61152   int i;
61153   if( p==0 ) return 0;
61154   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
61155   if( pNew==0 ) return 0;
61156   pNew->nId = pNew->nAlloc = p->nId;
61157   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
61158   if( pNew->a==0 ){
61159     sqlite3DbFree(db, pNew);
61160     return 0;
61161   }
61162   for(i=0; i<p->nId; i++){
61163     struct IdList_item *pNewItem = &pNew->a[i];
61164     struct IdList_item *pOldItem = &p->a[i];
61165     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
61166     pNewItem->idx = pOldItem->idx;
61167   }
61168   return pNew;
61169 }
61170 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
61171   Select *pNew;
61172   if( p==0 ) return 0;
61173   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
61174   if( pNew==0 ) return 0;
61175   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
61176   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
61177   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
61178   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
61179   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
61180   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
61181   pNew->op = p->op;
61182   pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
61183   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
61184   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
61185   pNew->iLimit = 0;
61186   pNew->iOffset = 0;
61187   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
61188   pNew->pRightmost = 0;
61189   pNew->addrOpenEphm[0] = -1;
61190   pNew->addrOpenEphm[1] = -1;
61191   pNew->addrOpenEphm[2] = -1;
61192   return pNew;
61193 }
61194 #else
61195 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
61196   assert( p==0 );
61197   return 0;
61198 }
61199 #endif
61200
61201
61202 /*
61203 ** Add a new element to the end of an expression list.  If pList is
61204 ** initially NULL, then create a new expression list.
61205 **
61206 ** If a memory allocation error occurs, the entire list is freed and
61207 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
61208 ** that the new entry was successfully appended.
61209 */
61210 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
61211   Parse *pParse,          /* Parsing context */
61212   ExprList *pList,        /* List to which to append. Might be NULL */
61213   Expr *pExpr             /* Expression to be appended. Might be NULL */
61214 ){
61215   sqlite3 *db = pParse->db;
61216   if( pList==0 ){
61217     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
61218     if( pList==0 ){
61219       goto no_mem;
61220     }
61221     assert( pList->nAlloc==0 );
61222   }
61223   if( pList->nAlloc<=pList->nExpr ){
61224     struct ExprList_item *a;
61225     int n = pList->nAlloc*2 + 4;
61226     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
61227     if( a==0 ){
61228       goto no_mem;
61229     }
61230     pList->a = a;
61231     pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
61232   }
61233   assert( pList->a!=0 );
61234   if( 1 ){
61235     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
61236     memset(pItem, 0, sizeof(*pItem));
61237     pItem->pExpr = pExpr;
61238   }
61239   return pList;
61240
61241 no_mem:     
61242   /* Avoid leaking memory if malloc has failed. */
61243   sqlite3ExprDelete(db, pExpr);
61244   sqlite3ExprListDelete(db, pList);
61245   return 0;
61246 }
61247
61248 /*
61249 ** Set the ExprList.a[].zName element of the most recently added item
61250 ** on the expression list.
61251 **
61252 ** pList might be NULL following an OOM error.  But pName should never be
61253 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
61254 ** is set.
61255 */
61256 SQLITE_PRIVATE void sqlite3ExprListSetName(
61257   Parse *pParse,          /* Parsing context */
61258   ExprList *pList,        /* List to which to add the span. */
61259   Token *pName,           /* Name to be added */
61260   int dequote             /* True to cause the name to be dequoted */
61261 ){
61262   assert( pList!=0 || pParse->db->mallocFailed!=0 );
61263   if( pList ){
61264     struct ExprList_item *pItem;
61265     assert( pList->nExpr>0 );
61266     pItem = &pList->a[pList->nExpr-1];
61267     assert( pItem->zName==0 );
61268     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
61269     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
61270   }
61271 }
61272
61273 /*
61274 ** Set the ExprList.a[].zSpan element of the most recently added item
61275 ** on the expression list.
61276 **
61277 ** pList might be NULL following an OOM error.  But pSpan should never be
61278 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
61279 ** is set.
61280 */
61281 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
61282   Parse *pParse,          /* Parsing context */
61283   ExprList *pList,        /* List to which to add the span. */
61284   ExprSpan *pSpan         /* The span to be added */
61285 ){
61286   sqlite3 *db = pParse->db;
61287   assert( pList!=0 || db->mallocFailed!=0 );
61288   if( pList ){
61289     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
61290     assert( pList->nExpr>0 );
61291     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
61292     sqlite3DbFree(db, pItem->zSpan);
61293     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
61294                                     (int)(pSpan->zEnd - pSpan->zStart));
61295   }
61296 }
61297
61298 /*
61299 ** If the expression list pEList contains more than iLimit elements,
61300 ** leave an error message in pParse.
61301 */
61302 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
61303   Parse *pParse,
61304   ExprList *pEList,
61305   const char *zObject
61306 ){
61307   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
61308   testcase( pEList && pEList->nExpr==mx );
61309   testcase( pEList && pEList->nExpr==mx+1 );
61310   if( pEList && pEList->nExpr>mx ){
61311     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
61312   }
61313 }
61314
61315 /*
61316 ** Delete an entire expression list.
61317 */
61318 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
61319   int i;
61320   struct ExprList_item *pItem;
61321   if( pList==0 ) return;
61322   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
61323   assert( pList->nExpr<=pList->nAlloc );
61324   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
61325     sqlite3ExprDelete(db, pItem->pExpr);
61326     sqlite3DbFree(db, pItem->zName);
61327     sqlite3DbFree(db, pItem->zSpan);
61328   }
61329   sqlite3DbFree(db, pList->a);
61330   sqlite3DbFree(db, pList);
61331 }
61332
61333 /*
61334 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
61335 ** to an integer.  These routines are checking an expression to see
61336 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
61337 ** not constant.
61338 **
61339 ** These callback routines are used to implement the following:
61340 **
61341 **     sqlite3ExprIsConstant()
61342 **     sqlite3ExprIsConstantNotJoin()
61343 **     sqlite3ExprIsConstantOrFunction()
61344 **
61345 */
61346 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
61347
61348   /* If pWalker->u.i is 3 then any term of the expression that comes from
61349   ** the ON or USING clauses of a join disqualifies the expression
61350   ** from being considered constant. */
61351   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
61352     pWalker->u.i = 0;
61353     return WRC_Abort;
61354   }
61355
61356   switch( pExpr->op ){
61357     /* Consider functions to be constant if all their arguments are constant
61358     ** and pWalker->u.i==2 */
61359     case TK_FUNCTION:
61360       if( pWalker->u.i==2 ) return 0;
61361       /* Fall through */
61362     case TK_ID:
61363     case TK_COLUMN:
61364     case TK_AGG_FUNCTION:
61365     case TK_AGG_COLUMN:
61366       testcase( pExpr->op==TK_ID );
61367       testcase( pExpr->op==TK_COLUMN );
61368       testcase( pExpr->op==TK_AGG_FUNCTION );
61369       testcase( pExpr->op==TK_AGG_COLUMN );
61370       pWalker->u.i = 0;
61371       return WRC_Abort;
61372     default:
61373       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
61374       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
61375       return WRC_Continue;
61376   }
61377 }
61378 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
61379   UNUSED_PARAMETER(NotUsed);
61380   pWalker->u.i = 0;
61381   return WRC_Abort;
61382 }
61383 static int exprIsConst(Expr *p, int initFlag){
61384   Walker w;
61385   w.u.i = initFlag;
61386   w.xExprCallback = exprNodeIsConstant;
61387   w.xSelectCallback = selectNodeIsConstant;
61388   sqlite3WalkExpr(&w, p);
61389   return w.u.i;
61390 }
61391
61392 /*
61393 ** Walk an expression tree.  Return 1 if the expression is constant
61394 ** and 0 if it involves variables or function calls.
61395 **
61396 ** For the purposes of this function, a double-quoted string (ex: "abc")
61397 ** is considered a variable but a single-quoted string (ex: 'abc') is
61398 ** a constant.
61399 */
61400 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
61401   return exprIsConst(p, 1);
61402 }
61403
61404 /*
61405 ** Walk an expression tree.  Return 1 if the expression is constant
61406 ** that does no originate from the ON or USING clauses of a join.
61407 ** Return 0 if it involves variables or function calls or terms from
61408 ** an ON or USING clause.
61409 */
61410 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
61411   return exprIsConst(p, 3);
61412 }
61413
61414 /*
61415 ** Walk an expression tree.  Return 1 if the expression is constant
61416 ** or a function call with constant arguments.  Return and 0 if there
61417 ** are any variables.
61418 **
61419 ** For the purposes of this function, a double-quoted string (ex: "abc")
61420 ** is considered a variable but a single-quoted string (ex: 'abc') is
61421 ** a constant.
61422 */
61423 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
61424   return exprIsConst(p, 2);
61425 }
61426
61427 /*
61428 ** If the expression p codes a constant integer that is small enough
61429 ** to fit in a 32-bit integer, return 1 and put the value of the integer
61430 ** in *pValue.  If the expression is not an integer or if it is too big
61431 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
61432 */
61433 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
61434   int rc = 0;
61435   if( p->flags & EP_IntValue ){
61436     *pValue = p->u.iValue;
61437     return 1;
61438   }
61439   switch( p->op ){
61440     case TK_INTEGER: {
61441       rc = sqlite3GetInt32(p->u.zToken, pValue);
61442       assert( rc==0 );
61443       break;
61444     }
61445     case TK_UPLUS: {
61446       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
61447       break;
61448     }
61449     case TK_UMINUS: {
61450       int v;
61451       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
61452         *pValue = -v;
61453         rc = 1;
61454       }
61455       break;
61456     }
61457     default: break;
61458   }
61459   if( rc ){
61460     assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
61461                || (p->flags2 & EP2_MallocedToken)==0 );
61462     p->op = TK_INTEGER;
61463     p->flags |= EP_IntValue;
61464     p->u.iValue = *pValue;
61465   }
61466   return rc;
61467 }
61468
61469 /*
61470 ** Return FALSE if there is no chance that the expression can be NULL.
61471 **
61472 ** If the expression might be NULL or if the expression is too complex
61473 ** to tell return TRUE.  
61474 **
61475 ** This routine is used as an optimization, to skip OP_IsNull opcodes
61476 ** when we know that a value cannot be NULL.  Hence, a false positive
61477 ** (returning TRUE when in fact the expression can never be NULL) might
61478 ** be a small performance hit but is otherwise harmless.  On the other
61479 ** hand, a false negative (returning FALSE when the result could be NULL)
61480 ** will likely result in an incorrect answer.  So when in doubt, return
61481 ** TRUE.
61482 */
61483 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
61484   u8 op;
61485   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
61486   op = p->op;
61487   if( op==TK_REGISTER ) op = p->op2;
61488   switch( op ){
61489     case TK_INTEGER:
61490     case TK_STRING:
61491     case TK_FLOAT:
61492     case TK_BLOB:
61493       return 0;
61494     default:
61495       return 1;
61496   }
61497 }
61498
61499 /*
61500 ** Generate an OP_IsNull instruction that tests register iReg and jumps
61501 ** to location iDest if the value in iReg is NULL.  The value in iReg 
61502 ** was computed by pExpr.  If we can look at pExpr at compile-time and
61503 ** determine that it can never generate a NULL, then the OP_IsNull operation
61504 ** can be omitted.
61505 */
61506 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
61507   Vdbe *v,            /* The VDBE under construction */
61508   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
61509   int iReg,           /* Test the value in this register for NULL */
61510   int iDest           /* Jump here if the value is null */
61511 ){
61512   if( sqlite3ExprCanBeNull(pExpr) ){
61513     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
61514   }
61515 }
61516
61517 /*
61518 ** Return TRUE if the given expression is a constant which would be
61519 ** unchanged by OP_Affinity with the affinity given in the second
61520 ** argument.
61521 **
61522 ** This routine is used to determine if the OP_Affinity operation
61523 ** can be omitted.  When in doubt return FALSE.  A false negative
61524 ** is harmless.  A false positive, however, can result in the wrong
61525 ** answer.
61526 */
61527 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
61528   u8 op;
61529   if( aff==SQLITE_AFF_NONE ) return 1;
61530   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
61531   op = p->op;
61532   if( op==TK_REGISTER ) op = p->op2;
61533   switch( op ){
61534     case TK_INTEGER: {
61535       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
61536     }
61537     case TK_FLOAT: {
61538       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
61539     }
61540     case TK_STRING: {
61541       return aff==SQLITE_AFF_TEXT;
61542     }
61543     case TK_BLOB: {
61544       return 1;
61545     }
61546     case TK_COLUMN: {
61547       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
61548       return p->iColumn<0
61549           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
61550     }
61551     default: {
61552       return 0;
61553     }
61554   }
61555 }
61556
61557 /*
61558 ** Return TRUE if the given string is a row-id column name.
61559 */
61560 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
61561   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
61562   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
61563   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
61564   return 0;
61565 }
61566
61567 /*
61568 ** Return true if we are able to the IN operator optimization on a
61569 ** query of the form
61570 **
61571 **       x IN (SELECT ...)
61572 **
61573 ** Where the SELECT... clause is as specified by the parameter to this
61574 ** routine.
61575 **
61576 ** The Select object passed in has already been preprocessed and no
61577 ** errors have been found.
61578 */
61579 #ifndef SQLITE_OMIT_SUBQUERY
61580 static int isCandidateForInOpt(Select *p){
61581   SrcList *pSrc;
61582   ExprList *pEList;
61583   Table *pTab;
61584   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
61585   if( p->pPrior ) return 0;              /* Not a compound SELECT */
61586   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
61587     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
61588     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
61589     return 0; /* No DISTINCT keyword and no aggregate functions */
61590   }
61591   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
61592   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
61593   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
61594   if( p->pWhere ) return 0;              /* Has no WHERE clause */
61595   pSrc = p->pSrc;
61596   assert( pSrc!=0 );
61597   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
61598   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
61599   pTab = pSrc->a[0].pTab;
61600   if( NEVER(pTab==0) ) return 0;
61601   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
61602   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
61603   pEList = p->pEList;
61604   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
61605   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
61606   return 1;
61607 }
61608 #endif /* SQLITE_OMIT_SUBQUERY */
61609
61610 /*
61611 ** This function is used by the implementation of the IN (...) operator.
61612 ** It's job is to find or create a b-tree structure that may be used
61613 ** either to test for membership of the (...) set or to iterate through
61614 ** its members, skipping duplicates.
61615 **
61616 ** The index of the cursor opened on the b-tree (database table, database index 
61617 ** or ephermal table) is stored in pX->iTable before this function returns.
61618 ** The returned value of this function indicates the b-tree type, as follows:
61619 **
61620 **   IN_INDEX_ROWID - The cursor was opened on a database table.
61621 **   IN_INDEX_INDEX - The cursor was opened on a database index.
61622 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
61623 **                    populated epheremal table.
61624 **
61625 ** An existing b-tree may only be used if the SELECT is of the simple
61626 ** form:
61627 **
61628 **     SELECT <column> FROM <table>
61629 **
61630 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
61631 ** through the set members, skipping any duplicates. In this case an
61632 ** epheremal table must be used unless the selected <column> is guaranteed
61633 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
61634 ** has a UNIQUE constraint or UNIQUE index.
61635 **
61636 ** If the prNotFound parameter is not 0, then the b-tree will be used 
61637 ** for fast set membership tests. In this case an epheremal table must 
61638 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
61639 ** be found with <column> as its left-most column.
61640 **
61641 ** When the b-tree is being used for membership tests, the calling function
61642 ** needs to know whether or not the structure contains an SQL NULL 
61643 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
61644 ** If there is any chance that the (...) might contain a NULL value at
61645 ** runtime, then a register is allocated and the register number written
61646 ** to *prNotFound. If there is no chance that the (...) contains a
61647 ** NULL value, then *prNotFound is left unchanged.
61648 **
61649 ** If a register is allocated and its location stored in *prNotFound, then
61650 ** its initial value is NULL.  If the (...) does not remain constant
61651 ** for the duration of the query (i.e. the SELECT within the (...)
61652 ** is a correlated subquery) then the value of the allocated register is
61653 ** reset to NULL each time the subquery is rerun. This allows the
61654 ** caller to use vdbe code equivalent to the following:
61655 **
61656 **   if( register==NULL ){
61657 **     has_null = <test if data structure contains null>
61658 **     register = 1
61659 **   }
61660 **
61661 ** in order to avoid running the <test if data structure contains null>
61662 ** test more often than is necessary.
61663 */
61664 #ifndef SQLITE_OMIT_SUBQUERY
61665 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
61666   Select *p;                            /* SELECT to the right of IN operator */
61667   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
61668   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
61669   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
61670
61671   assert( pX->op==TK_IN );
61672
61673   /* Check to see if an existing table or index can be used to
61674   ** satisfy the query.  This is preferable to generating a new 
61675   ** ephemeral table.
61676   */
61677   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
61678   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
61679     sqlite3 *db = pParse->db;              /* Database connection */
61680     Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
61681     int iCol = pExpr->iColumn;             /* Index of column <column> */
61682     Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
61683     Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
61684     int iDb;                               /* Database idx for pTab */
61685    
61686     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
61687     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
61688     sqlite3CodeVerifySchema(pParse, iDb);
61689     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
61690
61691     /* This function is only called from two places. In both cases the vdbe
61692     ** has already been allocated. So assume sqlite3GetVdbe() is always
61693     ** successful here.
61694     */
61695     assert(v);
61696     if( iCol<0 ){
61697       int iMem = ++pParse->nMem;
61698       int iAddr;
61699
61700       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
61701       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
61702
61703       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
61704       eType = IN_INDEX_ROWID;
61705
61706       sqlite3VdbeJumpHere(v, iAddr);
61707     }else{
61708       Index *pIdx;                         /* Iterator variable */
61709
61710       /* The collation sequence used by the comparison. If an index is to
61711       ** be used in place of a temp-table, it must be ordered according
61712       ** to this collation sequence.  */
61713       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
61714
61715       /* Check that the affinity that will be used to perform the 
61716       ** comparison is the same as the affinity of the column. If
61717       ** it is not, it is not possible to use any index.
61718       */
61719       char aff = comparisonAffinity(pX);
61720       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
61721
61722       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
61723         if( (pIdx->aiColumn[0]==iCol)
61724          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
61725          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
61726         ){
61727           int iMem = ++pParse->nMem;
61728           int iAddr;
61729           char *pKey;
61730   
61731           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
61732           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
61733           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
61734   
61735           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
61736                                pKey,P4_KEYINFO_HANDOFF);
61737           VdbeComment((v, "%s", pIdx->zName));
61738           eType = IN_INDEX_INDEX;
61739
61740           sqlite3VdbeJumpHere(v, iAddr);
61741           if( prNotFound && !pTab->aCol[iCol].notNull ){
61742             *prNotFound = ++pParse->nMem;
61743           }
61744         }
61745       }
61746     }
61747   }
61748
61749   if( eType==0 ){
61750     /* Could not found an existing table or index to use as the RHS b-tree.
61751     ** We will have to generate an ephemeral table to do the job.
61752     */
61753     int rMayHaveNull = 0;
61754     eType = IN_INDEX_EPH;
61755     if( prNotFound ){
61756       *prNotFound = rMayHaveNull = ++pParse->nMem;
61757     }else if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
61758       eType = IN_INDEX_ROWID;
61759     }
61760     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
61761   }else{
61762     pX->iTable = iTab;
61763   }
61764   return eType;
61765 }
61766 #endif
61767
61768 /*
61769 ** Generate code for scalar subqueries used as an expression
61770 ** and IN operators.  Examples:
61771 **
61772 **     (SELECT a FROM b)          -- subquery
61773 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
61774 **     x IN (4,5,11)              -- IN operator with list on right-hand side
61775 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
61776 **
61777 ** The pExpr parameter describes the expression that contains the IN
61778 ** operator or subquery.
61779 **
61780 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
61781 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
61782 ** to some integer key column of a table B-Tree. In this case, use an
61783 ** intkey B-Tree to store the set of IN(...) values instead of the usual
61784 ** (slower) variable length keys B-Tree.
61785 **
61786 ** If rMayHaveNull is non-zero, that means that the operation is an IN
61787 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
61788 ** Furthermore, the IN is in a WHERE clause and that we really want
61789 ** to iterate over the RHS of the IN operator in order to quickly locate
61790 ** all corresponding LHS elements.  All this routine does is initialize
61791 ** the register given by rMayHaveNull to NULL.  Calling routines will take
61792 ** care of changing this register value to non-NULL if the RHS is NULL-free.
61793 **
61794 ** If rMayHaveNull is zero, that means that the subquery is being used
61795 ** for membership testing only.  There is no need to initialize any
61796 ** registers to indicate the presense or absence of NULLs on the RHS.
61797 **
61798 ** For a SELECT or EXISTS operator, return the register that holds the
61799 ** result.  For IN operators or if an error occurs, the return value is 0.
61800 */
61801 #ifndef SQLITE_OMIT_SUBQUERY
61802 SQLITE_PRIVATE int sqlite3CodeSubselect(
61803   Parse *pParse,          /* Parsing context */
61804   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
61805   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
61806   int isRowid             /* If true, LHS of IN operator is a rowid */
61807 ){
61808   int testAddr = 0;                       /* One-time test address */
61809   int rReg = 0;                           /* Register storing resulting */
61810   Vdbe *v = sqlite3GetVdbe(pParse);
61811   if( NEVER(v==0) ) return 0;
61812   sqlite3ExprCachePush(pParse);
61813
61814   /* This code must be run in its entirety every time it is encountered
61815   ** if any of the following is true:
61816   **
61817   **    *  The right-hand side is a correlated subquery
61818   **    *  The right-hand side is an expression list containing variables
61819   **    *  We are inside a trigger
61820   **
61821   ** If all of the above are false, then we can run this code just once
61822   ** save the results, and reuse the same result on subsequent invocations.
61823   */
61824   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
61825     int mem = ++pParse->nMem;
61826     sqlite3VdbeAddOp1(v, OP_If, mem);
61827     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
61828     assert( testAddr>0 || pParse->db->mallocFailed );
61829   }
61830
61831   switch( pExpr->op ){
61832     case TK_IN: {
61833       char affinity;
61834       KeyInfo keyInfo;
61835       int addr;        /* Address of OP_OpenEphemeral instruction */
61836       Expr *pLeft = pExpr->pLeft;
61837
61838       if( rMayHaveNull ){
61839         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
61840       }
61841
61842       affinity = sqlite3ExprAffinity(pLeft);
61843
61844       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
61845       ** expression it is handled the same way.  An ephemeral table is 
61846       ** filled with single-field index keys representing the results
61847       ** from the SELECT or the <exprlist>.
61848       **
61849       ** If the 'x' expression is a column value, or the SELECT...
61850       ** statement returns a column value, then the affinity of that
61851       ** column is used to build the index keys. If both 'x' and the
61852       ** SELECT... statement are columns, then numeric affinity is used
61853       ** if either column has NUMERIC or INTEGER affinity. If neither
61854       ** 'x' nor the SELECT... statement are columns, then numeric affinity
61855       ** is used.
61856       */
61857       pExpr->iTable = pParse->nTab++;
61858       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
61859       memset(&keyInfo, 0, sizeof(keyInfo));
61860       keyInfo.nField = 1;
61861
61862       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
61863         /* Case 1:     expr IN (SELECT ...)
61864         **
61865         ** Generate code to write the results of the select into the temporary
61866         ** table allocated and opened above.
61867         */
61868         SelectDest dest;
61869         ExprList *pEList;
61870
61871         assert( !isRowid );
61872         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
61873         dest.affinity = (u8)affinity;
61874         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
61875         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
61876           return 0;
61877         }
61878         pEList = pExpr->x.pSelect->pEList;
61879         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
61880           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
61881               pEList->a[0].pExpr);
61882         }
61883       }else if( pExpr->x.pList!=0 ){
61884         /* Case 2:     expr IN (exprlist)
61885         **
61886         ** For each expression, build an index key from the evaluation and
61887         ** store it in the temporary table. If <expr> is a column, then use
61888         ** that columns affinity when building index keys. If <expr> is not
61889         ** a column, use numeric affinity.
61890         */
61891         int i;
61892         ExprList *pList = pExpr->x.pList;
61893         struct ExprList_item *pItem;
61894         int r1, r2, r3;
61895
61896         if( !affinity ){
61897           affinity = SQLITE_AFF_NONE;
61898         }
61899         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
61900
61901         /* Loop through each expression in <exprlist>. */
61902         r1 = sqlite3GetTempReg(pParse);
61903         r2 = sqlite3GetTempReg(pParse);
61904         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
61905         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
61906           Expr *pE2 = pItem->pExpr;
61907           int iValToIns;
61908
61909           /* If the expression is not constant then we will need to
61910           ** disable the test that was generated above that makes sure
61911           ** this code only executes once.  Because for a non-constant
61912           ** expression we need to rerun this code each time.
61913           */
61914           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
61915             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
61916             testAddr = 0;
61917           }
61918
61919           /* Evaluate the expression and insert it into the temp table */
61920           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
61921             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
61922           }else{
61923             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
61924             if( isRowid ){
61925               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
61926                                 sqlite3VdbeCurrentAddr(v)+2);
61927               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
61928             }else{
61929               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
61930               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
61931               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
61932             }
61933           }
61934         }
61935         sqlite3ReleaseTempReg(pParse, r1);
61936         sqlite3ReleaseTempReg(pParse, r2);
61937       }
61938       if( !isRowid ){
61939         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
61940       }
61941       break;
61942     }
61943
61944     case TK_EXISTS:
61945     case TK_SELECT:
61946     default: {
61947       /* If this has to be a scalar SELECT.  Generate code to put the
61948       ** value of this select in a memory cell and record the number
61949       ** of the memory cell in iColumn.  If this is an EXISTS, write
61950       ** an integer 0 (not exists) or 1 (exists) into a memory cell
61951       ** and record that memory cell in iColumn.
61952       */
61953       static const Token one = { "1", 1 };  /* Token for literal value 1 */
61954       Select *pSel;                         /* SELECT statement to encode */
61955       SelectDest dest;                      /* How to deal with SELECt result */
61956
61957       testcase( pExpr->op==TK_EXISTS );
61958       testcase( pExpr->op==TK_SELECT );
61959       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
61960
61961       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
61962       pSel = pExpr->x.pSelect;
61963       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
61964       if( pExpr->op==TK_SELECT ){
61965         dest.eDest = SRT_Mem;
61966         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
61967         VdbeComment((v, "Init subquery result"));
61968       }else{
61969         dest.eDest = SRT_Exists;
61970         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
61971         VdbeComment((v, "Init EXISTS result"));
61972       }
61973       sqlite3ExprDelete(pParse->db, pSel->pLimit);
61974       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
61975       if( sqlite3Select(pParse, pSel, &dest) ){
61976         return 0;
61977       }
61978       rReg = dest.iParm;
61979       ExprSetIrreducible(pExpr);
61980       break;
61981     }
61982   }
61983
61984   if( testAddr ){
61985     sqlite3VdbeJumpHere(v, testAddr-1);
61986   }
61987   sqlite3ExprCachePop(pParse, 1);
61988
61989   return rReg;
61990 }
61991 #endif /* SQLITE_OMIT_SUBQUERY */
61992
61993 #ifndef SQLITE_OMIT_SUBQUERY
61994 /*
61995 ** Generate code for an IN expression.
61996 **
61997 **      x IN (SELECT ...)
61998 **      x IN (value, value, ...)
61999 **
62000 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
62001 ** is an array of zero or more values.  The expression is true if the LHS is
62002 ** contained within the RHS.  The value of the expression is unknown (NULL)
62003 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
62004 ** RHS contains one or more NULL values.
62005 **
62006 ** This routine generates code will jump to destIfFalse if the LHS is not 
62007 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
62008 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
62009 ** within the RHS then fall through.
62010 */
62011 static void sqlite3ExprCodeIN(
62012   Parse *pParse,        /* Parsing and code generating context */
62013   Expr *pExpr,          /* The IN expression */
62014   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
62015   int destIfNull        /* Jump here if the results are unknown due to NULLs */
62016 ){
62017   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
62018   char affinity;        /* Comparison affinity to use */
62019   int eType;            /* Type of the RHS */
62020   int r1;               /* Temporary use register */
62021   Vdbe *v;              /* Statement under construction */
62022
62023   /* Compute the RHS.   After this step, the table with cursor
62024   ** pExpr->iTable will contains the values that make up the RHS.
62025   */
62026   v = pParse->pVdbe;
62027   assert( v!=0 );       /* OOM detected prior to this routine */
62028   VdbeNoopComment((v, "begin IN expr"));
62029   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
62030
62031   /* Figure out the affinity to use to create a key from the results
62032   ** of the expression. affinityStr stores a static string suitable for
62033   ** P4 of OP_MakeRecord.
62034   */
62035   affinity = comparisonAffinity(pExpr);
62036
62037   /* Code the LHS, the <expr> from "<expr> IN (...)".
62038   */
62039   sqlite3ExprCachePush(pParse);
62040   r1 = sqlite3GetTempReg(pParse);
62041   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
62042   sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
62043
62044
62045   if( eType==IN_INDEX_ROWID ){
62046     /* In this case, the RHS is the ROWID of table b-tree
62047     */
62048     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
62049     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
62050   }else{
62051     /* In this case, the RHS is an index b-tree.
62052     */
62053     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
62054
62055     /* If the set membership test fails, then the result of the 
62056     ** "x IN (...)" expression must be either 0 or NULL. If the set
62057     ** contains no NULL values, then the result is 0. If the set 
62058     ** contains one or more NULL values, then the result of the
62059     ** expression is also NULL.
62060     */
62061     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
62062       /* This branch runs if it is known at compile time that the RHS
62063       ** cannot contain NULL values. This happens as the result
62064       ** of a "NOT NULL" constraint in the database schema.
62065       **
62066       ** Also run this branch if NULL is equivalent to FALSE
62067       ** for this particular IN operator.
62068       */
62069       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
62070
62071     }else{
62072       /* In this branch, the RHS of the IN might contain a NULL and
62073       ** the presence of a NULL on the RHS makes a difference in the
62074       ** outcome.
62075       */
62076       int j1, j2, j3;
62077
62078       /* First check to see if the LHS is contained in the RHS.  If so,
62079       ** then the presence of NULLs in the RHS does not matter, so jump
62080       ** over all of the code that follows.
62081       */
62082       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
62083
62084       /* Here we begin generating code that runs if the LHS is not
62085       ** contained within the RHS.  Generate additional code that
62086       ** tests the RHS for NULLs.  If the RHS contains a NULL then
62087       ** jump to destIfNull.  If there are no NULLs in the RHS then
62088       ** jump to destIfFalse.
62089       */
62090       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
62091       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
62092       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
62093       sqlite3VdbeJumpHere(v, j3);
62094       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
62095       sqlite3VdbeJumpHere(v, j2);
62096
62097       /* Jump to the appropriate target depending on whether or not
62098       ** the RHS contains a NULL
62099       */
62100       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
62101       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
62102
62103       /* The OP_Found at the top of this branch jumps here when true, 
62104       ** causing the overall IN expression evaluation to fall through.
62105       */
62106       sqlite3VdbeJumpHere(v, j1);
62107     }
62108   }
62109   sqlite3ReleaseTempReg(pParse, r1);
62110   sqlite3ExprCachePop(pParse, 1);
62111   VdbeComment((v, "end IN expr"));
62112 }
62113 #endif /* SQLITE_OMIT_SUBQUERY */
62114
62115 /*
62116 ** Duplicate an 8-byte value
62117 */
62118 static char *dup8bytes(Vdbe *v, const char *in){
62119   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
62120   if( out ){
62121     memcpy(out, in, 8);
62122   }
62123   return out;
62124 }
62125
62126 /*
62127 ** Generate an instruction that will put the floating point
62128 ** value described by z[0..n-1] into register iMem.
62129 **
62130 ** The z[] string will probably not be zero-terminated.  But the 
62131 ** z[n] character is guaranteed to be something that does not look
62132 ** like the continuation of the number.
62133 */
62134 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
62135   if( ALWAYS(z!=0) ){
62136     double value;
62137     char *zV;
62138     sqlite3AtoF(z, &value);
62139     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
62140     if( negateFlag ) value = -value;
62141     zV = dup8bytes(v, (char*)&value);
62142     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
62143   }
62144 }
62145
62146
62147 /*
62148 ** Generate an instruction that will put the integer describe by
62149 ** text z[0..n-1] into register iMem.
62150 **
62151 ** The z[] string will probably not be zero-terminated.  But the 
62152 ** z[n] character is guaranteed to be something that does not look
62153 ** like the continuation of the number.
62154 */
62155 static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
62156   if( pExpr->flags & EP_IntValue ){
62157     int i = pExpr->u.iValue;
62158     if( negFlag ) i = -i;
62159     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
62160   }else{
62161     const char *z = pExpr->u.zToken;
62162     assert( z!=0 );
62163     if( sqlite3FitsIn64Bits(z, negFlag) ){
62164       i64 value;
62165       char *zV;
62166       sqlite3Atoi64(z, &value);
62167       if( negFlag ) value = -value;
62168       zV = dup8bytes(v, (char*)&value);
62169       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
62170     }else{
62171       codeReal(v, z, negFlag, iMem);
62172     }
62173   }
62174 }
62175
62176 /*
62177 ** Clear a cache entry.
62178 */
62179 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
62180   if( p->tempReg ){
62181     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
62182       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
62183     }
62184     p->tempReg = 0;
62185   }
62186 }
62187
62188
62189 /*
62190 ** Record in the column cache that a particular column from a
62191 ** particular table is stored in a particular register.
62192 */
62193 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
62194   int i;
62195   int minLru;
62196   int idxLru;
62197   struct yColCache *p;
62198
62199   assert( iReg>0 );  /* Register numbers are always positive */
62200   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
62201
62202   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
62203   ** for testing only - to verify that SQLite always gets the same answer
62204   ** with and without the column cache.
62205   */
62206   if( pParse->db->flags & SQLITE_ColumnCache ) return;
62207
62208   /* First replace any existing entry.
62209   **
62210   ** Actually, the way the column cache is currently used, we are guaranteed
62211   ** that the object will never already be in cache.  Verify this guarantee.
62212   */
62213 #ifndef NDEBUG
62214   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62215 #if 0 /* This code wold remove the entry from the cache if it existed */
62216     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
62217       cacheEntryClear(pParse, p);
62218       p->iLevel = pParse->iCacheLevel;
62219       p->iReg = iReg;
62220       p->lru = pParse->iCacheCnt++;
62221       return;
62222     }
62223 #endif
62224     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
62225   }
62226 #endif
62227
62228   /* Find an empty slot and replace it */
62229   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62230     if( p->iReg==0 ){
62231       p->iLevel = pParse->iCacheLevel;
62232       p->iTable = iTab;
62233       p->iColumn = iCol;
62234       p->iReg = iReg;
62235       p->tempReg = 0;
62236       p->lru = pParse->iCacheCnt++;
62237       return;
62238     }
62239   }
62240
62241   /* Replace the last recently used */
62242   minLru = 0x7fffffff;
62243   idxLru = -1;
62244   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62245     if( p->lru<minLru ){
62246       idxLru = i;
62247       minLru = p->lru;
62248     }
62249   }
62250   if( ALWAYS(idxLru>=0) ){
62251     p = &pParse->aColCache[idxLru];
62252     p->iLevel = pParse->iCacheLevel;
62253     p->iTable = iTab;
62254     p->iColumn = iCol;
62255     p->iReg = iReg;
62256     p->tempReg = 0;
62257     p->lru = pParse->iCacheCnt++;
62258     return;
62259   }
62260 }
62261
62262 /*
62263 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
62264 ** Purge the range of registers from the column cache.
62265 */
62266 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
62267   int i;
62268   int iLast = iReg + nReg - 1;
62269   struct yColCache *p;
62270   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62271     int r = p->iReg;
62272     if( r>=iReg && r<=iLast ){
62273       cacheEntryClear(pParse, p);
62274       p->iReg = 0;
62275     }
62276   }
62277 }
62278
62279 /*
62280 ** Remember the current column cache context.  Any new entries added
62281 ** added to the column cache after this call are removed when the
62282 ** corresponding pop occurs.
62283 */
62284 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
62285   pParse->iCacheLevel++;
62286 }
62287
62288 /*
62289 ** Remove from the column cache any entries that were added since the
62290 ** the previous N Push operations.  In other words, restore the cache
62291 ** to the state it was in N Pushes ago.
62292 */
62293 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
62294   int i;
62295   struct yColCache *p;
62296   assert( N>0 );
62297   assert( pParse->iCacheLevel>=N );
62298   pParse->iCacheLevel -= N;
62299   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62300     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
62301       cacheEntryClear(pParse, p);
62302       p->iReg = 0;
62303     }
62304   }
62305 }
62306
62307 /*
62308 ** When a cached column is reused, make sure that its register is
62309 ** no longer available as a temp register.  ticket #3879:  that same
62310 ** register might be in the cache in multiple places, so be sure to
62311 ** get them all.
62312 */
62313 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
62314   int i;
62315   struct yColCache *p;
62316   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62317     if( p->iReg==iReg ){
62318       p->tempReg = 0;
62319     }
62320   }
62321 }
62322
62323 /*
62324 ** Generate code that will extract the iColumn-th column from
62325 ** table pTab and store the column value in a register.  An effort
62326 ** is made to store the column value in register iReg, but this is
62327 ** not guaranteed.  The location of the column value is returned.
62328 **
62329 ** There must be an open cursor to pTab in iTable when this routine
62330 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
62331 */
62332 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
62333   Parse *pParse,   /* Parsing and code generating context */
62334   Table *pTab,     /* Description of the table we are reading from */
62335   int iColumn,     /* Index of the table column */
62336   int iTable,      /* The cursor pointing to the table */
62337   int iReg         /* Store results here */
62338 ){
62339   Vdbe *v = pParse->pVdbe;
62340   int i;
62341   struct yColCache *p;
62342
62343   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62344     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
62345       p->lru = pParse->iCacheCnt++;
62346       sqlite3ExprCachePinRegister(pParse, p->iReg);
62347       return p->iReg;
62348     }
62349   }  
62350   assert( v!=0 );
62351   if( iColumn<0 ){
62352     sqlite3VdbeAddOp2(v, OP_Rowid, iTable, iReg);
62353   }else if( ALWAYS(pTab!=0) ){
62354     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
62355     sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
62356     sqlite3ColumnDefault(v, pTab, iColumn, iReg);
62357   }
62358   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
62359   return iReg;
62360 }
62361
62362 /*
62363 ** Clear all column cache entries.
62364 */
62365 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
62366   int i;
62367   struct yColCache *p;
62368
62369   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62370     if( p->iReg ){
62371       cacheEntryClear(pParse, p);
62372       p->iReg = 0;
62373     }
62374   }
62375 }
62376
62377 /*
62378 ** Record the fact that an affinity change has occurred on iCount
62379 ** registers starting with iStart.
62380 */
62381 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
62382   sqlite3ExprCacheRemove(pParse, iStart, iCount);
62383 }
62384
62385 /*
62386 ** Generate code to move content from registers iFrom...iFrom+nReg-1
62387 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
62388 */
62389 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
62390   int i;
62391   struct yColCache *p;
62392   if( NEVER(iFrom==iTo) ) return;
62393   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
62394   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62395     int x = p->iReg;
62396     if( x>=iFrom && x<iFrom+nReg ){
62397       p->iReg += iTo-iFrom;
62398     }
62399   }
62400 }
62401
62402 /*
62403 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
62404 ** over to iTo..iTo+nReg-1.
62405 */
62406 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
62407   int i;
62408   if( NEVER(iFrom==iTo) ) return;
62409   for(i=0; i<nReg; i++){
62410     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
62411   }
62412 }
62413
62414 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
62415 /*
62416 ** Return true if any register in the range iFrom..iTo (inclusive)
62417 ** is used as part of the column cache.
62418 **
62419 ** This routine is used within assert() and testcase() macros only
62420 ** and does not appear in a normal build.
62421 */
62422 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
62423   int i;
62424   struct yColCache *p;
62425   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62426     int r = p->iReg;
62427     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
62428   }
62429   return 0;
62430 }
62431 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
62432
62433 /*
62434 ** If the last instruction coded is an ephemeral copy of any of
62435 ** the registers in the nReg registers beginning with iReg, then
62436 ** convert the last instruction from OP_SCopy to OP_Copy.
62437 */
62438 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
62439   VdbeOp *pOp;
62440   Vdbe *v;
62441
62442   assert( pParse->db->mallocFailed==0 );
62443   v = pParse->pVdbe;
62444   assert( v!=0 );
62445   pOp = sqlite3VdbeGetOp(v, -1);
62446   assert( pOp!=0 );
62447   if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
62448     pOp->opcode = OP_Copy;
62449   }
62450 }
62451
62452 /*
62453 ** Generate code to store the value of the iAlias-th alias in register
62454 ** target.  The first time this is called, pExpr is evaluated to compute
62455 ** the value of the alias.  The value is stored in an auxiliary register
62456 ** and the number of that register is returned.  On subsequent calls,
62457 ** the register number is returned without generating any code.
62458 **
62459 ** Note that in order for this to work, code must be generated in the
62460 ** same order that it is executed.
62461 **
62462 ** Aliases are numbered starting with 1.  So iAlias is in the range
62463 ** of 1 to pParse->nAlias inclusive.  
62464 **
62465 ** pParse->aAlias[iAlias-1] records the register number where the value
62466 ** of the iAlias-th alias is stored.  If zero, that means that the
62467 ** alias has not yet been computed.
62468 */
62469 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
62470 #if 0
62471   sqlite3 *db = pParse->db;
62472   int iReg;
62473   if( pParse->nAliasAlloc<pParse->nAlias ){
62474     pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
62475                                  sizeof(pParse->aAlias[0])*pParse->nAlias );
62476     testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
62477     if( db->mallocFailed ) return 0;
62478     memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
62479            (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
62480     pParse->nAliasAlloc = pParse->nAlias;
62481   }
62482   assert( iAlias>0 && iAlias<=pParse->nAlias );
62483   iReg = pParse->aAlias[iAlias-1];
62484   if( iReg==0 ){
62485     if( pParse->iCacheLevel>0 ){
62486       iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
62487     }else{
62488       iReg = ++pParse->nMem;
62489       sqlite3ExprCode(pParse, pExpr, iReg);
62490       pParse->aAlias[iAlias-1] = iReg;
62491     }
62492   }
62493   return iReg;
62494 #else
62495   UNUSED_PARAMETER(iAlias);
62496   return sqlite3ExprCodeTarget(pParse, pExpr, target);
62497 #endif
62498 }
62499
62500 /*
62501 ** Generate code into the current Vdbe to evaluate the given
62502 ** expression.  Attempt to store the results in register "target".
62503 ** Return the register where results are stored.
62504 **
62505 ** With this routine, there is no guarantee that results will
62506 ** be stored in target.  The result might be stored in some other
62507 ** register if it is convenient to do so.  The calling function
62508 ** must check the return code and move the results to the desired
62509 ** register.
62510 */
62511 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
62512   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
62513   int op;                   /* The opcode being coded */
62514   int inReg = target;       /* Results stored in register inReg */
62515   int regFree1 = 0;         /* If non-zero free this temporary register */
62516   int regFree2 = 0;         /* If non-zero free this temporary register */
62517   int r1, r2, r3, r4;       /* Various register numbers */
62518   sqlite3 *db = pParse->db; /* The database connection */
62519
62520   assert( target>0 && target<=pParse->nMem );
62521   if( v==0 ){
62522     assert( pParse->db->mallocFailed );
62523     return 0;
62524   }
62525
62526   if( pExpr==0 ){
62527     op = TK_NULL;
62528   }else{
62529     op = pExpr->op;
62530   }
62531   switch( op ){
62532     case TK_AGG_COLUMN: {
62533       AggInfo *pAggInfo = pExpr->pAggInfo;
62534       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
62535       if( !pAggInfo->directMode ){
62536         assert( pCol->iMem>0 );
62537         inReg = pCol->iMem;
62538         break;
62539       }else if( pAggInfo->useSortingIdx ){
62540         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
62541                               pCol->iSorterColumn, target);
62542         break;
62543       }
62544       /* Otherwise, fall thru into the TK_COLUMN case */
62545     }
62546     case TK_COLUMN: {
62547       if( pExpr->iTable<0 ){
62548         /* This only happens when coding check constraints */
62549         assert( pParse->ckBase>0 );
62550         inReg = pExpr->iColumn + pParse->ckBase;
62551       }else{
62552         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
62553                                  pExpr->iColumn, pExpr->iTable, target);
62554       }
62555       break;
62556     }
62557     case TK_INTEGER: {
62558       codeInteger(v, pExpr, 0, target);
62559       break;
62560     }
62561     case TK_FLOAT: {
62562       assert( !ExprHasProperty(pExpr, EP_IntValue) );
62563       codeReal(v, pExpr->u.zToken, 0, target);
62564       break;
62565     }
62566     case TK_STRING: {
62567       assert( !ExprHasProperty(pExpr, EP_IntValue) );
62568       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
62569       break;
62570     }
62571     case TK_NULL: {
62572       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
62573       break;
62574     }
62575 #ifndef SQLITE_OMIT_BLOB_LITERAL
62576     case TK_BLOB: {
62577       int n;
62578       const char *z;
62579       char *zBlob;
62580       assert( !ExprHasProperty(pExpr, EP_IntValue) );
62581       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
62582       assert( pExpr->u.zToken[1]=='\'' );
62583       z = &pExpr->u.zToken[2];
62584       n = sqlite3Strlen30(z) - 1;
62585       assert( z[n]=='\'' );
62586       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
62587       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
62588       break;
62589     }
62590 #endif
62591     case TK_VARIABLE: {
62592       VdbeOp *pOp;
62593       assert( !ExprHasProperty(pExpr, EP_IntValue) );
62594       assert( pExpr->u.zToken!=0 );
62595       assert( pExpr->u.zToken[0]!=0 );
62596       if( pExpr->u.zToken[1]==0
62597          && (pOp = sqlite3VdbeGetOp(v, -1))->opcode==OP_Variable
62598          && pOp->p1+pOp->p3==pExpr->iColumn
62599          && pOp->p2+pOp->p3==target
62600          && pOp->p4.z==0
62601       ){
62602         /* If the previous instruction was a copy of the previous unnamed
62603         ** parameter into the previous register, then simply increment the
62604         ** repeat count on the prior instruction rather than making a new
62605         ** instruction.
62606         */
62607         pOp->p3++;
62608       }else{
62609         sqlite3VdbeAddOp3(v, OP_Variable, pExpr->iColumn, target, 1);
62610         if( pExpr->u.zToken[1]!=0 ){
62611           sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
62612         }
62613       }
62614       break;
62615     }
62616     case TK_REGISTER: {
62617       inReg = pExpr->iTable;
62618       break;
62619     }
62620     case TK_AS: {
62621       inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
62622       break;
62623     }
62624 #ifndef SQLITE_OMIT_CAST
62625     case TK_CAST: {
62626       /* Expressions of the form:   CAST(pLeft AS token) */
62627       int aff, to_op;
62628       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
62629       assert( !ExprHasProperty(pExpr, EP_IntValue) );
62630       aff = sqlite3AffinityType(pExpr->u.zToken);
62631       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
62632       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
62633       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
62634       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
62635       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
62636       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
62637       testcase( to_op==OP_ToText );
62638       testcase( to_op==OP_ToBlob );
62639       testcase( to_op==OP_ToNumeric );
62640       testcase( to_op==OP_ToInt );
62641       testcase( to_op==OP_ToReal );
62642       if( inReg!=target ){
62643         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
62644         inReg = target;
62645       }
62646       sqlite3VdbeAddOp1(v, to_op, inReg);
62647       testcase( usedAsColumnCache(pParse, inReg, inReg) );
62648       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
62649       break;
62650     }
62651 #endif /* SQLITE_OMIT_CAST */
62652     case TK_LT:
62653     case TK_LE:
62654     case TK_GT:
62655     case TK_GE:
62656     case TK_NE:
62657     case TK_EQ: {
62658       assert( TK_LT==OP_Lt );
62659       assert( TK_LE==OP_Le );
62660       assert( TK_GT==OP_Gt );
62661       assert( TK_GE==OP_Ge );
62662       assert( TK_EQ==OP_Eq );
62663       assert( TK_NE==OP_Ne );
62664       testcase( op==TK_LT );
62665       testcase( op==TK_LE );
62666       testcase( op==TK_GT );
62667       testcase( op==TK_GE );
62668       testcase( op==TK_EQ );
62669       testcase( op==TK_NE );
62670       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62671       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
62672       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
62673                   r1, r2, inReg, SQLITE_STOREP2);
62674       testcase( regFree1==0 );
62675       testcase( regFree2==0 );
62676       break;
62677     }
62678     case TK_IS:
62679     case TK_ISNOT: {
62680       testcase( op==TK_IS );
62681       testcase( op==TK_ISNOT );
62682       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62683       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
62684       op = (op==TK_IS) ? TK_EQ : TK_NE;
62685       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
62686                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
62687       testcase( regFree1==0 );
62688       testcase( regFree2==0 );
62689       break;
62690     }
62691     case TK_AND:
62692     case TK_OR:
62693     case TK_PLUS:
62694     case TK_STAR:
62695     case TK_MINUS:
62696     case TK_REM:
62697     case TK_BITAND:
62698     case TK_BITOR:
62699     case TK_SLASH:
62700     case TK_LSHIFT:
62701     case TK_RSHIFT: 
62702     case TK_CONCAT: {
62703       assert( TK_AND==OP_And );
62704       assert( TK_OR==OP_Or );
62705       assert( TK_PLUS==OP_Add );
62706       assert( TK_MINUS==OP_Subtract );
62707       assert( TK_REM==OP_Remainder );
62708       assert( TK_BITAND==OP_BitAnd );
62709       assert( TK_BITOR==OP_BitOr );
62710       assert( TK_SLASH==OP_Divide );
62711       assert( TK_LSHIFT==OP_ShiftLeft );
62712       assert( TK_RSHIFT==OP_ShiftRight );
62713       assert( TK_CONCAT==OP_Concat );
62714       testcase( op==TK_AND );
62715       testcase( op==TK_OR );
62716       testcase( op==TK_PLUS );
62717       testcase( op==TK_MINUS );
62718       testcase( op==TK_REM );
62719       testcase( op==TK_BITAND );
62720       testcase( op==TK_BITOR );
62721       testcase( op==TK_SLASH );
62722       testcase( op==TK_LSHIFT );
62723       testcase( op==TK_RSHIFT );
62724       testcase( op==TK_CONCAT );
62725       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62726       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
62727       sqlite3VdbeAddOp3(v, op, r2, r1, target);
62728       testcase( regFree1==0 );
62729       testcase( regFree2==0 );
62730       break;
62731     }
62732     case TK_UMINUS: {
62733       Expr *pLeft = pExpr->pLeft;
62734       assert( pLeft );
62735       if( pLeft->op==TK_FLOAT ){
62736         assert( !ExprHasProperty(pExpr, EP_IntValue) );
62737         codeReal(v, pLeft->u.zToken, 1, target);
62738       }else if( pLeft->op==TK_INTEGER ){
62739         codeInteger(v, pLeft, 1, target);
62740       }else{
62741         regFree1 = r1 = sqlite3GetTempReg(pParse);
62742         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
62743         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
62744         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
62745         testcase( regFree2==0 );
62746       }
62747       inReg = target;
62748       break;
62749     }
62750     case TK_BITNOT:
62751     case TK_NOT: {
62752       assert( TK_BITNOT==OP_BitNot );
62753       assert( TK_NOT==OP_Not );
62754       testcase( op==TK_BITNOT );
62755       testcase( op==TK_NOT );
62756       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62757       testcase( regFree1==0 );
62758       inReg = target;
62759       sqlite3VdbeAddOp2(v, op, r1, inReg);
62760       break;
62761     }
62762     case TK_ISNULL:
62763     case TK_NOTNULL: {
62764       int addr;
62765       assert( TK_ISNULL==OP_IsNull );
62766       assert( TK_NOTNULL==OP_NotNull );
62767       testcase( op==TK_ISNULL );
62768       testcase( op==TK_NOTNULL );
62769       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
62770       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62771       testcase( regFree1==0 );
62772       addr = sqlite3VdbeAddOp1(v, op, r1);
62773       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
62774       sqlite3VdbeJumpHere(v, addr);
62775       break;
62776     }
62777     case TK_AGG_FUNCTION: {
62778       AggInfo *pInfo = pExpr->pAggInfo;
62779       if( pInfo==0 ){
62780         assert( !ExprHasProperty(pExpr, EP_IntValue) );
62781         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
62782       }else{
62783         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
62784       }
62785       break;
62786     }
62787     case TK_CONST_FUNC:
62788     case TK_FUNCTION: {
62789       ExprList *pFarg;       /* List of function arguments */
62790       int nFarg;             /* Number of function arguments */
62791       FuncDef *pDef;         /* The function definition object */
62792       int nId;               /* Length of the function name in bytes */
62793       const char *zId;       /* The function name */
62794       int constMask = 0;     /* Mask of function arguments that are constant */
62795       int i;                 /* Loop counter */
62796       u8 enc = ENC(db);      /* The text encoding used by this database */
62797       CollSeq *pColl = 0;    /* A collating sequence */
62798
62799       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
62800       testcase( op==TK_CONST_FUNC );
62801       testcase( op==TK_FUNCTION );
62802       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
62803         pFarg = 0;
62804       }else{
62805         pFarg = pExpr->x.pList;
62806       }
62807       nFarg = pFarg ? pFarg->nExpr : 0;
62808       assert( !ExprHasProperty(pExpr, EP_IntValue) );
62809       zId = pExpr->u.zToken;
62810       nId = sqlite3Strlen30(zId);
62811       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
62812       if( pDef==0 ){
62813         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
62814         break;
62815       }
62816
62817       /* Attempt a direct implementation of the built-in COALESCE() and
62818       ** IFNULL() functions.  This avoids unnecessary evalation of
62819       ** arguments past the first non-NULL argument.
62820       */
62821       if( pDef->flags & SQLITE_FUNC_COALESCE ){
62822         int endCoalesce = sqlite3VdbeMakeLabel(v);
62823         assert( nFarg>=2 );
62824         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
62825         for(i=1; i<nFarg; i++){
62826           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
62827           sqlite3ExprCacheRemove(pParse, target, 1);
62828           sqlite3ExprCachePush(pParse);
62829           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
62830           sqlite3ExprCachePop(pParse, 1);
62831         }
62832         sqlite3VdbeResolveLabel(v, endCoalesce);
62833         break;
62834       }
62835
62836
62837       if( pFarg ){
62838         r1 = sqlite3GetTempRange(pParse, nFarg);
62839         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
62840         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
62841         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
62842       }else{
62843         r1 = 0;
62844       }
62845 #ifndef SQLITE_OMIT_VIRTUALTABLE
62846       /* Possibly overload the function if the first argument is
62847       ** a virtual table column.
62848       **
62849       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
62850       ** second argument, not the first, as the argument to test to
62851       ** see if it is a column in a virtual table.  This is done because
62852       ** the left operand of infix functions (the operand we want to
62853       ** control overloading) ends up as the second argument to the
62854       ** function.  The expression "A glob B" is equivalent to 
62855       ** "glob(B,A).  We want to use the A in "A glob B" to test
62856       ** for function overloading.  But we use the B term in "glob(B,A)".
62857       */
62858       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
62859         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
62860       }else if( nFarg>0 ){
62861         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
62862       }
62863 #endif
62864       for(i=0; i<nFarg; i++){
62865         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
62866           constMask |= (1<<i);
62867         }
62868         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
62869           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
62870         }
62871       }
62872       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
62873         if( !pColl ) pColl = db->pDfltColl; 
62874         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
62875       }
62876       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
62877                         (char*)pDef, P4_FUNCDEF);
62878       sqlite3VdbeChangeP5(v, (u8)nFarg);
62879       if( nFarg ){
62880         sqlite3ReleaseTempRange(pParse, r1, nFarg);
62881       }
62882       break;
62883     }
62884 #ifndef SQLITE_OMIT_SUBQUERY
62885     case TK_EXISTS:
62886     case TK_SELECT: {
62887       testcase( op==TK_EXISTS );
62888       testcase( op==TK_SELECT );
62889       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
62890       break;
62891     }
62892     case TK_IN: {
62893       int destIfFalse = sqlite3VdbeMakeLabel(v);
62894       int destIfNull = sqlite3VdbeMakeLabel(v);
62895       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
62896       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
62897       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
62898       sqlite3VdbeResolveLabel(v, destIfFalse);
62899       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
62900       sqlite3VdbeResolveLabel(v, destIfNull);
62901       break;
62902     }
62903 #endif /* SQLITE_OMIT_SUBQUERY */
62904
62905
62906     /*
62907     **    x BETWEEN y AND z
62908     **
62909     ** This is equivalent to
62910     **
62911     **    x>=y AND x<=z
62912     **
62913     ** X is stored in pExpr->pLeft.
62914     ** Y is stored in pExpr->pList->a[0].pExpr.
62915     ** Z is stored in pExpr->pList->a[1].pExpr.
62916     */
62917     case TK_BETWEEN: {
62918       Expr *pLeft = pExpr->pLeft;
62919       struct ExprList_item *pLItem = pExpr->x.pList->a;
62920       Expr *pRight = pLItem->pExpr;
62921
62922       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
62923       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
62924       testcase( regFree1==0 );
62925       testcase( regFree2==0 );
62926       r3 = sqlite3GetTempReg(pParse);
62927       r4 = sqlite3GetTempReg(pParse);
62928       codeCompare(pParse, pLeft, pRight, OP_Ge,
62929                   r1, r2, r3, SQLITE_STOREP2);
62930       pLItem++;
62931       pRight = pLItem->pExpr;
62932       sqlite3ReleaseTempReg(pParse, regFree2);
62933       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
62934       testcase( regFree2==0 );
62935       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
62936       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
62937       sqlite3ReleaseTempReg(pParse, r3);
62938       sqlite3ReleaseTempReg(pParse, r4);
62939       break;
62940     }
62941     case TK_UPLUS: {
62942       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
62943       break;
62944     }
62945
62946     case TK_TRIGGER: {
62947       /* If the opcode is TK_TRIGGER, then the expression is a reference
62948       ** to a column in the new.* or old.* pseudo-tables available to
62949       ** trigger programs. In this case Expr.iTable is set to 1 for the
62950       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
62951       ** is set to the column of the pseudo-table to read, or to -1 to
62952       ** read the rowid field.
62953       **
62954       ** The expression is implemented using an OP_Param opcode. The p1
62955       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
62956       ** to reference another column of the old.* pseudo-table, where 
62957       ** i is the index of the column. For a new.rowid reference, p1 is
62958       ** set to (n+1), where n is the number of columns in each pseudo-table.
62959       ** For a reference to any other column in the new.* pseudo-table, p1
62960       ** is set to (n+2+i), where n and i are as defined previously. For
62961       ** example, if the table on which triggers are being fired is
62962       ** declared as:
62963       **
62964       **   CREATE TABLE t1(a, b);
62965       **
62966       ** Then p1 is interpreted as follows:
62967       **
62968       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
62969       **   p1==1   ->    old.a         p1==4   ->    new.a
62970       **   p1==2   ->    old.b         p1==5   ->    new.b       
62971       */
62972       Table *pTab = pExpr->pTab;
62973       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
62974
62975       assert( pExpr->iTable==0 || pExpr->iTable==1 );
62976       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
62977       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
62978       assert( p1>=0 && p1<(pTab->nCol*2+2) );
62979
62980       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
62981       VdbeComment((v, "%s.%s -> $%d",
62982         (pExpr->iTable ? "new" : "old"),
62983         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
62984         target
62985       ));
62986
62987       /* If the column has REAL affinity, it may currently be stored as an
62988       ** integer. Use OP_RealAffinity to make sure it is really real.  */
62989       if( pExpr->iColumn>=0 
62990        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
62991       ){
62992         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
62993       }
62994       break;
62995     }
62996
62997
62998     /*
62999     ** Form A:
63000     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
63001     **
63002     ** Form B:
63003     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
63004     **
63005     ** Form A is can be transformed into the equivalent form B as follows:
63006     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
63007     **        WHEN x=eN THEN rN ELSE y END
63008     **
63009     ** X (if it exists) is in pExpr->pLeft.
63010     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
63011     ** ELSE clause and no other term matches, then the result of the
63012     ** exprssion is NULL.
63013     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
63014     **
63015     ** The result of the expression is the Ri for the first matching Ei,
63016     ** or if there is no matching Ei, the ELSE term Y, or if there is
63017     ** no ELSE term, NULL.
63018     */
63019     default: assert( op==TK_CASE ); {
63020       int endLabel;                     /* GOTO label for end of CASE stmt */
63021       int nextCase;                     /* GOTO label for next WHEN clause */
63022       int nExpr;                        /* 2x number of WHEN terms */
63023       int i;                            /* Loop counter */
63024       ExprList *pEList;                 /* List of WHEN terms */
63025       struct ExprList_item *aListelem;  /* Array of WHEN terms */
63026       Expr opCompare;                   /* The X==Ei expression */
63027       Expr cacheX;                      /* Cached expression X */
63028       Expr *pX;                         /* The X expression */
63029       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
63030       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
63031
63032       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
63033       assert((pExpr->x.pList->nExpr % 2) == 0);
63034       assert(pExpr->x.pList->nExpr > 0);
63035       pEList = pExpr->x.pList;
63036       aListelem = pEList->a;
63037       nExpr = pEList->nExpr;
63038       endLabel = sqlite3VdbeMakeLabel(v);
63039       if( (pX = pExpr->pLeft)!=0 ){
63040         cacheX = *pX;
63041         testcase( pX->op==TK_COLUMN );
63042         testcase( pX->op==TK_REGISTER );
63043         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
63044         testcase( regFree1==0 );
63045         cacheX.op = TK_REGISTER;
63046         opCompare.op = TK_EQ;
63047         opCompare.pLeft = &cacheX;
63048         pTest = &opCompare;
63049       }
63050       for(i=0; i<nExpr; i=i+2){
63051         sqlite3ExprCachePush(pParse);
63052         if( pX ){
63053           assert( pTest!=0 );
63054           opCompare.pRight = aListelem[i].pExpr;
63055         }else{
63056           pTest = aListelem[i].pExpr;
63057         }
63058         nextCase = sqlite3VdbeMakeLabel(v);
63059         testcase( pTest->op==TK_COLUMN );
63060         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
63061         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
63062         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
63063         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
63064         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
63065         sqlite3ExprCachePop(pParse, 1);
63066         sqlite3VdbeResolveLabel(v, nextCase);
63067       }
63068       if( pExpr->pRight ){
63069         sqlite3ExprCachePush(pParse);
63070         sqlite3ExprCode(pParse, pExpr->pRight, target);
63071         sqlite3ExprCachePop(pParse, 1);
63072       }else{
63073         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
63074       }
63075       assert( db->mallocFailed || pParse->nErr>0 
63076            || pParse->iCacheLevel==iCacheLevel );
63077       sqlite3VdbeResolveLabel(v, endLabel);
63078       break;
63079     }
63080 #ifndef SQLITE_OMIT_TRIGGER
63081     case TK_RAISE: {
63082       assert( pExpr->affinity==OE_Rollback 
63083            || pExpr->affinity==OE_Abort
63084            || pExpr->affinity==OE_Fail
63085            || pExpr->affinity==OE_Ignore
63086       );
63087       if( !pParse->pTriggerTab ){
63088         sqlite3ErrorMsg(pParse,
63089                        "RAISE() may only be used within a trigger-program");
63090         return 0;
63091       }
63092       if( pExpr->affinity==OE_Abort ){
63093         sqlite3MayAbort(pParse);
63094       }
63095       assert( !ExprHasProperty(pExpr, EP_IntValue) );
63096       if( pExpr->affinity==OE_Ignore ){
63097         sqlite3VdbeAddOp4(
63098             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
63099       }else{
63100         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
63101       }
63102
63103       break;
63104     }
63105 #endif
63106   }
63107   sqlite3ReleaseTempReg(pParse, regFree1);
63108   sqlite3ReleaseTempReg(pParse, regFree2);
63109   return inReg;
63110 }
63111
63112 /*
63113 ** Generate code to evaluate an expression and store the results
63114 ** into a register.  Return the register number where the results
63115 ** are stored.
63116 **
63117 ** If the register is a temporary register that can be deallocated,
63118 ** then write its number into *pReg.  If the result register is not
63119 ** a temporary, then set *pReg to zero.
63120 */
63121 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
63122   int r1 = sqlite3GetTempReg(pParse);
63123   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
63124   if( r2==r1 ){
63125     *pReg = r1;
63126   }else{
63127     sqlite3ReleaseTempReg(pParse, r1);
63128     *pReg = 0;
63129   }
63130   return r2;
63131 }
63132
63133 /*
63134 ** Generate code that will evaluate expression pExpr and store the
63135 ** results in register target.  The results are guaranteed to appear
63136 ** in register target.
63137 */
63138 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
63139   int inReg;
63140
63141   assert( target>0 && target<=pParse->nMem );
63142   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
63143   assert( pParse->pVdbe || pParse->db->mallocFailed );
63144   if( inReg!=target && pParse->pVdbe ){
63145     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
63146   }
63147   return target;
63148 }
63149
63150 /*
63151 ** Generate code that evalutes the given expression and puts the result
63152 ** in register target.
63153 **
63154 ** Also make a copy of the expression results into another "cache" register
63155 ** and modify the expression so that the next time it is evaluated,
63156 ** the result is a copy of the cache register.
63157 **
63158 ** This routine is used for expressions that are used multiple 
63159 ** times.  They are evaluated once and the results of the expression
63160 ** are reused.
63161 */
63162 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
63163   Vdbe *v = pParse->pVdbe;
63164   int inReg;
63165   inReg = sqlite3ExprCode(pParse, pExpr, target);
63166   assert( target>0 );
63167   /* This routine is called for terms to INSERT or UPDATE.  And the only
63168   ** other place where expressions can be converted into TK_REGISTER is
63169   ** in WHERE clause processing.  So as currently implemented, there is
63170   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
63171   ** keep the ALWAYS() in case the conditions above change with future
63172   ** modifications or enhancements. */
63173   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
63174     int iMem;
63175     iMem = ++pParse->nMem;
63176     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
63177     pExpr->iTable = iMem;
63178     pExpr->op2 = pExpr->op;
63179     pExpr->op = TK_REGISTER;
63180   }
63181   return inReg;
63182 }
63183
63184 /*
63185 ** Return TRUE if pExpr is an constant expression that is appropriate
63186 ** for factoring out of a loop.  Appropriate expressions are:
63187 **
63188 **    *  Any expression that evaluates to two or more opcodes.
63189 **
63190 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
63191 **       or OP_Variable that does not need to be placed in a 
63192 **       specific register.
63193 **
63194 ** There is no point in factoring out single-instruction constant
63195 ** expressions that need to be placed in a particular register.  
63196 ** We could factor them out, but then we would end up adding an
63197 ** OP_SCopy instruction to move the value into the correct register
63198 ** later.  We might as well just use the original instruction and
63199 ** avoid the OP_SCopy.
63200 */
63201 static int isAppropriateForFactoring(Expr *p){
63202   if( !sqlite3ExprIsConstantNotJoin(p) ){
63203     return 0;  /* Only constant expressions are appropriate for factoring */
63204   }
63205   if( (p->flags & EP_FixedDest)==0 ){
63206     return 1;  /* Any constant without a fixed destination is appropriate */
63207   }
63208   while( p->op==TK_UPLUS ) p = p->pLeft;
63209   switch( p->op ){
63210 #ifndef SQLITE_OMIT_BLOB_LITERAL
63211     case TK_BLOB:
63212 #endif
63213     case TK_VARIABLE:
63214     case TK_INTEGER:
63215     case TK_FLOAT:
63216     case TK_NULL:
63217     case TK_STRING: {
63218       testcase( p->op==TK_BLOB );
63219       testcase( p->op==TK_VARIABLE );
63220       testcase( p->op==TK_INTEGER );
63221       testcase( p->op==TK_FLOAT );
63222       testcase( p->op==TK_NULL );
63223       testcase( p->op==TK_STRING );
63224       /* Single-instruction constants with a fixed destination are
63225       ** better done in-line.  If we factor them, they will just end
63226       ** up generating an OP_SCopy to move the value to the destination
63227       ** register. */
63228       return 0;
63229     }
63230     case TK_UMINUS: {
63231       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
63232         return 0;
63233       }
63234       break;
63235     }
63236     default: {
63237       break;
63238     }
63239   }
63240   return 1;
63241 }
63242
63243 /*
63244 ** If pExpr is a constant expression that is appropriate for
63245 ** factoring out of a loop, then evaluate the expression
63246 ** into a register and convert the expression into a TK_REGISTER
63247 ** expression.
63248 */
63249 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
63250   Parse *pParse = pWalker->pParse;
63251   switch( pExpr->op ){
63252     case TK_IN:
63253     case TK_REGISTER: {
63254       return WRC_Prune;
63255     }
63256     case TK_FUNCTION:
63257     case TK_AGG_FUNCTION:
63258     case TK_CONST_FUNC: {
63259       /* The arguments to a function have a fixed destination.
63260       ** Mark them this way to avoid generated unneeded OP_SCopy
63261       ** instructions. 
63262       */
63263       ExprList *pList = pExpr->x.pList;
63264       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
63265       if( pList ){
63266         int i = pList->nExpr;
63267         struct ExprList_item *pItem = pList->a;
63268         for(; i>0; i--, pItem++){
63269           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
63270         }
63271       }
63272       break;
63273     }
63274   }
63275   if( isAppropriateForFactoring(pExpr) ){
63276     int r1 = ++pParse->nMem;
63277     int r2;
63278     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
63279     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
63280     pExpr->op2 = pExpr->op;
63281     pExpr->op = TK_REGISTER;
63282     pExpr->iTable = r2;
63283     return WRC_Prune;
63284   }
63285   return WRC_Continue;
63286 }
63287
63288 /*
63289 ** Preevaluate constant subexpressions within pExpr and store the
63290 ** results in registers.  Modify pExpr so that the constant subexpresions
63291 ** are TK_REGISTER opcodes that refer to the precomputed values.
63292 */
63293 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
63294   Walker w;
63295   w.xExprCallback = evalConstExpr;
63296   w.xSelectCallback = 0;
63297   w.pParse = pParse;
63298   sqlite3WalkExpr(&w, pExpr);
63299 }
63300
63301
63302 /*
63303 ** Generate code that pushes the value of every element of the given
63304 ** expression list into a sequence of registers beginning at target.
63305 **
63306 ** Return the number of elements evaluated.
63307 */
63308 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
63309   Parse *pParse,     /* Parsing context */
63310   ExprList *pList,   /* The expression list to be coded */
63311   int target,        /* Where to write results */
63312   int doHardCopy     /* Make a hard copy of every element */
63313 ){
63314   struct ExprList_item *pItem;
63315   int i, n;
63316   assert( pList!=0 );
63317   assert( target>0 );
63318   n = pList->nExpr;
63319   for(pItem=pList->a, i=0; i<n; i++, pItem++){
63320     if( pItem->iAlias ){
63321       int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
63322       Vdbe *v = sqlite3GetVdbe(pParse);
63323       if( iReg!=target+i ){
63324         sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
63325       }
63326     }else{
63327       sqlite3ExprCode(pParse, pItem->pExpr, target+i);
63328     }
63329     if( doHardCopy && !pParse->db->mallocFailed ){
63330       sqlite3ExprHardCopy(pParse, target, n);
63331     }
63332   }
63333   return n;
63334 }
63335
63336 /*
63337 ** Generate code for a BETWEEN operator.
63338 **
63339 **    x BETWEEN y AND z
63340 **
63341 ** The above is equivalent to 
63342 **
63343 **    x>=y AND x<=z
63344 **
63345 ** Code it as such, taking care to do the common subexpression
63346 ** elementation of x.
63347 */
63348 static void exprCodeBetween(
63349   Parse *pParse,    /* Parsing and code generating context */
63350   Expr *pExpr,      /* The BETWEEN expression */
63351   int dest,         /* Jump here if the jump is taken */
63352   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
63353   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
63354 ){
63355   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
63356   Expr compLeft;    /* The  x>=y  term */
63357   Expr compRight;   /* The  x<=z  term */
63358   Expr exprX;       /* The  x  subexpression */
63359   int regFree1 = 0; /* Temporary use register */
63360
63361   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
63362   exprX = *pExpr->pLeft;
63363   exprAnd.op = TK_AND;
63364   exprAnd.pLeft = &compLeft;
63365   exprAnd.pRight = &compRight;
63366   compLeft.op = TK_GE;
63367   compLeft.pLeft = &exprX;
63368   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
63369   compRight.op = TK_LE;
63370   compRight.pLeft = &exprX;
63371   compRight.pRight = pExpr->x.pList->a[1].pExpr;
63372   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
63373   exprX.op = TK_REGISTER;
63374   if( jumpIfTrue ){
63375     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
63376   }else{
63377     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
63378   }
63379   sqlite3ReleaseTempReg(pParse, regFree1);
63380
63381   /* Ensure adequate test coverage */
63382   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
63383   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
63384   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
63385   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
63386   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
63387   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
63388   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
63389   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
63390 }
63391
63392 /*
63393 ** Generate code for a boolean expression such that a jump is made
63394 ** to the label "dest" if the expression is true but execution
63395 ** continues straight thru if the expression is false.
63396 **
63397 ** If the expression evaluates to NULL (neither true nor false), then
63398 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
63399 **
63400 ** This code depends on the fact that certain token values (ex: TK_EQ)
63401 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
63402 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
63403 ** the make process cause these values to align.  Assert()s in the code
63404 ** below verify that the numbers are aligned correctly.
63405 */
63406 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
63407   Vdbe *v = pParse->pVdbe;
63408   int op = 0;
63409   int regFree1 = 0;
63410   int regFree2 = 0;
63411   int r1, r2;
63412
63413   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
63414   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
63415   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
63416   op = pExpr->op;
63417   switch( op ){
63418     case TK_AND: {
63419       int d2 = sqlite3VdbeMakeLabel(v);
63420       testcase( jumpIfNull==0 );
63421       sqlite3ExprCachePush(pParse);
63422       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
63423       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
63424       sqlite3VdbeResolveLabel(v, d2);
63425       sqlite3ExprCachePop(pParse, 1);
63426       break;
63427     }
63428     case TK_OR: {
63429       testcase( jumpIfNull==0 );
63430       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
63431       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
63432       break;
63433     }
63434     case TK_NOT: {
63435       testcase( jumpIfNull==0 );
63436       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
63437       break;
63438     }
63439     case TK_LT:
63440     case TK_LE:
63441     case TK_GT:
63442     case TK_GE:
63443     case TK_NE:
63444     case TK_EQ: {
63445       assert( TK_LT==OP_Lt );
63446       assert( TK_LE==OP_Le );
63447       assert( TK_GT==OP_Gt );
63448       assert( TK_GE==OP_Ge );
63449       assert( TK_EQ==OP_Eq );
63450       assert( TK_NE==OP_Ne );
63451       testcase( op==TK_LT );
63452       testcase( op==TK_LE );
63453       testcase( op==TK_GT );
63454       testcase( op==TK_GE );
63455       testcase( op==TK_EQ );
63456       testcase( op==TK_NE );
63457       testcase( jumpIfNull==0 );
63458       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63459       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63460       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63461                   r1, r2, dest, jumpIfNull);
63462       testcase( regFree1==0 );
63463       testcase( regFree2==0 );
63464       break;
63465     }
63466     case TK_IS:
63467     case TK_ISNOT: {
63468       testcase( op==TK_IS );
63469       testcase( op==TK_ISNOT );
63470       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63471       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63472       op = (op==TK_IS) ? TK_EQ : TK_NE;
63473       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63474                   r1, r2, dest, SQLITE_NULLEQ);
63475       testcase( regFree1==0 );
63476       testcase( regFree2==0 );
63477       break;
63478     }
63479     case TK_ISNULL:
63480     case TK_NOTNULL: {
63481       assert( TK_ISNULL==OP_IsNull );
63482       assert( TK_NOTNULL==OP_NotNull );
63483       testcase( op==TK_ISNULL );
63484       testcase( op==TK_NOTNULL );
63485       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63486       sqlite3VdbeAddOp2(v, op, r1, dest);
63487       testcase( regFree1==0 );
63488       break;
63489     }
63490     case TK_BETWEEN: {
63491       testcase( jumpIfNull==0 );
63492       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
63493       break;
63494     }
63495     case TK_IN: {
63496       int destIfFalse = sqlite3VdbeMakeLabel(v);
63497       int destIfNull = jumpIfNull ? dest : destIfFalse;
63498       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
63499       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
63500       sqlite3VdbeResolveLabel(v, destIfFalse);
63501       break;
63502     }
63503     default: {
63504       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
63505       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
63506       testcase( regFree1==0 );
63507       testcase( jumpIfNull==0 );
63508       break;
63509     }
63510   }
63511   sqlite3ReleaseTempReg(pParse, regFree1);
63512   sqlite3ReleaseTempReg(pParse, regFree2);  
63513 }
63514
63515 /*
63516 ** Generate code for a boolean expression such that a jump is made
63517 ** to the label "dest" if the expression is false but execution
63518 ** continues straight thru if the expression is true.
63519 **
63520 ** If the expression evaluates to NULL (neither true nor false) then
63521 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
63522 ** is 0.
63523 */
63524 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
63525   Vdbe *v = pParse->pVdbe;
63526   int op = 0;
63527   int regFree1 = 0;
63528   int regFree2 = 0;
63529   int r1, r2;
63530
63531   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
63532   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
63533   if( pExpr==0 )    return;
63534
63535   /* The value of pExpr->op and op are related as follows:
63536   **
63537   **       pExpr->op            op
63538   **       ---------          ----------
63539   **       TK_ISNULL          OP_NotNull
63540   **       TK_NOTNULL         OP_IsNull
63541   **       TK_NE              OP_Eq
63542   **       TK_EQ              OP_Ne
63543   **       TK_GT              OP_Le
63544   **       TK_LE              OP_Gt
63545   **       TK_GE              OP_Lt
63546   **       TK_LT              OP_Ge
63547   **
63548   ** For other values of pExpr->op, op is undefined and unused.
63549   ** The value of TK_ and OP_ constants are arranged such that we
63550   ** can compute the mapping above using the following expression.
63551   ** Assert()s verify that the computation is correct.
63552   */
63553   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
63554
63555   /* Verify correct alignment of TK_ and OP_ constants
63556   */
63557   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
63558   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
63559   assert( pExpr->op!=TK_NE || op==OP_Eq );
63560   assert( pExpr->op!=TK_EQ || op==OP_Ne );
63561   assert( pExpr->op!=TK_LT || op==OP_Ge );
63562   assert( pExpr->op!=TK_LE || op==OP_Gt );
63563   assert( pExpr->op!=TK_GT || op==OP_Le );
63564   assert( pExpr->op!=TK_GE || op==OP_Lt );
63565
63566   switch( pExpr->op ){
63567     case TK_AND: {
63568       testcase( jumpIfNull==0 );
63569       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
63570       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
63571       break;
63572     }
63573     case TK_OR: {
63574       int d2 = sqlite3VdbeMakeLabel(v);
63575       testcase( jumpIfNull==0 );
63576       sqlite3ExprCachePush(pParse);
63577       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
63578       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
63579       sqlite3VdbeResolveLabel(v, d2);
63580       sqlite3ExprCachePop(pParse, 1);
63581       break;
63582     }
63583     case TK_NOT: {
63584       testcase( jumpIfNull==0 );
63585       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
63586       break;
63587     }
63588     case TK_LT:
63589     case TK_LE:
63590     case TK_GT:
63591     case TK_GE:
63592     case TK_NE:
63593     case TK_EQ: {
63594       testcase( op==TK_LT );
63595       testcase( op==TK_LE );
63596       testcase( op==TK_GT );
63597       testcase( op==TK_GE );
63598       testcase( op==TK_EQ );
63599       testcase( op==TK_NE );
63600       testcase( jumpIfNull==0 );
63601       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63602       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63603       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63604                   r1, r2, dest, jumpIfNull);
63605       testcase( regFree1==0 );
63606       testcase( regFree2==0 );
63607       break;
63608     }
63609     case TK_IS:
63610     case TK_ISNOT: {
63611       testcase( pExpr->op==TK_IS );
63612       testcase( pExpr->op==TK_ISNOT );
63613       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63614       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63615       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
63616       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63617                   r1, r2, dest, SQLITE_NULLEQ);
63618       testcase( regFree1==0 );
63619       testcase( regFree2==0 );
63620       break;
63621     }
63622     case TK_ISNULL:
63623     case TK_NOTNULL: {
63624       testcase( op==TK_ISNULL );
63625       testcase( op==TK_NOTNULL );
63626       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63627       sqlite3VdbeAddOp2(v, op, r1, dest);
63628       testcase( regFree1==0 );
63629       break;
63630     }
63631     case TK_BETWEEN: {
63632       testcase( jumpIfNull==0 );
63633       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
63634       break;
63635     }
63636     case TK_IN: {
63637       if( jumpIfNull ){
63638         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
63639       }else{
63640         int destIfNull = sqlite3VdbeMakeLabel(v);
63641         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
63642         sqlite3VdbeResolveLabel(v, destIfNull);
63643       }
63644       break;
63645     }
63646     default: {
63647       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
63648       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
63649       testcase( regFree1==0 );
63650       testcase( jumpIfNull==0 );
63651       break;
63652     }
63653   }
63654   sqlite3ReleaseTempReg(pParse, regFree1);
63655   sqlite3ReleaseTempReg(pParse, regFree2);
63656 }
63657
63658 /*
63659 ** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
63660 ** if they are identical and return FALSE if they differ in any way.
63661 **
63662 ** Sometimes this routine will return FALSE even if the two expressions
63663 ** really are equivalent.  If we cannot prove that the expressions are
63664 ** identical, we return FALSE just to be safe.  So if this routine
63665 ** returns false, then you do not really know for certain if the two
63666 ** expressions are the same.  But if you get a TRUE return, then you
63667 ** can be sure the expressions are the same.  In the places where
63668 ** this routine is used, it does not hurt to get an extra FALSE - that
63669 ** just might result in some slightly slower code.  But returning
63670 ** an incorrect TRUE could lead to a malfunction.
63671 */
63672 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
63673   int i;
63674   if( pA==0||pB==0 ){
63675     return pB==pA;
63676   }
63677   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
63678   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
63679   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
63680     return 0;
63681   }
63682   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
63683   if( pA->op!=pB->op ) return 0;
63684   if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
63685   if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
63686
63687   if( pA->x.pList && pB->x.pList ){
63688     if( pA->x.pList->nExpr!=pB->x.pList->nExpr ) return 0;
63689     for(i=0; i<pA->x.pList->nExpr; i++){
63690       Expr *pExprA = pA->x.pList->a[i].pExpr;
63691       Expr *pExprB = pB->x.pList->a[i].pExpr;
63692       if( !sqlite3ExprCompare(pExprA, pExprB) ) return 0;
63693     }
63694   }else if( pA->x.pList || pB->x.pList ){
63695     return 0;
63696   }
63697
63698   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
63699   if( ExprHasProperty(pA, EP_IntValue) ){
63700     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
63701       return 0;
63702     }
63703   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
63704     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 0;
63705     if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
63706       return 0;
63707     }
63708   }
63709   return 1;
63710 }
63711
63712
63713 /*
63714 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
63715 ** the new element.  Return a negative number if malloc fails.
63716 */
63717 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
63718   int i;
63719   pInfo->aCol = sqlite3ArrayAllocate(
63720        db,
63721        pInfo->aCol,
63722        sizeof(pInfo->aCol[0]),
63723        3,
63724        &pInfo->nColumn,
63725        &pInfo->nColumnAlloc,
63726        &i
63727   );
63728   return i;
63729 }    
63730
63731 /*
63732 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
63733 ** the new element.  Return a negative number if malloc fails.
63734 */
63735 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
63736   int i;
63737   pInfo->aFunc = sqlite3ArrayAllocate(
63738        db, 
63739        pInfo->aFunc,
63740        sizeof(pInfo->aFunc[0]),
63741        3,
63742        &pInfo->nFunc,
63743        &pInfo->nFuncAlloc,
63744        &i
63745   );
63746   return i;
63747 }    
63748
63749 /*
63750 ** This is the xExprCallback for a tree walker.  It is used to
63751 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
63752 ** for additional information.
63753 */
63754 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
63755   int i;
63756   NameContext *pNC = pWalker->u.pNC;
63757   Parse *pParse = pNC->pParse;
63758   SrcList *pSrcList = pNC->pSrcList;
63759   AggInfo *pAggInfo = pNC->pAggInfo;
63760
63761   switch( pExpr->op ){
63762     case TK_AGG_COLUMN:
63763     case TK_COLUMN: {
63764       testcase( pExpr->op==TK_AGG_COLUMN );
63765       testcase( pExpr->op==TK_COLUMN );
63766       /* Check to see if the column is in one of the tables in the FROM
63767       ** clause of the aggregate query */
63768       if( ALWAYS(pSrcList!=0) ){
63769         struct SrcList_item *pItem = pSrcList->a;
63770         for(i=0; i<pSrcList->nSrc; i++, pItem++){
63771           struct AggInfo_col *pCol;
63772           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
63773           if( pExpr->iTable==pItem->iCursor ){
63774             /* If we reach this point, it means that pExpr refers to a table
63775             ** that is in the FROM clause of the aggregate query.  
63776             **
63777             ** Make an entry for the column in pAggInfo->aCol[] if there
63778             ** is not an entry there already.
63779             */
63780             int k;
63781             pCol = pAggInfo->aCol;
63782             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
63783               if( pCol->iTable==pExpr->iTable &&
63784                   pCol->iColumn==pExpr->iColumn ){
63785                 break;
63786               }
63787             }
63788             if( (k>=pAggInfo->nColumn)
63789              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
63790             ){
63791               pCol = &pAggInfo->aCol[k];
63792               pCol->pTab = pExpr->pTab;
63793               pCol->iTable = pExpr->iTable;
63794               pCol->iColumn = pExpr->iColumn;
63795               pCol->iMem = ++pParse->nMem;
63796               pCol->iSorterColumn = -1;
63797               pCol->pExpr = pExpr;
63798               if( pAggInfo->pGroupBy ){
63799                 int j, n;
63800                 ExprList *pGB = pAggInfo->pGroupBy;
63801                 struct ExprList_item *pTerm = pGB->a;
63802                 n = pGB->nExpr;
63803                 for(j=0; j<n; j++, pTerm++){
63804                   Expr *pE = pTerm->pExpr;
63805                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
63806                       pE->iColumn==pExpr->iColumn ){
63807                     pCol->iSorterColumn = j;
63808                     break;
63809                   }
63810                 }
63811               }
63812               if( pCol->iSorterColumn<0 ){
63813                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
63814               }
63815             }
63816             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
63817             ** because it was there before or because we just created it).
63818             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
63819             ** pAggInfo->aCol[] entry.
63820             */
63821             ExprSetIrreducible(pExpr);
63822             pExpr->pAggInfo = pAggInfo;
63823             pExpr->op = TK_AGG_COLUMN;
63824             pExpr->iAgg = (i16)k;
63825             break;
63826           } /* endif pExpr->iTable==pItem->iCursor */
63827         } /* end loop over pSrcList */
63828       }
63829       return WRC_Prune;
63830     }
63831     case TK_AGG_FUNCTION: {
63832       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
63833       ** to be ignored */
63834       if( pNC->nDepth==0 ){
63835         /* Check to see if pExpr is a duplicate of another aggregate 
63836         ** function that is already in the pAggInfo structure
63837         */
63838         struct AggInfo_func *pItem = pAggInfo->aFunc;
63839         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
63840           if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
63841             break;
63842           }
63843         }
63844         if( i>=pAggInfo->nFunc ){
63845           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
63846           */
63847           u8 enc = ENC(pParse->db);
63848           i = addAggInfoFunc(pParse->db, pAggInfo);
63849           if( i>=0 ){
63850             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
63851             pItem = &pAggInfo->aFunc[i];
63852             pItem->pExpr = pExpr;
63853             pItem->iMem = ++pParse->nMem;
63854             assert( !ExprHasProperty(pExpr, EP_IntValue) );
63855             pItem->pFunc = sqlite3FindFunction(pParse->db,
63856                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
63857                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
63858             if( pExpr->flags & EP_Distinct ){
63859               pItem->iDistinct = pParse->nTab++;
63860             }else{
63861               pItem->iDistinct = -1;
63862             }
63863           }
63864         }
63865         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
63866         */
63867         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
63868         ExprSetIrreducible(pExpr);
63869         pExpr->iAgg = (i16)i;
63870         pExpr->pAggInfo = pAggInfo;
63871         return WRC_Prune;
63872       }
63873     }
63874   }
63875   return WRC_Continue;
63876 }
63877 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
63878   NameContext *pNC = pWalker->u.pNC;
63879   if( pNC->nDepth==0 ){
63880     pNC->nDepth++;
63881     sqlite3WalkSelect(pWalker, pSelect);
63882     pNC->nDepth--;
63883     return WRC_Prune;
63884   }else{
63885     return WRC_Continue;
63886   }
63887 }
63888
63889 /*
63890 ** Analyze the given expression looking for aggregate functions and
63891 ** for variables that need to be added to the pParse->aAgg[] array.
63892 ** Make additional entries to the pParse->aAgg[] array as necessary.
63893 **
63894 ** This routine should only be called after the expression has been
63895 ** analyzed by sqlite3ResolveExprNames().
63896 */
63897 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
63898   Walker w;
63899   w.xExprCallback = analyzeAggregate;
63900   w.xSelectCallback = analyzeAggregatesInSelect;
63901   w.u.pNC = pNC;
63902   assert( pNC->pSrcList!=0 );
63903   sqlite3WalkExpr(&w, pExpr);
63904 }
63905
63906 /*
63907 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
63908 ** expression list.  Return the number of errors.
63909 **
63910 ** If an error is found, the analysis is cut short.
63911 */
63912 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
63913   struct ExprList_item *pItem;
63914   int i;
63915   if( pList ){
63916     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
63917       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
63918     }
63919   }
63920 }
63921
63922 /*
63923 ** Allocate a single new register for use to hold some intermediate result.
63924 */
63925 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
63926   if( pParse->nTempReg==0 ){
63927     return ++pParse->nMem;
63928   }
63929   return pParse->aTempReg[--pParse->nTempReg];
63930 }
63931
63932 /*
63933 ** Deallocate a register, making available for reuse for some other
63934 ** purpose.
63935 **
63936 ** If a register is currently being used by the column cache, then
63937 ** the dallocation is deferred until the column cache line that uses
63938 ** the register becomes stale.
63939 */
63940 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
63941   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
63942     int i;
63943     struct yColCache *p;
63944     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
63945       if( p->iReg==iReg ){
63946         p->tempReg = 1;
63947         return;
63948       }
63949     }
63950     pParse->aTempReg[pParse->nTempReg++] = iReg;
63951   }
63952 }
63953
63954 /*
63955 ** Allocate or deallocate a block of nReg consecutive registers
63956 */
63957 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
63958   int i, n;
63959   i = pParse->iRangeReg;
63960   n = pParse->nRangeReg;
63961   if( nReg<=n ){
63962     assert( !usedAsColumnCache(pParse, i, i+n-1) );
63963     pParse->iRangeReg += nReg;
63964     pParse->nRangeReg -= nReg;
63965   }else{
63966     i = pParse->nMem+1;
63967     pParse->nMem += nReg;
63968   }
63969   return i;
63970 }
63971 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
63972   sqlite3ExprCacheRemove(pParse, iReg, nReg);
63973   if( nReg>pParse->nRangeReg ){
63974     pParse->nRangeReg = nReg;
63975     pParse->iRangeReg = iReg;
63976   }
63977 }
63978
63979 /************** End of expr.c ************************************************/
63980 /************** Begin file alter.c *******************************************/
63981 /*
63982 ** 2005 February 15
63983 **
63984 ** The author disclaims copyright to this source code.  In place of
63985 ** a legal notice, here is a blessing:
63986 **
63987 **    May you do good and not evil.
63988 **    May you find forgiveness for yourself and forgive others.
63989 **    May you share freely, never taking more than you give.
63990 **
63991 *************************************************************************
63992 ** This file contains C code routines that used to generate VDBE code
63993 ** that implements the ALTER TABLE command.
63994 */
63995
63996 /*
63997 ** The code in this file only exists if we are not omitting the
63998 ** ALTER TABLE logic from the build.
63999 */
64000 #ifndef SQLITE_OMIT_ALTERTABLE
64001
64002
64003 /*
64004 ** This function is used by SQL generated to implement the 
64005 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
64006 ** CREATE INDEX command. The second is a table name. The table name in 
64007 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
64008 ** argument and the result returned. Examples:
64009 **
64010 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
64011 **     -> 'CREATE TABLE def(a, b, c)'
64012 **
64013 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
64014 **     -> 'CREATE INDEX i ON def(a, b, c)'
64015 */
64016 static void renameTableFunc(
64017   sqlite3_context *context,
64018   int NotUsed,
64019   sqlite3_value **argv
64020 ){
64021   unsigned char const *zSql = sqlite3_value_text(argv[0]);
64022   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
64023
64024   int token;
64025   Token tname;
64026   unsigned char const *zCsr = zSql;
64027   int len = 0;
64028   char *zRet;
64029
64030   sqlite3 *db = sqlite3_context_db_handle(context);
64031
64032   UNUSED_PARAMETER(NotUsed);
64033
64034   /* The principle used to locate the table name in the CREATE TABLE 
64035   ** statement is that the table name is the first non-space token that
64036   ** is immediately followed by a TK_LP or TK_USING token.
64037   */
64038   if( zSql ){
64039     do {
64040       if( !*zCsr ){
64041         /* Ran out of input before finding an opening bracket. Return NULL. */
64042         return;
64043       }
64044
64045       /* Store the token that zCsr points to in tname. */
64046       tname.z = (char*)zCsr;
64047       tname.n = len;
64048
64049       /* Advance zCsr to the next token. Store that token type in 'token',
64050       ** and its length in 'len' (to be used next iteration of this loop).
64051       */
64052       do {
64053         zCsr += len;
64054         len = sqlite3GetToken(zCsr, &token);
64055       } while( token==TK_SPACE );
64056       assert( len>0 );
64057     } while( token!=TK_LP && token!=TK_USING );
64058
64059     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
64060        zTableName, tname.z+tname.n);
64061     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
64062   }
64063 }
64064
64065 /*
64066 ** This C function implements an SQL user function that is used by SQL code
64067 ** generated by the ALTER TABLE ... RENAME command to modify the definition
64068 ** of any foreign key constraints that use the table being renamed as the 
64069 ** parent table. It is passed three arguments:
64070 **
64071 **   1) The complete text of the CREATE TABLE statement being modified,
64072 **   2) The old name of the table being renamed, and
64073 **   3) The new name of the table being renamed.
64074 **
64075 ** It returns the new CREATE TABLE statement. For example:
64076 **
64077 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
64078 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
64079 */
64080 #ifndef SQLITE_OMIT_FOREIGN_KEY
64081 static void renameParentFunc(
64082   sqlite3_context *context,
64083   int NotUsed,
64084   sqlite3_value **argv
64085 ){
64086   sqlite3 *db = sqlite3_context_db_handle(context);
64087   char *zOutput = 0;
64088   char *zResult;
64089   unsigned char const *zInput = sqlite3_value_text(argv[0]);
64090   unsigned char const *zOld = sqlite3_value_text(argv[1]);
64091   unsigned char const *zNew = sqlite3_value_text(argv[2]);
64092
64093   unsigned const char *z;         /* Pointer to token */
64094   int n;                          /* Length of token z */
64095   int token;                      /* Type of token */
64096
64097   UNUSED_PARAMETER(NotUsed);
64098   for(z=zInput; *z; z=z+n){
64099     n = sqlite3GetToken(z, &token);
64100     if( token==TK_REFERENCES ){
64101       char *zParent;
64102       do {
64103         z += n;
64104         n = sqlite3GetToken(z, &token);
64105       }while( token==TK_SPACE );
64106
64107       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
64108       if( zParent==0 ) break;
64109       sqlite3Dequote(zParent);
64110       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
64111         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
64112             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
64113         );
64114         sqlite3DbFree(db, zOutput);
64115         zOutput = zOut;
64116         zInput = &z[n];
64117       }
64118       sqlite3DbFree(db, zParent);
64119     }
64120   }
64121
64122   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
64123   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
64124   sqlite3DbFree(db, zOutput);
64125 }
64126 #endif
64127
64128 #ifndef SQLITE_OMIT_TRIGGER
64129 /* This function is used by SQL generated to implement the
64130 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
64131 ** statement. The second is a table name. The table name in the CREATE 
64132 ** TRIGGER statement is replaced with the third argument and the result 
64133 ** returned. This is analagous to renameTableFunc() above, except for CREATE
64134 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
64135 */
64136 static void renameTriggerFunc(
64137   sqlite3_context *context,
64138   int NotUsed,
64139   sqlite3_value **argv
64140 ){
64141   unsigned char const *zSql = sqlite3_value_text(argv[0]);
64142   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
64143
64144   int token;
64145   Token tname;
64146   int dist = 3;
64147   unsigned char const *zCsr = zSql;
64148   int len = 0;
64149   char *zRet;
64150   sqlite3 *db = sqlite3_context_db_handle(context);
64151
64152   UNUSED_PARAMETER(NotUsed);
64153
64154   /* The principle used to locate the table name in the CREATE TRIGGER 
64155   ** statement is that the table name is the first token that is immediatedly
64156   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
64157   ** of TK_WHEN, TK_BEGIN or TK_FOR.
64158   */
64159   if( zSql ){
64160     do {
64161
64162       if( !*zCsr ){
64163         /* Ran out of input before finding the table name. Return NULL. */
64164         return;
64165       }
64166
64167       /* Store the token that zCsr points to in tname. */
64168       tname.z = (char*)zCsr;
64169       tname.n = len;
64170
64171       /* Advance zCsr to the next token. Store that token type in 'token',
64172       ** and its length in 'len' (to be used next iteration of this loop).
64173       */
64174       do {
64175         zCsr += len;
64176         len = sqlite3GetToken(zCsr, &token);
64177       }while( token==TK_SPACE );
64178       assert( len>0 );
64179
64180       /* Variable 'dist' stores the number of tokens read since the most
64181       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
64182       ** token is read and 'dist' equals 2, the condition stated above
64183       ** to be met.
64184       **
64185       ** Note that ON cannot be a database, table or column name, so
64186       ** there is no need to worry about syntax like 
64187       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
64188       */
64189       dist++;
64190       if( token==TK_DOT || token==TK_ON ){
64191         dist = 0;
64192       }
64193     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
64194
64195     /* Variable tname now contains the token that is the old table-name
64196     ** in the CREATE TRIGGER statement.
64197     */
64198     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
64199        zTableName, tname.z+tname.n);
64200     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
64201   }
64202 }
64203 #endif   /* !SQLITE_OMIT_TRIGGER */
64204
64205 /*
64206 ** Register built-in functions used to help implement ALTER TABLE
64207 */
64208 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
64209   sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
64210                          renameTableFunc, 0, 0);
64211 #ifndef SQLITE_OMIT_TRIGGER
64212   sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
64213                          renameTriggerFunc, 0, 0);
64214 #endif
64215 #ifndef SQLITE_OMIT_FOREIGN_KEY
64216   sqlite3CreateFunc(db, "sqlite_rename_parent", 3, SQLITE_UTF8, 0,
64217                          renameParentFunc, 0, 0);
64218 #endif
64219 }
64220
64221 /*
64222 ** This function is used to create the text of expressions of the form:
64223 **
64224 **   name=<constant1> OR name=<constant2> OR ...
64225 **
64226 ** If argument zWhere is NULL, then a pointer string containing the text 
64227 ** "name=<constant>" is returned, where <constant> is the quoted version
64228 ** of the string passed as argument zConstant. The returned buffer is
64229 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
64230 ** caller to ensure that it is eventually freed.
64231 **
64232 ** If argument zWhere is not NULL, then the string returned is 
64233 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
64234 ** In this case zWhere is passed to sqlite3DbFree() before returning.
64235 ** 
64236 */
64237 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
64238   char *zNew;
64239   if( !zWhere ){
64240     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
64241   }else{
64242     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
64243     sqlite3DbFree(db, zWhere);
64244   }
64245   return zNew;
64246 }
64247
64248 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
64249 /*
64250 ** Generate the text of a WHERE expression which can be used to select all
64251 ** tables that have foreign key constraints that refer to table pTab (i.e.
64252 ** constraints for which pTab is the parent table) from the sqlite_master
64253 ** table.
64254 */
64255 static char *whereForeignKeys(Parse *pParse, Table *pTab){
64256   FKey *p;
64257   char *zWhere = 0;
64258   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
64259     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
64260   }
64261   return zWhere;
64262 }
64263 #endif
64264
64265 /*
64266 ** Generate the text of a WHERE expression which can be used to select all
64267 ** temporary triggers on table pTab from the sqlite_temp_master table. If
64268 ** table pTab has no temporary triggers, or is itself stored in the 
64269 ** temporary database, NULL is returned.
64270 */
64271 static char *whereTempTriggers(Parse *pParse, Table *pTab){
64272   Trigger *pTrig;
64273   char *zWhere = 0;
64274   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
64275
64276   /* If the table is not located in the temp-db (in which case NULL is 
64277   ** returned, loop through the tables list of triggers. For each trigger
64278   ** that is not part of the temp-db schema, add a clause to the WHERE 
64279   ** expression being built up in zWhere.
64280   */
64281   if( pTab->pSchema!=pTempSchema ){
64282     sqlite3 *db = pParse->db;
64283     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
64284       if( pTrig->pSchema==pTempSchema ){
64285         zWhere = whereOrName(db, zWhere, pTrig->zName);
64286       }
64287     }
64288   }
64289   return zWhere;
64290 }
64291
64292 /*
64293 ** Generate code to drop and reload the internal representation of table
64294 ** pTab from the database, including triggers and temporary triggers.
64295 ** Argument zName is the name of the table in the database schema at
64296 ** the time the generated code is executed. This can be different from
64297 ** pTab->zName if this function is being called to code part of an 
64298 ** "ALTER TABLE RENAME TO" statement.
64299 */
64300 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
64301   Vdbe *v;
64302   char *zWhere;
64303   int iDb;                   /* Index of database containing pTab */
64304 #ifndef SQLITE_OMIT_TRIGGER
64305   Trigger *pTrig;
64306 #endif
64307
64308   v = sqlite3GetVdbe(pParse);
64309   if( NEVER(v==0) ) return;
64310   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
64311   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
64312   assert( iDb>=0 );
64313
64314 #ifndef SQLITE_OMIT_TRIGGER
64315   /* Drop any table triggers from the internal schema. */
64316   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
64317     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
64318     assert( iTrigDb==iDb || iTrigDb==1 );
64319     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
64320   }
64321 #endif
64322
64323   /* Drop the table and index from the internal schema.  */
64324   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
64325
64326   /* Reload the table, index and permanent trigger schemas. */
64327   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
64328   if( !zWhere ) return;
64329   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
64330
64331 #ifndef SQLITE_OMIT_TRIGGER
64332   /* Now, if the table is not stored in the temp database, reload any temp 
64333   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
64334   */
64335   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
64336     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
64337   }
64338 #endif
64339 }
64340
64341 /*
64342 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
64343 ** command. 
64344 */
64345 SQLITE_PRIVATE void sqlite3AlterRenameTable(
64346   Parse *pParse,            /* Parser context. */
64347   SrcList *pSrc,            /* The table to rename. */
64348   Token *pName              /* The new table name. */
64349 ){
64350   int iDb;                  /* Database that contains the table */
64351   char *zDb;                /* Name of database iDb */
64352   Table *pTab;              /* Table being renamed */
64353   char *zName = 0;          /* NULL-terminated version of pName */ 
64354   sqlite3 *db = pParse->db; /* Database connection */
64355   int nTabName;             /* Number of UTF-8 characters in zTabName */
64356   const char *zTabName;     /* Original name of the table */
64357   Vdbe *v;
64358 #ifndef SQLITE_OMIT_TRIGGER
64359   char *zWhere = 0;         /* Where clause to locate temp triggers */
64360 #endif
64361   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
64362   
64363   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
64364   assert( pSrc->nSrc==1 );
64365   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
64366
64367   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
64368   if( !pTab ) goto exit_rename_table;
64369   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
64370   zDb = db->aDb[iDb].zName;
64371
64372   /* Get a NULL terminated version of the new table name. */
64373   zName = sqlite3NameFromToken(db, pName);
64374   if( !zName ) goto exit_rename_table;
64375
64376   /* Check that a table or index named 'zName' does not already exist
64377   ** in database iDb. If so, this is an error.
64378   */
64379   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
64380     sqlite3ErrorMsg(pParse, 
64381         "there is already another table or index with this name: %s", zName);
64382     goto exit_rename_table;
64383   }
64384
64385   /* Make sure it is not a system table being altered, or a reserved name
64386   ** that the table is being renamed to.
64387   */
64388   if( sqlite3Strlen30(pTab->zName)>6 
64389    && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
64390   ){
64391     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
64392     goto exit_rename_table;
64393   }
64394   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
64395     goto exit_rename_table;
64396   }
64397
64398 #ifndef SQLITE_OMIT_VIEW
64399   if( pTab->pSelect ){
64400     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
64401     goto exit_rename_table;
64402   }
64403 #endif
64404
64405 #ifndef SQLITE_OMIT_AUTHORIZATION
64406   /* Invoke the authorization callback. */
64407   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
64408     goto exit_rename_table;
64409   }
64410 #endif
64411
64412 #ifndef SQLITE_OMIT_VIRTUALTABLE
64413   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
64414     goto exit_rename_table;
64415   }
64416   if( IsVirtual(pTab) ){
64417     pVTab = sqlite3GetVTable(db, pTab);
64418     if( pVTab->pVtab->pModule->xRename==0 ){
64419       pVTab = 0;
64420     }
64421   }
64422 #endif
64423
64424   /* Begin a transaction and code the VerifyCookie for database iDb. 
64425   ** Then modify the schema cookie (since the ALTER TABLE modifies the
64426   ** schema). Open a statement transaction if the table is a virtual
64427   ** table.
64428   */
64429   v = sqlite3GetVdbe(pParse);
64430   if( v==0 ){
64431     goto exit_rename_table;
64432   }
64433   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
64434   sqlite3ChangeCookie(pParse, iDb);
64435
64436   /* If this is a virtual table, invoke the xRename() function if
64437   ** one is defined. The xRename() callback will modify the names
64438   ** of any resources used by the v-table implementation (including other
64439   ** SQLite tables) that are identified by the name of the virtual table.
64440   */
64441 #ifndef SQLITE_OMIT_VIRTUALTABLE
64442   if( pVTab ){
64443     int i = ++pParse->nMem;
64444     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
64445     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
64446     sqlite3MayAbort(pParse);
64447   }
64448 #endif
64449
64450   /* figure out how many UTF-8 characters are in zName */
64451   zTabName = pTab->zName;
64452   nTabName = sqlite3Utf8CharLen(zTabName, -1);
64453
64454 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
64455   if( db->flags&SQLITE_ForeignKeys ){
64456     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
64457     ** statements corresponding to all child tables of foreign key constraints
64458     ** for which the renamed table is the parent table.  */
64459     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
64460       sqlite3NestedParse(pParse, 
64461           "UPDATE sqlite_master SET "
64462               "sql = sqlite_rename_parent(sql, %Q, %Q) "
64463               "WHERE %s;", zTabName, zName, zWhere);
64464       sqlite3DbFree(db, zWhere);
64465     }
64466   }
64467 #endif
64468
64469   /* Modify the sqlite_master table to use the new table name. */
64470   sqlite3NestedParse(pParse,
64471       "UPDATE %Q.%s SET "
64472 #ifdef SQLITE_OMIT_TRIGGER
64473           "sql = sqlite_rename_table(sql, %Q), "
64474 #else
64475           "sql = CASE "
64476             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
64477             "ELSE sqlite_rename_table(sql, %Q) END, "
64478 #endif
64479           "tbl_name = %Q, "
64480           "name = CASE "
64481             "WHEN type='table' THEN %Q "
64482             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
64483              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
64484             "ELSE name END "
64485       "WHERE tbl_name=%Q AND "
64486           "(type='table' OR type='index' OR type='trigger');", 
64487       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
64488 #ifndef SQLITE_OMIT_TRIGGER
64489       zName,
64490 #endif
64491       zName, nTabName, zTabName
64492   );
64493
64494 #ifndef SQLITE_OMIT_AUTOINCREMENT
64495   /* If the sqlite_sequence table exists in this database, then update 
64496   ** it with the new table name.
64497   */
64498   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
64499     sqlite3NestedParse(pParse,
64500         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
64501         zDb, zName, pTab->zName);
64502   }
64503 #endif
64504
64505 #ifndef SQLITE_OMIT_TRIGGER
64506   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
64507   ** table. Don't do this if the table being ALTERed is itself located in
64508   ** the temp database.
64509   */
64510   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
64511     sqlite3NestedParse(pParse, 
64512         "UPDATE sqlite_temp_master SET "
64513             "sql = sqlite_rename_trigger(sql, %Q), "
64514             "tbl_name = %Q "
64515             "WHERE %s;", zName, zName, zWhere);
64516     sqlite3DbFree(db, zWhere);
64517   }
64518 #endif
64519
64520 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
64521   if( db->flags&SQLITE_ForeignKeys ){
64522     FKey *p;
64523     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
64524       Table *pFrom = p->pFrom;
64525       if( pFrom!=pTab ){
64526         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
64527       }
64528     }
64529   }
64530 #endif
64531
64532   /* Drop and reload the internal table schema. */
64533   reloadTableSchema(pParse, pTab, zName);
64534
64535 exit_rename_table:
64536   sqlite3SrcListDelete(db, pSrc);
64537   sqlite3DbFree(db, zName);
64538 }
64539
64540
64541 /*
64542 ** Generate code to make sure the file format number is at least minFormat.
64543 ** The generated code will increase the file format number if necessary.
64544 */
64545 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
64546   Vdbe *v;
64547   v = sqlite3GetVdbe(pParse);
64548   /* The VDBE should have been allocated before this routine is called.
64549   ** If that allocation failed, we would have quit before reaching this
64550   ** point */
64551   if( ALWAYS(v) ){
64552     int r1 = sqlite3GetTempReg(pParse);
64553     int r2 = sqlite3GetTempReg(pParse);
64554     int j1;
64555     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
64556     sqlite3VdbeUsesBtree(v, iDb);
64557     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
64558     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
64559     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
64560     sqlite3VdbeJumpHere(v, j1);
64561     sqlite3ReleaseTempReg(pParse, r1);
64562     sqlite3ReleaseTempReg(pParse, r2);
64563   }
64564 }
64565
64566 /*
64567 ** This function is called after an "ALTER TABLE ... ADD" statement
64568 ** has been parsed. Argument pColDef contains the text of the new
64569 ** column definition.
64570 **
64571 ** The Table structure pParse->pNewTable was extended to include
64572 ** the new column during parsing.
64573 */
64574 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
64575   Table *pNew;              /* Copy of pParse->pNewTable */
64576   Table *pTab;              /* Table being altered */
64577   int iDb;                  /* Database number */
64578   const char *zDb;          /* Database name */
64579   const char *zTab;         /* Table name */
64580   char *zCol;               /* Null-terminated column definition */
64581   Column *pCol;             /* The new column */
64582   Expr *pDflt;              /* Default value for the new column */
64583   sqlite3 *db;              /* The database connection; */
64584
64585   db = pParse->db;
64586   if( pParse->nErr || db->mallocFailed ) return;
64587   pNew = pParse->pNewTable;
64588   assert( pNew );
64589
64590   assert( sqlite3BtreeHoldsAllMutexes(db) );
64591   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
64592   zDb = db->aDb[iDb].zName;
64593   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
64594   pCol = &pNew->aCol[pNew->nCol-1];
64595   pDflt = pCol->pDflt;
64596   pTab = sqlite3FindTable(db, zTab, zDb);
64597   assert( pTab );
64598
64599 #ifndef SQLITE_OMIT_AUTHORIZATION
64600   /* Invoke the authorization callback. */
64601   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
64602     return;
64603   }
64604 #endif
64605
64606   /* If the default value for the new column was specified with a 
64607   ** literal NULL, then set pDflt to 0. This simplifies checking
64608   ** for an SQL NULL default below.
64609   */
64610   if( pDflt && pDflt->op==TK_NULL ){
64611     pDflt = 0;
64612   }
64613
64614   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
64615   ** If there is a NOT NULL constraint, then the default value for the
64616   ** column must not be NULL.
64617   */
64618   if( pCol->isPrimKey ){
64619     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
64620     return;
64621   }
64622   if( pNew->pIndex ){
64623     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
64624     return;
64625   }
64626   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
64627     sqlite3ErrorMsg(pParse, 
64628         "Cannot add a REFERENCES column with non-NULL default value");
64629     return;
64630   }
64631   if( pCol->notNull && !pDflt ){
64632     sqlite3ErrorMsg(pParse, 
64633         "Cannot add a NOT NULL column with default value NULL");
64634     return;
64635   }
64636
64637   /* Ensure the default expression is something that sqlite3ValueFromExpr()
64638   ** can handle (i.e. not CURRENT_TIME etc.)
64639   */
64640   if( pDflt ){
64641     sqlite3_value *pVal;
64642     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
64643       db->mallocFailed = 1;
64644       return;
64645     }
64646     if( !pVal ){
64647       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
64648       return;
64649     }
64650     sqlite3ValueFree(pVal);
64651   }
64652
64653   /* Modify the CREATE TABLE statement. */
64654   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
64655   if( zCol ){
64656     char *zEnd = &zCol[pColDef->n-1];
64657     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
64658       *zEnd-- = '\0';
64659     }
64660     sqlite3NestedParse(pParse, 
64661         "UPDATE \"%w\".%s SET "
64662           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
64663         "WHERE type = 'table' AND name = %Q", 
64664       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
64665       zTab
64666     );
64667     sqlite3DbFree(db, zCol);
64668   }
64669
64670   /* If the default value of the new column is NULL, then set the file
64671   ** format to 2. If the default value of the new column is not NULL,
64672   ** the file format becomes 3.
64673   */
64674   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
64675
64676   /* Reload the schema of the modified table. */
64677   reloadTableSchema(pParse, pTab, pTab->zName);
64678 }
64679
64680 /*
64681 ** This function is called by the parser after the table-name in
64682 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
64683 ** pSrc is the full-name of the table being altered.
64684 **
64685 ** This routine makes a (partial) copy of the Table structure
64686 ** for the table being altered and sets Parse.pNewTable to point
64687 ** to it. Routines called by the parser as the column definition
64688 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
64689 ** the copy. The copy of the Table structure is deleted by tokenize.c 
64690 ** after parsing is finished.
64691 **
64692 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
64693 ** coding the "ALTER TABLE ... ADD" statement.
64694 */
64695 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
64696   Table *pNew;
64697   Table *pTab;
64698   Vdbe *v;
64699   int iDb;
64700   int i;
64701   int nAlloc;
64702   sqlite3 *db = pParse->db;
64703
64704   /* Look up the table being altered. */
64705   assert( pParse->pNewTable==0 );
64706   assert( sqlite3BtreeHoldsAllMutexes(db) );
64707   if( db->mallocFailed ) goto exit_begin_add_column;
64708   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
64709   if( !pTab ) goto exit_begin_add_column;
64710
64711 #ifndef SQLITE_OMIT_VIRTUALTABLE
64712   if( IsVirtual(pTab) ){
64713     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
64714     goto exit_begin_add_column;
64715   }
64716 #endif
64717
64718   /* Make sure this is not an attempt to ALTER a view. */
64719   if( pTab->pSelect ){
64720     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
64721     goto exit_begin_add_column;
64722   }
64723
64724   assert( pTab->addColOffset>0 );
64725   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
64726
64727   /* Put a copy of the Table struct in Parse.pNewTable for the
64728   ** sqlite3AddColumn() function and friends to modify.  But modify
64729   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
64730   ** prefix, we insure that the name will not collide with an existing
64731   ** table because user table are not allowed to have the "sqlite_"
64732   ** prefix on their name.
64733   */
64734   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
64735   if( !pNew ) goto exit_begin_add_column;
64736   pParse->pNewTable = pNew;
64737   pNew->nRef = 1;
64738   pNew->dbMem = pTab->dbMem;
64739   pNew->nCol = pTab->nCol;
64740   assert( pNew->nCol>0 );
64741   nAlloc = (((pNew->nCol-1)/8)*8)+8;
64742   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
64743   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
64744   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
64745   if( !pNew->aCol || !pNew->zName ){
64746     db->mallocFailed = 1;
64747     goto exit_begin_add_column;
64748   }
64749   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
64750   for(i=0; i<pNew->nCol; i++){
64751     Column *pCol = &pNew->aCol[i];
64752     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
64753     pCol->zColl = 0;
64754     pCol->zType = 0;
64755     pCol->pDflt = 0;
64756     pCol->zDflt = 0;
64757   }
64758   pNew->pSchema = db->aDb[iDb].pSchema;
64759   pNew->addColOffset = pTab->addColOffset;
64760   pNew->nRef = 1;
64761
64762   /* Begin a transaction and increment the schema cookie.  */
64763   sqlite3BeginWriteOperation(pParse, 0, iDb);
64764   v = sqlite3GetVdbe(pParse);
64765   if( !v ) goto exit_begin_add_column;
64766   sqlite3ChangeCookie(pParse, iDb);
64767
64768 exit_begin_add_column:
64769   sqlite3SrcListDelete(db, pSrc);
64770   return;
64771 }
64772 #endif  /* SQLITE_ALTER_TABLE */
64773
64774 /************** End of alter.c ***********************************************/
64775 /************** Begin file analyze.c *****************************************/
64776 /*
64777 ** 2005 July 8
64778 **
64779 ** The author disclaims copyright to this source code.  In place of
64780 ** a legal notice, here is a blessing:
64781 **
64782 **    May you do good and not evil.
64783 **    May you find forgiveness for yourself and forgive others.
64784 **    May you share freely, never taking more than you give.
64785 **
64786 *************************************************************************
64787 ** This file contains code associated with the ANALYZE command.
64788 */
64789 #ifndef SQLITE_OMIT_ANALYZE
64790
64791 /*
64792 ** This routine generates code that opens the sqlite_stat1 table for
64793 ** writing with cursor iStatCur. If the library was built with the
64794 ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
64795 ** opened for writing using cursor (iStatCur+1)
64796 **
64797 ** If the sqlite_stat1 tables does not previously exist, it is created.
64798 ** Similarly, if the sqlite_stat2 table does not exist and the library
64799 ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created. 
64800 **
64801 ** Argument zWhere may be a pointer to a buffer containing a table name,
64802 ** or it may be a NULL pointer. If it is not NULL, then all entries in
64803 ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
64804 ** with the named table are deleted. If zWhere==0, then code is generated
64805 ** to delete all stat table entries.
64806 */
64807 static void openStatTable(
64808   Parse *pParse,          /* Parsing context */
64809   int iDb,                /* The database we are looking in */
64810   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
64811   const char *zWhere      /* Delete entries associated with this table */
64812 ){
64813   static struct {
64814     const char *zName;
64815     const char *zCols;
64816   } aTable[] = {
64817     { "sqlite_stat1", "tbl,idx,stat" },
64818 #ifdef SQLITE_ENABLE_STAT2
64819     { "sqlite_stat2", "tbl,idx,sampleno,sample" },
64820 #endif
64821   };
64822
64823   int aRoot[] = {0, 0};
64824   u8 aCreateTbl[] = {0, 0};
64825
64826   int i;
64827   sqlite3 *db = pParse->db;
64828   Db *pDb;
64829   Vdbe *v = sqlite3GetVdbe(pParse);
64830   if( v==0 ) return;
64831   assert( sqlite3BtreeHoldsAllMutexes(db) );
64832   assert( sqlite3VdbeDb(v)==db );
64833   pDb = &db->aDb[iDb];
64834
64835   for(i=0; i<ArraySize(aTable); i++){
64836     const char *zTab = aTable[i].zName;
64837     Table *pStat;
64838     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
64839       /* The sqlite_stat[12] table does not exist. Create it. Note that a 
64840       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
64841       ** of the new table in register pParse->regRoot. This is important 
64842       ** because the OpenWrite opcode below will be needing it. */
64843       sqlite3NestedParse(pParse,
64844           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
64845       );
64846       aRoot[i] = pParse->regRoot;
64847       aCreateTbl[i] = 1;
64848     }else{
64849       /* The table already exists. If zWhere is not NULL, delete all entries 
64850       ** associated with the table zWhere. If zWhere is NULL, delete the
64851       ** entire contents of the table. */
64852       aRoot[i] = pStat->tnum;
64853       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
64854       if( zWhere ){
64855         sqlite3NestedParse(pParse,
64856            "DELETE FROM %Q.%s WHERE tbl=%Q", pDb->zName, zTab, zWhere
64857         );
64858       }else{
64859         /* The sqlite_stat[12] table already exists.  Delete all rows. */
64860         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
64861       }
64862     }
64863   }
64864
64865   /* Open the sqlite_stat[12] tables for writing. */
64866   for(i=0; i<ArraySize(aTable); i++){
64867     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
64868     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
64869     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
64870   }
64871 }
64872
64873 /*
64874 ** Generate code to do an analysis of all indices associated with
64875 ** a single table.
64876 */
64877 static void analyzeOneTable(
64878   Parse *pParse,   /* Parser context */
64879   Table *pTab,     /* Table whose indices are to be analyzed */
64880   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
64881   int iMem         /* Available memory locations begin here */
64882 ){
64883   sqlite3 *db = pParse->db;    /* Database handle */
64884   Index *pIdx;                 /* An index to being analyzed */
64885   int iIdxCur;                 /* Cursor open on index being analyzed */
64886   Vdbe *v;                     /* The virtual machine being built up */
64887   int i;                       /* Loop counter */
64888   int topOfLoop;               /* The top of the loop */
64889   int endOfLoop;               /* The end of the loop */
64890   int addr;                    /* The address of an instruction */
64891   int iDb;                     /* Index of database containing pTab */
64892   int regTabname = iMem++;     /* Register containing table name */
64893   int regIdxname = iMem++;     /* Register containing index name */
64894   int regSampleno = iMem++;    /* Register containing next sample number */
64895   int regCol = iMem++;         /* Content of a column analyzed table */
64896   int regRec = iMem++;         /* Register holding completed record */
64897   int regTemp = iMem++;        /* Temporary use register */
64898   int regRowid = iMem++;       /* Rowid for the inserted record */
64899
64900 #ifdef SQLITE_ENABLE_STAT2
64901   int regTemp2 = iMem++;       /* Temporary use register */
64902   int regSamplerecno = iMem++; /* Index of next sample to record */
64903   int regRecno = iMem++;       /* Current sample index */
64904   int regLast = iMem++;        /* Index of last sample to record */
64905   int regFirst = iMem++;       /* Index of first sample to record */
64906 #endif
64907
64908   v = sqlite3GetVdbe(pParse);
64909   if( v==0 || NEVER(pTab==0) || pTab->pIndex==0 ){
64910     /* Do no analysis for tables that have no indices */
64911     return;
64912   }
64913   assert( sqlite3BtreeHoldsAllMutexes(db) );
64914   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
64915   assert( iDb>=0 );
64916 #ifndef SQLITE_OMIT_AUTHORIZATION
64917   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
64918       db->aDb[iDb].zName ) ){
64919     return;
64920   }
64921 #endif
64922
64923   /* Establish a read-lock on the table at the shared-cache level. */
64924   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
64925
64926   iIdxCur = pParse->nTab++;
64927   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
64928     int nCol = pIdx->nColumn;
64929     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
64930
64931     if( iMem+1+(nCol*2)>pParse->nMem ){
64932       pParse->nMem = iMem+1+(nCol*2);
64933     }
64934
64935     /* Open a cursor to the index to be analyzed. */
64936     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
64937     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
64938         (char *)pKey, P4_KEYINFO_HANDOFF);
64939     VdbeComment((v, "%s", pIdx->zName));
64940
64941     /* Populate the registers containing the table and index names. */
64942     if( pTab->pIndex==pIdx ){
64943       sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
64944     }
64945     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
64946
64947 #ifdef SQLITE_ENABLE_STAT2
64948
64949     /* If this iteration of the loop is generating code to analyze the
64950     ** first index in the pTab->pIndex list, then register regLast has
64951     ** not been populated. In this case populate it now.  */
64952     if( pTab->pIndex==pIdx ){
64953       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
64954       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
64955       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
64956
64957       sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
64958       sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
64959       addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
64960       sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
64961       sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
64962       sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
64963       sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
64964       sqlite3VdbeJumpHere(v, addr);
64965     }
64966
64967     /* Zero the regSampleno and regRecno registers. */
64968     sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
64969     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
64970     sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
64971 #endif
64972
64973     /* The block of memory cells initialized here is used as follows.
64974     **
64975     **    iMem:                
64976     **        The total number of rows in the table.
64977     **
64978     **    iMem+1 .. iMem+nCol: 
64979     **        Number of distinct entries in index considering the 
64980     **        left-most N columns only, where N is between 1 and nCol, 
64981     **        inclusive.
64982     **
64983     **    iMem+nCol+1 .. Mem+2*nCol:  
64984     **        Previous value of indexed columns, from left to right.
64985     **
64986     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
64987     ** initialized to contain an SQL NULL.
64988     */
64989     for(i=0; i<=nCol; i++){
64990       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
64991     }
64992     for(i=0; i<nCol; i++){
64993       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
64994     }
64995
64996     /* Start the analysis loop. This loop runs through all the entries in
64997     ** the index b-tree.  */
64998     endOfLoop = sqlite3VdbeMakeLabel(v);
64999     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
65000     topOfLoop = sqlite3VdbeCurrentAddr(v);
65001     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
65002
65003     for(i=0; i<nCol; i++){
65004       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
65005 #ifdef SQLITE_ENABLE_STAT2
65006       if( i==0 ){
65007         /* Check if the record that cursor iIdxCur points to contains a
65008         ** value that should be stored in the sqlite_stat2 table. If so,
65009         ** store it.  */
65010         int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
65011         assert( regTabname+1==regIdxname 
65012              && regTabname+2==regSampleno
65013              && regTabname+3==regCol
65014         );
65015         sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
65016         sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
65017         sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
65018         sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
65019
65020         /* Calculate new values for regSamplerecno and regSampleno.
65021         **
65022         **   sampleno = sampleno + 1
65023         **   samplerecno = samplerecno+(remaining records)/(remaining samples)
65024         */
65025         sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
65026         sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
65027         sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
65028         sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
65029         sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
65030         sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
65031         sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
65032
65033         sqlite3VdbeJumpHere(v, ne);
65034         sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
65035       }
65036 #endif
65037
65038       sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
65039       /**** TODO:  add collating sequence *****/
65040       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
65041     }
65042     if( db->mallocFailed ){
65043       /* If a malloc failure has occurred, then the result of the expression 
65044       ** passed as the second argument to the call to sqlite3VdbeJumpHere() 
65045       ** below may be negative. Which causes an assert() to fail (or an
65046       ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
65047       return;
65048     }
65049     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
65050     for(i=0; i<nCol; i++){
65051       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-(nCol*2));
65052       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
65053       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
65054     }
65055
65056     /* End of the analysis loop. */
65057     sqlite3VdbeResolveLabel(v, endOfLoop);
65058     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
65059     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
65060
65061     /* Store the results in sqlite_stat1.
65062     **
65063     ** The result is a single row of the sqlite_stat1 table.  The first
65064     ** two columns are the names of the table and index.  The third column
65065     ** is a string composed of a list of integer statistics about the
65066     ** index.  The first integer in the list is the total number of entries
65067     ** in the index.  There is one additional integer in the list for each
65068     ** column of the table.  This additional integer is a guess of how many
65069     ** rows of the table the index will select.  If D is the count of distinct
65070     ** values and K is the total number of rows, then the integer is computed
65071     ** as:
65072     **
65073     **        I = (K+D-1)/D
65074     **
65075     ** If K==0 then no entry is made into the sqlite_stat1 table.  
65076     ** If K>0 then it is always the case the D>0 so division by zero
65077     ** is never possible.
65078     */
65079     addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
65080     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
65081     for(i=0; i<nCol; i++){
65082       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
65083       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
65084       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
65085       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
65086       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
65087       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
65088       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
65089     }
65090     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
65091     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
65092     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
65093     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
65094     sqlite3VdbeJumpHere(v, addr);
65095   }
65096 }
65097
65098 /*
65099 ** Generate code that will cause the most recent index analysis to
65100 ** be laoded into internal hash tables where is can be used.
65101 */
65102 static void loadAnalysis(Parse *pParse, int iDb){
65103   Vdbe *v = sqlite3GetVdbe(pParse);
65104   if( v ){
65105     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
65106   }
65107 }
65108
65109 /*
65110 ** Generate code that will do an analysis of an entire database
65111 */
65112 static void analyzeDatabase(Parse *pParse, int iDb){
65113   sqlite3 *db = pParse->db;
65114   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
65115   HashElem *k;
65116   int iStatCur;
65117   int iMem;
65118
65119   sqlite3BeginWriteOperation(pParse, 0, iDb);
65120   iStatCur = pParse->nTab;
65121   pParse->nTab += 2;
65122   openStatTable(pParse, iDb, iStatCur, 0);
65123   iMem = pParse->nMem+1;
65124   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
65125     Table *pTab = (Table*)sqliteHashData(k);
65126     analyzeOneTable(pParse, pTab, iStatCur, iMem);
65127   }
65128   loadAnalysis(pParse, iDb);
65129 }
65130
65131 /*
65132 ** Generate code that will do an analysis of a single table in
65133 ** a database.
65134 */
65135 static void analyzeTable(Parse *pParse, Table *pTab){
65136   int iDb;
65137   int iStatCur;
65138
65139   assert( pTab!=0 );
65140   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
65141   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
65142   sqlite3BeginWriteOperation(pParse, 0, iDb);
65143   iStatCur = pParse->nTab;
65144   pParse->nTab += 2;
65145   openStatTable(pParse, iDb, iStatCur, pTab->zName);
65146   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
65147   loadAnalysis(pParse, iDb);
65148 }
65149
65150 /*
65151 ** Generate code for the ANALYZE command.  The parser calls this routine
65152 ** when it recognizes an ANALYZE command.
65153 **
65154 **        ANALYZE                            -- 1
65155 **        ANALYZE  <database>                -- 2
65156 **        ANALYZE  ?<database>.?<tablename>  -- 3
65157 **
65158 ** Form 1 causes all indices in all attached databases to be analyzed.
65159 ** Form 2 analyzes all indices the single database named.
65160 ** Form 3 analyzes all indices associated with the named table.
65161 */
65162 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
65163   sqlite3 *db = pParse->db;
65164   int iDb;
65165   int i;
65166   char *z, *zDb;
65167   Table *pTab;
65168   Token *pTableName;
65169
65170   /* Read the database schema. If an error occurs, leave an error message
65171   ** and code in pParse and return NULL. */
65172   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
65173   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
65174     return;
65175   }
65176
65177   assert( pName2!=0 || pName1==0 );
65178   if( pName1==0 ){
65179     /* Form 1:  Analyze everything */
65180     for(i=0; i<db->nDb; i++){
65181       if( i==1 ) continue;  /* Do not analyze the TEMP database */
65182       analyzeDatabase(pParse, i);
65183     }
65184   }else if( pName2->n==0 ){
65185     /* Form 2:  Analyze the database or table named */
65186     iDb = sqlite3FindDb(db, pName1);
65187     if( iDb>=0 ){
65188       analyzeDatabase(pParse, iDb);
65189     }else{
65190       z = sqlite3NameFromToken(db, pName1);
65191       if( z ){
65192         pTab = sqlite3LocateTable(pParse, 0, z, 0);
65193         sqlite3DbFree(db, z);
65194         if( pTab ){
65195           analyzeTable(pParse, pTab);
65196         }
65197       }
65198     }
65199   }else{
65200     /* Form 3: Analyze the fully qualified table name */
65201     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
65202     if( iDb>=0 ){
65203       zDb = db->aDb[iDb].zName;
65204       z = sqlite3NameFromToken(db, pTableName);
65205       if( z ){
65206         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
65207         sqlite3DbFree(db, z);
65208         if( pTab ){
65209           analyzeTable(pParse, pTab);
65210         }
65211       }
65212     }   
65213   }
65214 }
65215
65216 /*
65217 ** Used to pass information from the analyzer reader through to the
65218 ** callback routine.
65219 */
65220 typedef struct analysisInfo analysisInfo;
65221 struct analysisInfo {
65222   sqlite3 *db;
65223   const char *zDatabase;
65224 };
65225
65226 /*
65227 ** This callback is invoked once for each index when reading the
65228 ** sqlite_stat1 table.  
65229 **
65230 **     argv[0] = name of the index
65231 **     argv[1] = results of analysis - on integer for each column
65232 */
65233 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
65234   analysisInfo *pInfo = (analysisInfo*)pData;
65235   Index *pIndex;
65236   int i, c;
65237   unsigned int v;
65238   const char *z;
65239
65240   assert( argc==2 );
65241   UNUSED_PARAMETER2(NotUsed, argc);
65242
65243   if( argv==0 || argv[0]==0 || argv[1]==0 ){
65244     return 0;
65245   }
65246   pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
65247   if( pIndex==0 ){
65248     return 0;
65249   }
65250   z = argv[1];
65251   for(i=0; *z && i<=pIndex->nColumn; i++){
65252     v = 0;
65253     while( (c=z[0])>='0' && c<='9' ){
65254       v = v*10 + c - '0';
65255       z++;
65256     }
65257     pIndex->aiRowEst[i] = v;
65258     if( *z==' ' ) z++;
65259   }
65260   return 0;
65261 }
65262
65263 /*
65264 ** If the Index.aSample variable is not NULL, delete the aSample[] array
65265 ** and its contents.
65266 */
65267 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index *pIdx){
65268 #ifdef SQLITE_ENABLE_STAT2
65269   if( pIdx->aSample ){
65270     int j;
65271     sqlite3 *dbMem = pIdx->pTable->dbMem;
65272     for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
65273       IndexSample *p = &pIdx->aSample[j];
65274       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
65275         sqlite3DbFree(pIdx->pTable->dbMem, p->u.z);
65276       }
65277     }
65278     sqlite3DbFree(dbMem, pIdx->aSample);
65279     pIdx->aSample = 0;
65280   }
65281 #else
65282   UNUSED_PARAMETER(pIdx);
65283 #endif
65284 }
65285
65286 /*
65287 ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
65288 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
65289 ** arrays. The contents of sqlite_stat2 are used to populate the
65290 ** Index.aSample[] arrays.
65291 **
65292 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
65293 ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined 
65294 ** during compilation and the sqlite_stat2 table is present, no data is 
65295 ** read from it.
65296 **
65297 ** If SQLITE_ENABLE_STAT2 was defined during compilation and the 
65298 ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
65299 ** returned. However, in this case, data is read from the sqlite_stat1
65300 ** table (if it is present) before returning.
65301 **
65302 ** If an OOM error occurs, this function always sets db->mallocFailed.
65303 ** This means if the caller does not care about other errors, the return
65304 ** code may be ignored.
65305 */
65306 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
65307   analysisInfo sInfo;
65308   HashElem *i;
65309   char *zSql;
65310   int rc;
65311
65312   assert( iDb>=0 && iDb<db->nDb );
65313   assert( db->aDb[iDb].pBt!=0 );
65314   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
65315
65316   /* Clear any prior statistics */
65317   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
65318     Index *pIdx = sqliteHashData(i);
65319     sqlite3DefaultRowEst(pIdx);
65320     sqlite3DeleteIndexSamples(pIdx);
65321   }
65322
65323   /* Check to make sure the sqlite_stat1 table exists */
65324   sInfo.db = db;
65325   sInfo.zDatabase = db->aDb[iDb].zName;
65326   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
65327     return SQLITE_ERROR;
65328   }
65329
65330   /* Load new statistics out of the sqlite_stat1 table */
65331   zSql = sqlite3MPrintf(db, 
65332       "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
65333   if( zSql==0 ){
65334     rc = SQLITE_NOMEM;
65335   }else{
65336     (void)sqlite3SafetyOff(db);
65337     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
65338     (void)sqlite3SafetyOn(db);
65339     sqlite3DbFree(db, zSql);
65340   }
65341
65342
65343   /* Load the statistics from the sqlite_stat2 table. */
65344 #ifdef SQLITE_ENABLE_STAT2
65345   if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
65346     rc = SQLITE_ERROR;
65347   }
65348   if( rc==SQLITE_OK ){
65349     sqlite3_stmt *pStmt = 0;
65350
65351     zSql = sqlite3MPrintf(db, 
65352         "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
65353     if( !zSql ){
65354       rc = SQLITE_NOMEM;
65355     }else{
65356       (void)sqlite3SafetyOff(db);
65357       rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
65358       (void)sqlite3SafetyOn(db);
65359       sqlite3DbFree(db, zSql);
65360     }
65361
65362     if( rc==SQLITE_OK ){
65363       (void)sqlite3SafetyOff(db);
65364       while( sqlite3_step(pStmt)==SQLITE_ROW ){
65365         char *zIndex = (char *)sqlite3_column_text(pStmt, 0);
65366         Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
65367         if( pIdx ){
65368           int iSample = sqlite3_column_int(pStmt, 1);
65369           sqlite3 *dbMem = pIdx->pTable->dbMem;
65370           assert( dbMem==db || dbMem==0 );
65371           if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
65372             int eType = sqlite3_column_type(pStmt, 2);
65373
65374             if( pIdx->aSample==0 ){
65375               static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
65376               pIdx->aSample = (IndexSample *)sqlite3DbMallocZero(dbMem, sz);
65377               if( pIdx->aSample==0 ){
65378                 db->mallocFailed = 1;
65379                 break;
65380               }
65381             }
65382
65383             assert( pIdx->aSample );
65384             {
65385               IndexSample *pSample = &pIdx->aSample[iSample];
65386               pSample->eType = (u8)eType;
65387               if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
65388                 pSample->u.r = sqlite3_column_double(pStmt, 2);
65389               }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
65390                 const char *z = (const char *)(
65391                     (eType==SQLITE_BLOB) ?
65392                     sqlite3_column_blob(pStmt, 2):
65393                     sqlite3_column_text(pStmt, 2)
65394                 );
65395                 int n = sqlite3_column_bytes(pStmt, 2);
65396                 if( n>24 ){
65397                   n = 24;
65398                 }
65399                 pSample->nByte = (u8)n;
65400                 pSample->u.z = sqlite3DbMallocRaw(dbMem, n);
65401                 if( pSample->u.z ){
65402                   memcpy(pSample->u.z, z, n);
65403                 }else{
65404                   db->mallocFailed = 1;
65405                   break;
65406                 }
65407               }
65408             }
65409           }
65410         }
65411       }
65412       rc = sqlite3_finalize(pStmt);
65413       (void)sqlite3SafetyOn(db);
65414     }
65415   }
65416 #endif
65417
65418   if( rc==SQLITE_NOMEM ){
65419     db->mallocFailed = 1;
65420   }
65421   return rc;
65422 }
65423
65424
65425 #endif /* SQLITE_OMIT_ANALYZE */
65426
65427 /************** End of analyze.c *********************************************/
65428 /************** Begin file attach.c ******************************************/
65429 /*
65430 ** 2003 April 6
65431 **
65432 ** The author disclaims copyright to this source code.  In place of
65433 ** a legal notice, here is a blessing:
65434 **
65435 **    May you do good and not evil.
65436 **    May you find forgiveness for yourself and forgive others.
65437 **    May you share freely, never taking more than you give.
65438 **
65439 *************************************************************************
65440 ** This file contains code used to implement the ATTACH and DETACH commands.
65441 */
65442
65443 #ifndef SQLITE_OMIT_ATTACH
65444 /*
65445 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
65446 ** is slightly different from resolving a normal SQL expression, because simple
65447 ** identifiers are treated as strings, not possible column names or aliases.
65448 **
65449 ** i.e. if the parser sees:
65450 **
65451 **     ATTACH DATABASE abc AS def
65452 **
65453 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
65454 ** looking for columns of the same name.
65455 **
65456 ** This only applies to the root node of pExpr, so the statement:
65457 **
65458 **     ATTACH DATABASE abc||def AS 'db2'
65459 **
65460 ** will fail because neither abc or def can be resolved.
65461 */
65462 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
65463 {
65464   int rc = SQLITE_OK;
65465   if( pExpr ){
65466     if( pExpr->op!=TK_ID ){
65467       rc = sqlite3ResolveExprNames(pName, pExpr);
65468       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
65469         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
65470         return SQLITE_ERROR;
65471       }
65472     }else{
65473       pExpr->op = TK_STRING;
65474     }
65475   }
65476   return rc;
65477 }
65478
65479 /*
65480 ** An SQL user-function registered to do the work of an ATTACH statement. The
65481 ** three arguments to the function come directly from an attach statement:
65482 **
65483 **     ATTACH DATABASE x AS y KEY z
65484 **
65485 **     SELECT sqlite_attach(x, y, z)
65486 **
65487 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
65488 ** third argument.
65489 */
65490 static void attachFunc(
65491   sqlite3_context *context,
65492   int NotUsed,
65493   sqlite3_value **argv
65494 ){
65495   int i;
65496   int rc = 0;
65497   sqlite3 *db = sqlite3_context_db_handle(context);
65498   const char *zName;
65499   const char *zFile;
65500   Db *aNew;
65501   char *zErrDyn = 0;
65502
65503   UNUSED_PARAMETER(NotUsed);
65504
65505   zFile = (const char *)sqlite3_value_text(argv[0]);
65506   zName = (const char *)sqlite3_value_text(argv[1]);
65507   if( zFile==0 ) zFile = "";
65508   if( zName==0 ) zName = "";
65509
65510   /* Check for the following errors:
65511   **
65512   **     * Too many attached databases,
65513   **     * Transaction currently open
65514   **     * Specified database name already being used.
65515   */
65516   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
65517     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
65518       db->aLimit[SQLITE_LIMIT_ATTACHED]
65519     );
65520     goto attach_error;
65521   }
65522   if( !db->autoCommit ){
65523     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
65524     goto attach_error;
65525   }
65526   for(i=0; i<db->nDb; i++){
65527     char *z = db->aDb[i].zName;
65528     assert( z && zName );
65529     if( sqlite3StrICmp(z, zName)==0 ){
65530       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
65531       goto attach_error;
65532     }
65533   }
65534
65535   /* Allocate the new entry in the db->aDb[] array and initialise the schema
65536   ** hash tables.
65537   */
65538   if( db->aDb==db->aDbStatic ){
65539     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
65540     if( aNew==0 ) return;
65541     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
65542   }else{
65543     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
65544     if( aNew==0 ) return;
65545   }
65546   db->aDb = aNew;
65547   aNew = &db->aDb[db->nDb];
65548   memset(aNew, 0, sizeof(*aNew));
65549
65550   /* Open the database file. If the btree is successfully opened, use
65551   ** it to obtain the database schema. At this point the schema may
65552   ** or may not be initialised.
65553   */
65554   rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
65555                            db->openFlags | SQLITE_OPEN_MAIN_DB,
65556                            &aNew->pBt);
65557   db->nDb++;
65558   if( rc==SQLITE_CONSTRAINT ){
65559     rc = SQLITE_ERROR;
65560     zErrDyn = sqlite3MPrintf(db, "database is already attached");
65561   }else if( rc==SQLITE_OK ){
65562     Pager *pPager;
65563     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
65564     if( !aNew->pSchema ){
65565       rc = SQLITE_NOMEM;
65566     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
65567       zErrDyn = sqlite3MPrintf(db, 
65568         "attached databases must use the same text encoding as main database");
65569       rc = SQLITE_ERROR;
65570     }
65571     pPager = sqlite3BtreePager(aNew->pBt);
65572     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
65573     sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
65574   }
65575   aNew->zName = sqlite3DbStrDup(db, zName);
65576   aNew->safety_level = 3;
65577
65578 #if SQLITE_HAS_CODEC
65579   if( rc==SQLITE_OK ){
65580     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
65581     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
65582     int nKey;
65583     char *zKey;
65584     int t = sqlite3_value_type(argv[2]);
65585     switch( t ){
65586       case SQLITE_INTEGER:
65587       case SQLITE_FLOAT:
65588         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
65589         rc = SQLITE_ERROR;
65590         break;
65591         
65592       case SQLITE_TEXT:
65593       case SQLITE_BLOB:
65594         nKey = sqlite3_value_bytes(argv[2]);
65595         zKey = (char *)sqlite3_value_blob(argv[2]);
65596         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
65597         break;
65598
65599       case SQLITE_NULL:
65600         /* No key specified.  Use the key from the main database */
65601         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
65602         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
65603         break;
65604     }
65605   }
65606 #endif
65607
65608   /* If the file was opened successfully, read the schema for the new database.
65609   ** If this fails, or if opening the file failed, then close the file and 
65610   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
65611   ** we found it.
65612   */
65613   if( rc==SQLITE_OK ){
65614     (void)sqlite3SafetyOn(db);
65615     sqlite3BtreeEnterAll(db);
65616     rc = sqlite3Init(db, &zErrDyn);
65617     sqlite3BtreeLeaveAll(db);
65618     (void)sqlite3SafetyOff(db);
65619   }
65620   if( rc ){
65621     int iDb = db->nDb - 1;
65622     assert( iDb>=2 );
65623     if( db->aDb[iDb].pBt ){
65624       sqlite3BtreeClose(db->aDb[iDb].pBt);
65625       db->aDb[iDb].pBt = 0;
65626       db->aDb[iDb].pSchema = 0;
65627     }
65628     sqlite3ResetInternalSchema(db, 0);
65629     db->nDb = iDb;
65630     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
65631       db->mallocFailed = 1;
65632       sqlite3DbFree(db, zErrDyn);
65633       zErrDyn = sqlite3MPrintf(db, "out of memory");
65634     }else if( zErrDyn==0 ){
65635       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
65636     }
65637     goto attach_error;
65638   }
65639   
65640   return;
65641
65642 attach_error:
65643   /* Return an error if we get here */
65644   if( zErrDyn ){
65645     sqlite3_result_error(context, zErrDyn, -1);
65646     sqlite3DbFree(db, zErrDyn);
65647   }
65648   if( rc ) sqlite3_result_error_code(context, rc);
65649 }
65650
65651 /*
65652 ** An SQL user-function registered to do the work of an DETACH statement. The
65653 ** three arguments to the function come directly from a detach statement:
65654 **
65655 **     DETACH DATABASE x
65656 **
65657 **     SELECT sqlite_detach(x)
65658 */
65659 static void detachFunc(
65660   sqlite3_context *context,
65661   int NotUsed,
65662   sqlite3_value **argv
65663 ){
65664   const char *zName = (const char *)sqlite3_value_text(argv[0]);
65665   sqlite3 *db = sqlite3_context_db_handle(context);
65666   int i;
65667   Db *pDb = 0;
65668   char zErr[128];
65669
65670   UNUSED_PARAMETER(NotUsed);
65671
65672   if( zName==0 ) zName = "";
65673   for(i=0; i<db->nDb; i++){
65674     pDb = &db->aDb[i];
65675     if( pDb->pBt==0 ) continue;
65676     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
65677   }
65678
65679   if( i>=db->nDb ){
65680     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
65681     goto detach_error;
65682   }
65683   if( i<2 ){
65684     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
65685     goto detach_error;
65686   }
65687   if( !db->autoCommit ){
65688     sqlite3_snprintf(sizeof(zErr), zErr,
65689                      "cannot DETACH database within transaction");
65690     goto detach_error;
65691   }
65692   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
65693     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
65694     goto detach_error;
65695   }
65696
65697   sqlite3BtreeClose(pDb->pBt);
65698   pDb->pBt = 0;
65699   pDb->pSchema = 0;
65700   sqlite3ResetInternalSchema(db, 0);
65701   return;
65702
65703 detach_error:
65704   sqlite3_result_error(context, zErr, -1);
65705 }
65706
65707 /*
65708 ** This procedure generates VDBE code for a single invocation of either the
65709 ** sqlite_detach() or sqlite_attach() SQL user functions.
65710 */
65711 static void codeAttach(
65712   Parse *pParse,       /* The parser context */
65713   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
65714   FuncDef *pFunc,      /* FuncDef wrapper for detachFunc() or attachFunc() */
65715   Expr *pAuthArg,      /* Expression to pass to authorization callback */
65716   Expr *pFilename,     /* Name of database file */
65717   Expr *pDbname,       /* Name of the database to use internally */
65718   Expr *pKey           /* Database key for encryption extension */
65719 ){
65720   int rc;
65721   NameContext sName;
65722   Vdbe *v;
65723   sqlite3* db = pParse->db;
65724   int regArgs;
65725
65726   memset(&sName, 0, sizeof(NameContext));
65727   sName.pParse = pParse;
65728
65729   if( 
65730       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
65731       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
65732       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
65733   ){
65734     pParse->nErr++;
65735     goto attach_end;
65736   }
65737
65738 #ifndef SQLITE_OMIT_AUTHORIZATION
65739   if( pAuthArg ){
65740     char *zAuthArg = pAuthArg->u.zToken;
65741     if( NEVER(zAuthArg==0) ){
65742       goto attach_end;
65743     }
65744     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
65745     if(rc!=SQLITE_OK ){
65746       goto attach_end;
65747     }
65748   }
65749 #endif /* SQLITE_OMIT_AUTHORIZATION */
65750
65751
65752   v = sqlite3GetVdbe(pParse);
65753   regArgs = sqlite3GetTempRange(pParse, 4);
65754   sqlite3ExprCode(pParse, pFilename, regArgs);
65755   sqlite3ExprCode(pParse, pDbname, regArgs+1);
65756   sqlite3ExprCode(pParse, pKey, regArgs+2);
65757
65758   assert( v || db->mallocFailed );
65759   if( v ){
65760     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
65761     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
65762     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
65763     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
65764
65765     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
65766     ** statement only). For DETACH, set it to false (expire all existing
65767     ** statements).
65768     */
65769     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
65770   }
65771   
65772 attach_end:
65773   sqlite3ExprDelete(db, pFilename);
65774   sqlite3ExprDelete(db, pDbname);
65775   sqlite3ExprDelete(db, pKey);
65776 }
65777
65778 /*
65779 ** Called by the parser to compile a DETACH statement.
65780 **
65781 **     DETACH pDbname
65782 */
65783 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
65784   static FuncDef detach_func = {
65785     1,                /* nArg */
65786     SQLITE_UTF8,      /* iPrefEnc */
65787     0,                /* flags */
65788     0,                /* pUserData */
65789     0,                /* pNext */
65790     detachFunc,       /* xFunc */
65791     0,                /* xStep */
65792     0,                /* xFinalize */
65793     "sqlite_detach",  /* zName */
65794     0                 /* pHash */
65795   };
65796   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
65797 }
65798
65799 /*
65800 ** Called by the parser to compile an ATTACH statement.
65801 **
65802 **     ATTACH p AS pDbname KEY pKey
65803 */
65804 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
65805   static FuncDef attach_func = {
65806     3,                /* nArg */
65807     SQLITE_UTF8,      /* iPrefEnc */
65808     0,                /* flags */
65809     0,                /* pUserData */
65810     0,                /* pNext */
65811     attachFunc,       /* xFunc */
65812     0,                /* xStep */
65813     0,                /* xFinalize */
65814     "sqlite_attach",  /* zName */
65815     0                 /* pHash */
65816   };
65817   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
65818 }
65819 #endif /* SQLITE_OMIT_ATTACH */
65820
65821 /*
65822 ** Initialize a DbFixer structure.  This routine must be called prior
65823 ** to passing the structure to one of the sqliteFixAAAA() routines below.
65824 **
65825 ** The return value indicates whether or not fixation is required.  TRUE
65826 ** means we do need to fix the database references, FALSE means we do not.
65827 */
65828 SQLITE_PRIVATE int sqlite3FixInit(
65829   DbFixer *pFix,      /* The fixer to be initialized */
65830   Parse *pParse,      /* Error messages will be written here */
65831   int iDb,            /* This is the database that must be used */
65832   const char *zType,  /* "view", "trigger", or "index" */
65833   const Token *pName  /* Name of the view, trigger, or index */
65834 ){
65835   sqlite3 *db;
65836
65837   if( NEVER(iDb<0) || iDb==1 ) return 0;
65838   db = pParse->db;
65839   assert( db->nDb>iDb );
65840   pFix->pParse = pParse;
65841   pFix->zDb = db->aDb[iDb].zName;
65842   pFix->zType = zType;
65843   pFix->pName = pName;
65844   return 1;
65845 }
65846
65847 /*
65848 ** The following set of routines walk through the parse tree and assign
65849 ** a specific database to all table references where the database name
65850 ** was left unspecified in the original SQL statement.  The pFix structure
65851 ** must have been initialized by a prior call to sqlite3FixInit().
65852 **
65853 ** These routines are used to make sure that an index, trigger, or
65854 ** view in one database does not refer to objects in a different database.
65855 ** (Exception: indices, triggers, and views in the TEMP database are
65856 ** allowed to refer to anything.)  If a reference is explicitly made
65857 ** to an object in a different database, an error message is added to
65858 ** pParse->zErrMsg and these routines return non-zero.  If everything
65859 ** checks out, these routines return 0.
65860 */
65861 SQLITE_PRIVATE int sqlite3FixSrcList(
65862   DbFixer *pFix,       /* Context of the fixation */
65863   SrcList *pList       /* The Source list to check and modify */
65864 ){
65865   int i;
65866   const char *zDb;
65867   struct SrcList_item *pItem;
65868
65869   if( NEVER(pList==0) ) return 0;
65870   zDb = pFix->zDb;
65871   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
65872     if( pItem->zDatabase==0 ){
65873       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
65874     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
65875       sqlite3ErrorMsg(pFix->pParse,
65876          "%s %T cannot reference objects in database %s",
65877          pFix->zType, pFix->pName, pItem->zDatabase);
65878       return 1;
65879     }
65880 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
65881     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
65882     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
65883 #endif
65884   }
65885   return 0;
65886 }
65887 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
65888 SQLITE_PRIVATE int sqlite3FixSelect(
65889   DbFixer *pFix,       /* Context of the fixation */
65890   Select *pSelect      /* The SELECT statement to be fixed to one database */
65891 ){
65892   while( pSelect ){
65893     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
65894       return 1;
65895     }
65896     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
65897       return 1;
65898     }
65899     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
65900       return 1;
65901     }
65902     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
65903       return 1;
65904     }
65905     pSelect = pSelect->pPrior;
65906   }
65907   return 0;
65908 }
65909 SQLITE_PRIVATE int sqlite3FixExpr(
65910   DbFixer *pFix,     /* Context of the fixation */
65911   Expr *pExpr        /* The expression to be fixed to one database */
65912 ){
65913   while( pExpr ){
65914     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
65915     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
65916       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
65917     }else{
65918       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
65919     }
65920     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
65921       return 1;
65922     }
65923     pExpr = pExpr->pLeft;
65924   }
65925   return 0;
65926 }
65927 SQLITE_PRIVATE int sqlite3FixExprList(
65928   DbFixer *pFix,     /* Context of the fixation */
65929   ExprList *pList    /* The expression to be fixed to one database */
65930 ){
65931   int i;
65932   struct ExprList_item *pItem;
65933   if( pList==0 ) return 0;
65934   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
65935     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
65936       return 1;
65937     }
65938   }
65939   return 0;
65940 }
65941 #endif
65942
65943 #ifndef SQLITE_OMIT_TRIGGER
65944 SQLITE_PRIVATE int sqlite3FixTriggerStep(
65945   DbFixer *pFix,     /* Context of the fixation */
65946   TriggerStep *pStep /* The trigger step be fixed to one database */
65947 ){
65948   while( pStep ){
65949     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
65950       return 1;
65951     }
65952     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
65953       return 1;
65954     }
65955     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
65956       return 1;
65957     }
65958     pStep = pStep->pNext;
65959   }
65960   return 0;
65961 }
65962 #endif
65963
65964 /************** End of attach.c **********************************************/
65965 /************** Begin file auth.c ********************************************/
65966 /*
65967 ** 2003 January 11
65968 **
65969 ** The author disclaims copyright to this source code.  In place of
65970 ** a legal notice, here is a blessing:
65971 **
65972 **    May you do good and not evil.
65973 **    May you find forgiveness for yourself and forgive others.
65974 **    May you share freely, never taking more than you give.
65975 **
65976 *************************************************************************
65977 ** This file contains code used to implement the sqlite3_set_authorizer()
65978 ** API.  This facility is an optional feature of the library.  Embedded
65979 ** systems that do not need this facility may omit it by recompiling
65980 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
65981 */
65982
65983 /*
65984 ** All of the code in this file may be omitted by defining a single
65985 ** macro.
65986 */
65987 #ifndef SQLITE_OMIT_AUTHORIZATION
65988
65989 /*
65990 ** Set or clear the access authorization function.
65991 **
65992 ** The access authorization function is be called during the compilation
65993 ** phase to verify that the user has read and/or write access permission on
65994 ** various fields of the database.  The first argument to the auth function
65995 ** is a copy of the 3rd argument to this routine.  The second argument
65996 ** to the auth function is one of these constants:
65997 **
65998 **       SQLITE_CREATE_INDEX
65999 **       SQLITE_CREATE_TABLE
66000 **       SQLITE_CREATE_TEMP_INDEX
66001 **       SQLITE_CREATE_TEMP_TABLE
66002 **       SQLITE_CREATE_TEMP_TRIGGER
66003 **       SQLITE_CREATE_TEMP_VIEW
66004 **       SQLITE_CREATE_TRIGGER
66005 **       SQLITE_CREATE_VIEW
66006 **       SQLITE_DELETE
66007 **       SQLITE_DROP_INDEX
66008 **       SQLITE_DROP_TABLE
66009 **       SQLITE_DROP_TEMP_INDEX
66010 **       SQLITE_DROP_TEMP_TABLE
66011 **       SQLITE_DROP_TEMP_TRIGGER
66012 **       SQLITE_DROP_TEMP_VIEW
66013 **       SQLITE_DROP_TRIGGER
66014 **       SQLITE_DROP_VIEW
66015 **       SQLITE_INSERT
66016 **       SQLITE_PRAGMA
66017 **       SQLITE_READ
66018 **       SQLITE_SELECT
66019 **       SQLITE_TRANSACTION
66020 **       SQLITE_UPDATE
66021 **
66022 ** The third and fourth arguments to the auth function are the name of
66023 ** the table and the column that are being accessed.  The auth function
66024 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
66025 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
66026 ** means that the SQL statement will never-run - the sqlite3_exec() call
66027 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
66028 ** should run but attempts to read the specified column will return NULL
66029 ** and attempts to write the column will be ignored.
66030 **
66031 ** Setting the auth function to NULL disables this hook.  The default
66032 ** setting of the auth function is NULL.
66033 */
66034 SQLITE_API int sqlite3_set_authorizer(
66035   sqlite3 *db,
66036   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
66037   void *pArg
66038 ){
66039   sqlite3_mutex_enter(db->mutex);
66040   db->xAuth = xAuth;
66041   db->pAuthArg = pArg;
66042   sqlite3ExpirePreparedStatements(db);
66043   sqlite3_mutex_leave(db->mutex);
66044   return SQLITE_OK;
66045 }
66046
66047 /*
66048 ** Write an error message into pParse->zErrMsg that explains that the
66049 ** user-supplied authorization function returned an illegal value.
66050 */
66051 static void sqliteAuthBadReturnCode(Parse *pParse){
66052   sqlite3ErrorMsg(pParse, "authorizer malfunction");
66053   pParse->rc = SQLITE_ERROR;
66054 }
66055
66056 /*
66057 ** Invoke the authorization callback for permission to read column zCol from
66058 ** table zTab in database zDb. This function assumes that an authorization
66059 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
66060 **
66061 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
66062 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
66063 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
66064 */
66065 SQLITE_PRIVATE int sqlite3AuthReadCol(
66066   Parse *pParse,                  /* The parser context */
66067   const char *zTab,               /* Table name */
66068   const char *zCol,               /* Column name */
66069   int iDb                         /* Index of containing database. */
66070 ){
66071   sqlite3 *db = pParse->db;       /* Database handle */
66072   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
66073   int rc;                         /* Auth callback return code */
66074
66075   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
66076   if( rc==SQLITE_DENY ){
66077     if( db->nDb>2 || iDb!=0 ){
66078       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
66079     }else{
66080       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
66081     }
66082     pParse->rc = SQLITE_AUTH;
66083   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
66084     sqliteAuthBadReturnCode(pParse);
66085   }
66086   return rc;
66087 }
66088
66089 /*
66090 ** The pExpr should be a TK_COLUMN expression.  The table referred to
66091 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
66092 ** Check to see if it is OK to read this particular column.
66093 **
66094 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
66095 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
66096 ** then generate an error.
66097 */
66098 SQLITE_PRIVATE void sqlite3AuthRead(
66099   Parse *pParse,        /* The parser context */
66100   Expr *pExpr,          /* The expression to check authorization on */
66101   Schema *pSchema,      /* The schema of the expression */
66102   SrcList *pTabList     /* All table that pExpr might refer to */
66103 ){
66104   sqlite3 *db = pParse->db;
66105   Table *pTab = 0;      /* The table being read */
66106   const char *zCol;     /* Name of the column of the table */
66107   int iSrc;             /* Index in pTabList->a[] of table being read */
66108   int iDb;              /* The index of the database the expression refers to */
66109   int iCol;             /* Index of column in table */
66110
66111   if( db->xAuth==0 ) return;
66112   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
66113   if( iDb<0 ){
66114     /* An attempt to read a column out of a subquery or other
66115     ** temporary table. */
66116     return;
66117   }
66118
66119   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
66120   if( pExpr->op==TK_TRIGGER ){
66121     pTab = pParse->pTriggerTab;
66122   }else{
66123     assert( pTabList );
66124     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
66125       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
66126         pTab = pTabList->a[iSrc].pTab;
66127         break;
66128       }
66129     }
66130   }
66131   iCol = pExpr->iColumn;
66132   if( NEVER(pTab==0) ) return;
66133
66134   if( iCol>=0 ){
66135     assert( iCol<pTab->nCol );
66136     zCol = pTab->aCol[iCol].zName;
66137   }else if( pTab->iPKey>=0 ){
66138     assert( pTab->iPKey<pTab->nCol );
66139     zCol = pTab->aCol[pTab->iPKey].zName;
66140   }else{
66141     zCol = "ROWID";
66142   }
66143   assert( iDb>=0 && iDb<db->nDb );
66144   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
66145     pExpr->op = TK_NULL;
66146   }
66147 }
66148
66149 /*
66150 ** Do an authorization check using the code and arguments given.  Return
66151 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
66152 ** is returned, then the error count and error message in pParse are
66153 ** modified appropriately.
66154 */
66155 SQLITE_PRIVATE int sqlite3AuthCheck(
66156   Parse *pParse,
66157   int code,
66158   const char *zArg1,
66159   const char *zArg2,
66160   const char *zArg3
66161 ){
66162   sqlite3 *db = pParse->db;
66163   int rc;
66164
66165   /* Don't do any authorization checks if the database is initialising
66166   ** or if the parser is being invoked from within sqlite3_declare_vtab.
66167   */
66168   if( db->init.busy || IN_DECLARE_VTAB ){
66169     return SQLITE_OK;
66170   }
66171
66172   if( db->xAuth==0 ){
66173     return SQLITE_OK;
66174   }
66175   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
66176   if( rc==SQLITE_DENY ){
66177     sqlite3ErrorMsg(pParse, "not authorized");
66178     pParse->rc = SQLITE_AUTH;
66179   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
66180     rc = SQLITE_DENY;
66181     sqliteAuthBadReturnCode(pParse);
66182   }
66183   return rc;
66184 }
66185
66186 /*
66187 ** Push an authorization context.  After this routine is called, the
66188 ** zArg3 argument to authorization callbacks will be zContext until
66189 ** popped.  Or if pParse==0, this routine is a no-op.
66190 */
66191 SQLITE_PRIVATE void sqlite3AuthContextPush(
66192   Parse *pParse,
66193   AuthContext *pContext, 
66194   const char *zContext
66195 ){
66196   assert( pParse );
66197   pContext->pParse = pParse;
66198   pContext->zAuthContext = pParse->zAuthContext;
66199   pParse->zAuthContext = zContext;
66200 }
66201
66202 /*
66203 ** Pop an authorization context that was previously pushed
66204 ** by sqlite3AuthContextPush
66205 */
66206 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
66207   if( pContext->pParse ){
66208     pContext->pParse->zAuthContext = pContext->zAuthContext;
66209     pContext->pParse = 0;
66210   }
66211 }
66212
66213 #endif /* SQLITE_OMIT_AUTHORIZATION */
66214
66215 /************** End of auth.c ************************************************/
66216 /************** Begin file build.c *******************************************/
66217 /*
66218 ** 2001 September 15
66219 **
66220 ** The author disclaims copyright to this source code.  In place of
66221 ** a legal notice, here is a blessing:
66222 **
66223 **    May you do good and not evil.
66224 **    May you find forgiveness for yourself and forgive others.
66225 **    May you share freely, never taking more than you give.
66226 **
66227 *************************************************************************
66228 ** This file contains C code routines that are called by the SQLite parser
66229 ** when syntax rules are reduced.  The routines in this file handle the
66230 ** following kinds of SQL syntax:
66231 **
66232 **     CREATE TABLE
66233 **     DROP TABLE
66234 **     CREATE INDEX
66235 **     DROP INDEX
66236 **     creating ID lists
66237 **     BEGIN TRANSACTION
66238 **     COMMIT
66239 **     ROLLBACK
66240 */
66241
66242 /*
66243 ** This routine is called when a new SQL statement is beginning to
66244 ** be parsed.  Initialize the pParse structure as needed.
66245 */
66246 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
66247   pParse->explain = (u8)explainFlag;
66248   pParse->nVar = 0;
66249 }
66250
66251 #ifndef SQLITE_OMIT_SHARED_CACHE
66252 /*
66253 ** The TableLock structure is only used by the sqlite3TableLock() and
66254 ** codeTableLocks() functions.
66255 */
66256 struct TableLock {
66257   int iDb;             /* The database containing the table to be locked */
66258   int iTab;            /* The root page of the table to be locked */
66259   u8 isWriteLock;      /* True for write lock.  False for a read lock */
66260   const char *zName;   /* Name of the table */
66261 };
66262
66263 /*
66264 ** Record the fact that we want to lock a table at run-time.  
66265 **
66266 ** The table to be locked has root page iTab and is found in database iDb.
66267 ** A read or a write lock can be taken depending on isWritelock.
66268 **
66269 ** This routine just records the fact that the lock is desired.  The
66270 ** code to make the lock occur is generated by a later call to
66271 ** codeTableLocks() which occurs during sqlite3FinishCoding().
66272 */
66273 SQLITE_PRIVATE void sqlite3TableLock(
66274   Parse *pParse,     /* Parsing context */
66275   int iDb,           /* Index of the database containing the table to lock */
66276   int iTab,          /* Root page number of the table to be locked */
66277   u8 isWriteLock,    /* True for a write lock */
66278   const char *zName  /* Name of the table to be locked */
66279 ){
66280   Parse *pToplevel = sqlite3ParseToplevel(pParse);
66281   int i;
66282   int nBytes;
66283   TableLock *p;
66284   assert( iDb>=0 );
66285
66286   for(i=0; i<pToplevel->nTableLock; i++){
66287     p = &pToplevel->aTableLock[i];
66288     if( p->iDb==iDb && p->iTab==iTab ){
66289       p->isWriteLock = (p->isWriteLock || isWriteLock);
66290       return;
66291     }
66292   }
66293
66294   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
66295   pToplevel->aTableLock =
66296       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
66297   if( pToplevel->aTableLock ){
66298     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
66299     p->iDb = iDb;
66300     p->iTab = iTab;
66301     p->isWriteLock = isWriteLock;
66302     p->zName = zName;
66303   }else{
66304     pToplevel->nTableLock = 0;
66305     pToplevel->db->mallocFailed = 1;
66306   }
66307 }
66308
66309 /*
66310 ** Code an OP_TableLock instruction for each table locked by the
66311 ** statement (configured by calls to sqlite3TableLock()).
66312 */
66313 static void codeTableLocks(Parse *pParse){
66314   int i;
66315   Vdbe *pVdbe; 
66316
66317   pVdbe = sqlite3GetVdbe(pParse);
66318   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
66319
66320   for(i=0; i<pParse->nTableLock; i++){
66321     TableLock *p = &pParse->aTableLock[i];
66322     int p1 = p->iDb;
66323     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
66324                       p->zName, P4_STATIC);
66325   }
66326 }
66327 #else
66328   #define codeTableLocks(x)
66329 #endif
66330
66331 /*
66332 ** This routine is called after a single SQL statement has been
66333 ** parsed and a VDBE program to execute that statement has been
66334 ** prepared.  This routine puts the finishing touches on the
66335 ** VDBE program and resets the pParse structure for the next
66336 ** parse.
66337 **
66338 ** Note that if an error occurred, it might be the case that
66339 ** no VDBE code was generated.
66340 */
66341 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
66342   sqlite3 *db;
66343   Vdbe *v;
66344
66345   db = pParse->db;
66346   if( db->mallocFailed ) return;
66347   if( pParse->nested ) return;
66348   if( pParse->nErr ) return;
66349
66350   /* Begin by generating some termination code at the end of the
66351   ** vdbe program
66352   */
66353   v = sqlite3GetVdbe(pParse);
66354   assert( !pParse->isMultiWrite 
66355        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
66356   if( v ){
66357     sqlite3VdbeAddOp0(v, OP_Halt);
66358
66359     /* The cookie mask contains one bit for each database file open.
66360     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
66361     ** set for each database that is used.  Generate code to start a
66362     ** transaction on each used database and to verify the schema cookie
66363     ** on each used database.
66364     */
66365     if( pParse->cookieGoto>0 ){
66366       u32 mask;
66367       int iDb;
66368       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
66369       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
66370         if( (mask & pParse->cookieMask)==0 ) continue;
66371         sqlite3VdbeUsesBtree(v, iDb);
66372         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
66373         if( db->init.busy==0 ){
66374           sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
66375         }
66376       }
66377 #ifndef SQLITE_OMIT_VIRTUALTABLE
66378       {
66379         int i;
66380         for(i=0; i<pParse->nVtabLock; i++){
66381           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
66382           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
66383         }
66384         pParse->nVtabLock = 0;
66385       }
66386 #endif
66387
66388       /* Once all the cookies have been verified and transactions opened, 
66389       ** obtain the required table-locks. This is a no-op unless the 
66390       ** shared-cache feature is enabled.
66391       */
66392       codeTableLocks(pParse);
66393
66394       /* Initialize any AUTOINCREMENT data structures required.
66395       */
66396       sqlite3AutoincrementBegin(pParse);
66397
66398       /* Finally, jump back to the beginning of the executable code. */
66399       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
66400     }
66401   }
66402
66403
66404   /* Get the VDBE program ready for execution
66405   */
66406   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
66407 #ifdef SQLITE_DEBUG
66408     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
66409     sqlite3VdbeTrace(v, trace);
66410 #endif
66411     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
66412     /* A minimum of one cursor is required if autoincrement is used
66413     *  See ticket [a696379c1f08866] */
66414     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
66415     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
66416                          pParse->nTab, pParse->nMaxArg, pParse->explain,
66417                          pParse->isMultiWrite && pParse->mayAbort);
66418     pParse->rc = SQLITE_DONE;
66419     pParse->colNamesSet = 0;
66420   }else if( pParse->rc==SQLITE_OK ){
66421     pParse->rc = SQLITE_ERROR;
66422   }
66423   pParse->nTab = 0;
66424   pParse->nMem = 0;
66425   pParse->nSet = 0;
66426   pParse->nVar = 0;
66427   pParse->cookieMask = 0;
66428   pParse->cookieGoto = 0;
66429 }
66430
66431 /*
66432 ** Run the parser and code generator recursively in order to generate
66433 ** code for the SQL statement given onto the end of the pParse context
66434 ** currently under construction.  When the parser is run recursively
66435 ** this way, the final OP_Halt is not appended and other initialization
66436 ** and finalization steps are omitted because those are handling by the
66437 ** outermost parser.
66438 **
66439 ** Not everything is nestable.  This facility is designed to permit
66440 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
66441 ** care if you decide to try to use this routine for some other purposes.
66442 */
66443 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
66444   va_list ap;
66445   char *zSql;
66446   char *zErrMsg = 0;
66447   sqlite3 *db = pParse->db;
66448 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
66449   char saveBuf[SAVE_SZ];
66450
66451   if( pParse->nErr ) return;
66452   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
66453   va_start(ap, zFormat);
66454   zSql = sqlite3VMPrintf(db, zFormat, ap);
66455   va_end(ap);
66456   if( zSql==0 ){
66457     return;   /* A malloc must have failed */
66458   }
66459   pParse->nested++;
66460   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
66461   memset(&pParse->nVar, 0, SAVE_SZ);
66462   sqlite3RunParser(pParse, zSql, &zErrMsg);
66463   sqlite3DbFree(db, zErrMsg);
66464   sqlite3DbFree(db, zSql);
66465   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
66466   pParse->nested--;
66467 }
66468
66469 /*
66470 ** Locate the in-memory structure that describes a particular database
66471 ** table given the name of that table and (optionally) the name of the
66472 ** database containing the table.  Return NULL if not found.
66473 **
66474 ** If zDatabase is 0, all databases are searched for the table and the
66475 ** first matching table is returned.  (No checking for duplicate table
66476 ** names is done.)  The search order is TEMP first, then MAIN, then any
66477 ** auxiliary databases added using the ATTACH command.
66478 **
66479 ** See also sqlite3LocateTable().
66480 */
66481 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
66482   Table *p = 0;
66483   int i;
66484   int nName;
66485   assert( zName!=0 );
66486   nName = sqlite3Strlen30(zName);
66487   for(i=OMIT_TEMPDB; i<db->nDb; i++){
66488     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
66489     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
66490     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
66491     if( p ) break;
66492   }
66493   return p;
66494 }
66495
66496 /*
66497 ** Locate the in-memory structure that describes a particular database
66498 ** table given the name of that table and (optionally) the name of the
66499 ** database containing the table.  Return NULL if not found.  Also leave an
66500 ** error message in pParse->zErrMsg.
66501 **
66502 ** The difference between this routine and sqlite3FindTable() is that this
66503 ** routine leaves an error message in pParse->zErrMsg where
66504 ** sqlite3FindTable() does not.
66505 */
66506 SQLITE_PRIVATE Table *sqlite3LocateTable(
66507   Parse *pParse,         /* context in which to report errors */
66508   int isView,            /* True if looking for a VIEW rather than a TABLE */
66509   const char *zName,     /* Name of the table we are looking for */
66510   const char *zDbase     /* Name of the database.  Might be NULL */
66511 ){
66512   Table *p;
66513
66514   /* Read the database schema. If an error occurs, leave an error message
66515   ** and code in pParse and return NULL. */
66516   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
66517     return 0;
66518   }
66519
66520   p = sqlite3FindTable(pParse->db, zName, zDbase);
66521   if( p==0 ){
66522     const char *zMsg = isView ? "no such view" : "no such table";
66523     if( zDbase ){
66524       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
66525     }else{
66526       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
66527     }
66528     pParse->checkSchema = 1;
66529   }
66530   return p;
66531 }
66532
66533 /*
66534 ** Locate the in-memory structure that describes 
66535 ** a particular index given the name of that index
66536 ** and the name of the database that contains the index.
66537 ** Return NULL if not found.
66538 **
66539 ** If zDatabase is 0, all databases are searched for the
66540 ** table and the first matching index is returned.  (No checking
66541 ** for duplicate index names is done.)  The search order is
66542 ** TEMP first, then MAIN, then any auxiliary databases added
66543 ** using the ATTACH command.
66544 */
66545 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
66546   Index *p = 0;
66547   int i;
66548   int nName = sqlite3Strlen30(zName);
66549   for(i=OMIT_TEMPDB; i<db->nDb; i++){
66550     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
66551     Schema *pSchema = db->aDb[j].pSchema;
66552     assert( pSchema );
66553     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
66554     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
66555     if( p ) break;
66556   }
66557   return p;
66558 }
66559
66560 /*
66561 ** Reclaim the memory used by an index
66562 */
66563 static void freeIndex(Index *p){
66564   sqlite3 *db = p->pTable->dbMem;
66565 #ifndef SQLITE_OMIT_ANALYZE
66566   sqlite3DeleteIndexSamples(p);
66567 #endif
66568   sqlite3DbFree(db, p->zColAff);
66569   sqlite3DbFree(db, p);
66570 }
66571
66572 /*
66573 ** Remove the given index from the index hash table, and free
66574 ** its memory structures.
66575 **
66576 ** The index is removed from the database hash tables but
66577 ** it is not unlinked from the Table that it indexes.
66578 ** Unlinking from the Table must be done by the calling function.
66579 */
66580 static void sqlite3DeleteIndex(Index *p){
66581   Index *pOld;
66582   const char *zName = p->zName;
66583
66584   pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
66585                            sqlite3Strlen30(zName), 0);
66586   assert( pOld==0 || pOld==p );
66587   freeIndex(p);
66588 }
66589
66590 /*
66591 ** For the index called zIdxName which is found in the database iDb,
66592 ** unlike that index from its Table then remove the index from
66593 ** the index hash table and free all memory structures associated
66594 ** with the index.
66595 */
66596 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
66597   Index *pIndex;
66598   int len;
66599   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
66600
66601   len = sqlite3Strlen30(zIdxName);
66602   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
66603   if( pIndex ){
66604     if( pIndex->pTable->pIndex==pIndex ){
66605       pIndex->pTable->pIndex = pIndex->pNext;
66606     }else{
66607       Index *p;
66608       /* Justification of ALWAYS();  The index must be on the list of
66609       ** indices. */
66610       p = pIndex->pTable->pIndex;
66611       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
66612       if( ALWAYS(p && p->pNext==pIndex) ){
66613         p->pNext = pIndex->pNext;
66614       }
66615     }
66616     freeIndex(pIndex);
66617   }
66618   db->flags |= SQLITE_InternChanges;
66619 }
66620
66621 /*
66622 ** Erase all schema information from the in-memory hash tables of
66623 ** a single database.  This routine is called to reclaim memory
66624 ** before the database closes.  It is also called during a rollback
66625 ** if there were schema changes during the transaction or if a
66626 ** schema-cookie mismatch occurs.
66627 **
66628 ** If iDb==0 then reset the internal schema tables for all database
66629 ** files.  If iDb>=1 then reset the internal schema for only the
66630 ** single file indicated.
66631 */
66632 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
66633   int i, j;
66634   assert( iDb>=0 && iDb<db->nDb );
66635
66636   if( iDb==0 ){
66637     sqlite3BtreeEnterAll(db);
66638   }
66639   for(i=iDb; i<db->nDb; i++){
66640     Db *pDb = &db->aDb[i];
66641     if( pDb->pSchema ){
66642       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
66643       sqlite3SchemaFree(pDb->pSchema);
66644     }
66645     if( iDb>0 ) return;
66646   }
66647   assert( iDb==0 );
66648   db->flags &= ~SQLITE_InternChanges;
66649   sqlite3VtabUnlockList(db);
66650   sqlite3BtreeLeaveAll(db);
66651
66652   /* If one or more of the auxiliary database files has been closed,
66653   ** then remove them from the auxiliary database list.  We take the
66654   ** opportunity to do this here since we have just deleted all of the
66655   ** schema hash tables and therefore do not have to make any changes
66656   ** to any of those tables.
66657   */
66658   for(i=j=2; i<db->nDb; i++){
66659     struct Db *pDb = &db->aDb[i];
66660     if( pDb->pBt==0 ){
66661       sqlite3DbFree(db, pDb->zName);
66662       pDb->zName = 0;
66663       continue;
66664     }
66665     if( j<i ){
66666       db->aDb[j] = db->aDb[i];
66667     }
66668     j++;
66669   }
66670   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
66671   db->nDb = j;
66672   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
66673     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
66674     sqlite3DbFree(db, db->aDb);
66675     db->aDb = db->aDbStatic;
66676   }
66677 }
66678
66679 /*
66680 ** This routine is called when a commit occurs.
66681 */
66682 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
66683   db->flags &= ~SQLITE_InternChanges;
66684 }
66685
66686 /*
66687 ** Clear the column names from a table or view.
66688 */
66689 static void sqliteResetColumnNames(Table *pTable){
66690   int i;
66691   Column *pCol;
66692   sqlite3 *db = pTable->dbMem;
66693   testcase( db==0 );
66694   assert( pTable!=0 );
66695   if( (pCol = pTable->aCol)!=0 ){
66696     for(i=0; i<pTable->nCol; i++, pCol++){
66697       sqlite3DbFree(db, pCol->zName);
66698       sqlite3ExprDelete(db, pCol->pDflt);
66699       sqlite3DbFree(db, pCol->zDflt);
66700       sqlite3DbFree(db, pCol->zType);
66701       sqlite3DbFree(db, pCol->zColl);
66702     }
66703     sqlite3DbFree(db, pTable->aCol);
66704   }
66705   pTable->aCol = 0;
66706   pTable->nCol = 0;
66707 }
66708
66709 /*
66710 ** Remove the memory data structures associated with the given
66711 ** Table.  No changes are made to disk by this routine.
66712 **
66713 ** This routine just deletes the data structure.  It does not unlink
66714 ** the table data structure from the hash table.  But it does destroy
66715 ** memory structures of the indices and foreign keys associated with 
66716 ** the table.
66717 */
66718 SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
66719   Index *pIndex, *pNext;
66720   sqlite3 *db;
66721
66722   if( pTable==0 ) return;
66723   db = pTable->dbMem;
66724   testcase( db==0 );
66725
66726   /* Do not delete the table until the reference count reaches zero. */
66727   pTable->nRef--;
66728   if( pTable->nRef>0 ){
66729     return;
66730   }
66731   assert( pTable->nRef==0 );
66732
66733   /* Delete all indices associated with this table
66734   */
66735   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
66736     pNext = pIndex->pNext;
66737     assert( pIndex->pSchema==pTable->pSchema );
66738     sqlite3DeleteIndex(pIndex);
66739   }
66740
66741   /* Delete any foreign keys attached to this table. */
66742   sqlite3FkDelete(pTable);
66743
66744   /* Delete the Table structure itself.
66745   */
66746   sqliteResetColumnNames(pTable);
66747   sqlite3DbFree(db, pTable->zName);
66748   sqlite3DbFree(db, pTable->zColAff);
66749   sqlite3SelectDelete(db, pTable->pSelect);
66750 #ifndef SQLITE_OMIT_CHECK
66751   sqlite3ExprDelete(db, pTable->pCheck);
66752 #endif
66753   sqlite3VtabClear(pTable);
66754   sqlite3DbFree(db, pTable);
66755 }
66756
66757 /*
66758 ** Unlink the given table from the hash tables and the delete the
66759 ** table structure with all its indices and foreign keys.
66760 */
66761 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
66762   Table *p;
66763   Db *pDb;
66764
66765   assert( db!=0 );
66766   assert( iDb>=0 && iDb<db->nDb );
66767   assert( zTabName );
66768   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
66769   pDb = &db->aDb[iDb];
66770   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
66771                         sqlite3Strlen30(zTabName),0);
66772   sqlite3DeleteTable(p);
66773   db->flags |= SQLITE_InternChanges;
66774 }
66775
66776 /*
66777 ** Given a token, return a string that consists of the text of that
66778 ** token.  Space to hold the returned string
66779 ** is obtained from sqliteMalloc() and must be freed by the calling
66780 ** function.
66781 **
66782 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
66783 ** surround the body of the token are removed.
66784 **
66785 ** Tokens are often just pointers into the original SQL text and so
66786 ** are not \000 terminated and are not persistent.  The returned string
66787 ** is \000 terminated and is persistent.
66788 */
66789 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
66790   char *zName;
66791   if( pName ){
66792     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
66793     sqlite3Dequote(zName);
66794   }else{
66795     zName = 0;
66796   }
66797   return zName;
66798 }
66799
66800 /*
66801 ** Open the sqlite_master table stored in database number iDb for
66802 ** writing. The table is opened using cursor 0.
66803 */
66804 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
66805   Vdbe *v = sqlite3GetVdbe(p);
66806   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
66807   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
66808   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
66809   if( p->nTab==0 ){
66810     p->nTab = 1;
66811   }
66812 }
66813
66814 /*
66815 ** Parameter zName points to a nul-terminated buffer containing the name
66816 ** of a database ("main", "temp" or the name of an attached db). This
66817 ** function returns the index of the named database in db->aDb[], or
66818 ** -1 if the named db cannot be found.
66819 */
66820 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
66821   int i = -1;         /* Database number */
66822   if( zName ){
66823     Db *pDb;
66824     int n = sqlite3Strlen30(zName);
66825     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
66826       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
66827           0==sqlite3StrICmp(pDb->zName, zName) ){
66828         break;
66829       }
66830     }
66831   }
66832   return i;
66833 }
66834
66835 /*
66836 ** The token *pName contains the name of a database (either "main" or
66837 ** "temp" or the name of an attached db). This routine returns the
66838 ** index of the named database in db->aDb[], or -1 if the named db 
66839 ** does not exist.
66840 */
66841 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
66842   int i;                               /* Database number */
66843   char *zName;                         /* Name we are searching for */
66844   zName = sqlite3NameFromToken(db, pName);
66845   i = sqlite3FindDbName(db, zName);
66846   sqlite3DbFree(db, zName);
66847   return i;
66848 }
66849
66850 /* The table or view or trigger name is passed to this routine via tokens
66851 ** pName1 and pName2. If the table name was fully qualified, for example:
66852 **
66853 ** CREATE TABLE xxx.yyy (...);
66854 ** 
66855 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
66856 ** the table name is not fully qualified, i.e.:
66857 **
66858 ** CREATE TABLE yyy(...);
66859 **
66860 ** Then pName1 is set to "yyy" and pName2 is "".
66861 **
66862 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
66863 ** pName2) that stores the unqualified table name.  The index of the
66864 ** database "xxx" is returned.
66865 */
66866 SQLITE_PRIVATE int sqlite3TwoPartName(
66867   Parse *pParse,      /* Parsing and code generating context */
66868   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
66869   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
66870   Token **pUnqual     /* Write the unqualified object name here */
66871 ){
66872   int iDb;                    /* Database holding the object */
66873   sqlite3 *db = pParse->db;
66874
66875   if( ALWAYS(pName2!=0) && pName2->n>0 ){
66876     if( db->init.busy ) {
66877       sqlite3ErrorMsg(pParse, "corrupt database");
66878       pParse->nErr++;
66879       return -1;
66880     }
66881     *pUnqual = pName2;
66882     iDb = sqlite3FindDb(db, pName1);
66883     if( iDb<0 ){
66884       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
66885       pParse->nErr++;
66886       return -1;
66887     }
66888   }else{
66889     assert( db->init.iDb==0 || db->init.busy );
66890     iDb = db->init.iDb;
66891     *pUnqual = pName1;
66892   }
66893   return iDb;
66894 }
66895
66896 /*
66897 ** This routine is used to check if the UTF-8 string zName is a legal
66898 ** unqualified name for a new schema object (table, index, view or
66899 ** trigger). All names are legal except those that begin with the string
66900 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
66901 ** is reserved for internal use.
66902 */
66903 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
66904   if( !pParse->db->init.busy && pParse->nested==0 
66905           && (pParse->db->flags & SQLITE_WriteSchema)==0
66906           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
66907     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
66908     return SQLITE_ERROR;
66909   }
66910   return SQLITE_OK;
66911 }
66912
66913 /*
66914 ** Begin constructing a new table representation in memory.  This is
66915 ** the first of several action routines that get called in response
66916 ** to a CREATE TABLE statement.  In particular, this routine is called
66917 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
66918 ** flag is true if the table should be stored in the auxiliary database
66919 ** file instead of in the main database file.  This is normally the case
66920 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
66921 ** CREATE and TABLE.
66922 **
66923 ** The new table record is initialized and put in pParse->pNewTable.
66924 ** As more of the CREATE TABLE statement is parsed, additional action
66925 ** routines will be called to add more information to this record.
66926 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
66927 ** is called to complete the construction of the new table record.
66928 */
66929 SQLITE_PRIVATE void sqlite3StartTable(
66930   Parse *pParse,   /* Parser context */
66931   Token *pName1,   /* First part of the name of the table or view */
66932   Token *pName2,   /* Second part of the name of the table or view */
66933   int isTemp,      /* True if this is a TEMP table */
66934   int isView,      /* True if this is a VIEW */
66935   int isVirtual,   /* True if this is a VIRTUAL table */
66936   int noErr        /* Do nothing if table already exists */
66937 ){
66938   Table *pTable;
66939   char *zName = 0; /* The name of the new table */
66940   sqlite3 *db = pParse->db;
66941   Vdbe *v;
66942   int iDb;         /* Database number to create the table in */
66943   Token *pName;    /* Unqualified name of the table to create */
66944
66945   /* The table or view name to create is passed to this routine via tokens
66946   ** pName1 and pName2. If the table name was fully qualified, for example:
66947   **
66948   ** CREATE TABLE xxx.yyy (...);
66949   ** 
66950   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
66951   ** the table name is not fully qualified, i.e.:
66952   **
66953   ** CREATE TABLE yyy(...);
66954   **
66955   ** Then pName1 is set to "yyy" and pName2 is "".
66956   **
66957   ** The call below sets the pName pointer to point at the token (pName1 or
66958   ** pName2) that stores the unqualified table name. The variable iDb is
66959   ** set to the index of the database that the table or view is to be
66960   ** created in.
66961   */
66962   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
66963   if( iDb<0 ) return;
66964   if( !OMIT_TEMPDB && isTemp && iDb>1 ){
66965     /* If creating a temp table, the name may not be qualified */
66966     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
66967     return;
66968   }
66969   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
66970
66971   pParse->sNameToken = *pName;
66972   zName = sqlite3NameFromToken(db, pName);
66973   if( zName==0 ) return;
66974   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
66975     goto begin_table_error;
66976   }
66977   if( db->init.iDb==1 ) isTemp = 1;
66978 #ifndef SQLITE_OMIT_AUTHORIZATION
66979   assert( (isTemp & 1)==isTemp );
66980   {
66981     int code;
66982     char *zDb = db->aDb[iDb].zName;
66983     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
66984       goto begin_table_error;
66985     }
66986     if( isView ){
66987       if( !OMIT_TEMPDB && isTemp ){
66988         code = SQLITE_CREATE_TEMP_VIEW;
66989       }else{
66990         code = SQLITE_CREATE_VIEW;
66991       }
66992     }else{
66993       if( !OMIT_TEMPDB && isTemp ){
66994         code = SQLITE_CREATE_TEMP_TABLE;
66995       }else{
66996         code = SQLITE_CREATE_TABLE;
66997       }
66998     }
66999     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
67000       goto begin_table_error;
67001     }
67002   }
67003 #endif
67004
67005   /* Make sure the new table name does not collide with an existing
67006   ** index or table name in the same database.  Issue an error message if
67007   ** it does. The exception is if the statement being parsed was passed
67008   ** to an sqlite3_declare_vtab() call. In that case only the column names
67009   ** and types will be used, so there is no need to test for namespace
67010   ** collisions.
67011   */
67012   if( !IN_DECLARE_VTAB ){
67013     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
67014       goto begin_table_error;
67015     }
67016     pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
67017     if( pTable ){
67018       if( !noErr ){
67019         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
67020       }
67021       goto begin_table_error;
67022     }
67023     if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
67024       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
67025       goto begin_table_error;
67026     }
67027   }
67028
67029   pTable = sqlite3DbMallocZero(db, sizeof(Table));
67030   if( pTable==0 ){
67031     db->mallocFailed = 1;
67032     pParse->rc = SQLITE_NOMEM;
67033     pParse->nErr++;
67034     goto begin_table_error;
67035   }
67036   pTable->zName = zName;
67037   pTable->iPKey = -1;
67038   pTable->pSchema = db->aDb[iDb].pSchema;
67039   pTable->nRef = 1;
67040   pTable->dbMem = 0;
67041   assert( pParse->pNewTable==0 );
67042   pParse->pNewTable = pTable;
67043
67044   /* If this is the magic sqlite_sequence table used by autoincrement,
67045   ** then record a pointer to this table in the main database structure
67046   ** so that INSERT can find the table easily.
67047   */
67048 #ifndef SQLITE_OMIT_AUTOINCREMENT
67049   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
67050     pTable->pSchema->pSeqTab = pTable;
67051   }
67052 #endif
67053
67054   /* Begin generating the code that will insert the table record into
67055   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
67056   ** and allocate the record number for the table entry now.  Before any
67057   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
67058   ** indices to be created and the table record must come before the 
67059   ** indices.  Hence, the record number for the table must be allocated
67060   ** now.
67061   */
67062   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
67063     int j1;
67064     int fileFormat;
67065     int reg1, reg2, reg3;
67066     sqlite3BeginWriteOperation(pParse, 0, iDb);
67067
67068 #ifndef SQLITE_OMIT_VIRTUALTABLE
67069     if( isVirtual ){
67070       sqlite3VdbeAddOp0(v, OP_VBegin);
67071     }
67072 #endif
67073
67074     /* If the file format and encoding in the database have not been set, 
67075     ** set them now.
67076     */
67077     reg1 = pParse->regRowid = ++pParse->nMem;
67078     reg2 = pParse->regRoot = ++pParse->nMem;
67079     reg3 = ++pParse->nMem;
67080     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
67081     sqlite3VdbeUsesBtree(v, iDb);
67082     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
67083     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
67084                   1 : SQLITE_MAX_FILE_FORMAT;
67085     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
67086     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
67087     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
67088     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
67089     sqlite3VdbeJumpHere(v, j1);
67090
67091     /* This just creates a place-holder record in the sqlite_master table.
67092     ** The record created does not contain anything yet.  It will be replaced
67093     ** by the real entry in code generated at sqlite3EndTable().
67094     **
67095     ** The rowid for the new entry is left in register pParse->regRowid.
67096     ** The root page number of the new table is left in reg pParse->regRoot.
67097     ** The rowid and root page number values are needed by the code that
67098     ** sqlite3EndTable will generate.
67099     */
67100 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
67101     if( isView || isVirtual ){
67102       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
67103     }else
67104 #endif
67105     {
67106       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
67107     }
67108     sqlite3OpenMasterTable(pParse, iDb);
67109     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
67110     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
67111     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
67112     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
67113     sqlite3VdbeAddOp0(v, OP_Close);
67114   }
67115
67116   /* Normal (non-error) return. */
67117   return;
67118
67119   /* If an error occurs, we jump here */
67120 begin_table_error:
67121   sqlite3DbFree(db, zName);
67122   return;
67123 }
67124
67125 /*
67126 ** This macro is used to compare two strings in a case-insensitive manner.
67127 ** It is slightly faster than calling sqlite3StrICmp() directly, but
67128 ** produces larger code.
67129 **
67130 ** WARNING: This macro is not compatible with the strcmp() family. It
67131 ** returns true if the two strings are equal, otherwise false.
67132 */
67133 #define STRICMP(x, y) (\
67134 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
67135 sqlite3UpperToLower[*(unsigned char *)(y)]     \
67136 && sqlite3StrICmp((x)+1,(y)+1)==0 )
67137
67138 /*
67139 ** Add a new column to the table currently being constructed.
67140 **
67141 ** The parser calls this routine once for each column declaration
67142 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
67143 ** first to get things going.  Then this routine is called for each
67144 ** column.
67145 */
67146 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
67147   Table *p;
67148   int i;
67149   char *z;
67150   Column *pCol;
67151   sqlite3 *db = pParse->db;
67152   if( (p = pParse->pNewTable)==0 ) return;
67153 #if SQLITE_MAX_COLUMN
67154   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
67155     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
67156     return;
67157   }
67158 #endif
67159   z = sqlite3NameFromToken(db, pName);
67160   if( z==0 ) return;
67161   for(i=0; i<p->nCol; i++){
67162     if( STRICMP(z, p->aCol[i].zName) ){
67163       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
67164       sqlite3DbFree(db, z);
67165       return;
67166     }
67167   }
67168   if( (p->nCol & 0x7)==0 ){
67169     Column *aNew;
67170     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
67171     if( aNew==0 ){
67172       sqlite3DbFree(db, z);
67173       return;
67174     }
67175     p->aCol = aNew;
67176   }
67177   pCol = &p->aCol[p->nCol];
67178   memset(pCol, 0, sizeof(p->aCol[0]));
67179   pCol->zName = z;
67180  
67181   /* If there is no type specified, columns have the default affinity
67182   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
67183   ** be called next to set pCol->affinity correctly.
67184   */
67185   pCol->affinity = SQLITE_AFF_NONE;
67186   p->nCol++;
67187 }
67188
67189 /*
67190 ** This routine is called by the parser while in the middle of
67191 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
67192 ** been seen on a column.  This routine sets the notNull flag on
67193 ** the column currently under construction.
67194 */
67195 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
67196   Table *p;
67197   p = pParse->pNewTable;
67198   if( p==0 || NEVER(p->nCol<1) ) return;
67199   p->aCol[p->nCol-1].notNull = (u8)onError;
67200 }
67201
67202 /*
67203 ** Scan the column type name zType (length nType) and return the
67204 ** associated affinity type.
67205 **
67206 ** This routine does a case-independent search of zType for the 
67207 ** substrings in the following table. If one of the substrings is
67208 ** found, the corresponding affinity is returned. If zType contains
67209 ** more than one of the substrings, entries toward the top of 
67210 ** the table take priority. For example, if zType is 'BLOBINT', 
67211 ** SQLITE_AFF_INTEGER is returned.
67212 **
67213 ** Substring     | Affinity
67214 ** --------------------------------
67215 ** 'INT'         | SQLITE_AFF_INTEGER
67216 ** 'CHAR'        | SQLITE_AFF_TEXT
67217 ** 'CLOB'        | SQLITE_AFF_TEXT
67218 ** 'TEXT'        | SQLITE_AFF_TEXT
67219 ** 'BLOB'        | SQLITE_AFF_NONE
67220 ** 'REAL'        | SQLITE_AFF_REAL
67221 ** 'FLOA'        | SQLITE_AFF_REAL
67222 ** 'DOUB'        | SQLITE_AFF_REAL
67223 **
67224 ** If none of the substrings in the above table are found,
67225 ** SQLITE_AFF_NUMERIC is returned.
67226 */
67227 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
67228   u32 h = 0;
67229   char aff = SQLITE_AFF_NUMERIC;
67230
67231   if( zIn ) while( zIn[0] ){
67232     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
67233     zIn++;
67234     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
67235       aff = SQLITE_AFF_TEXT; 
67236     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
67237       aff = SQLITE_AFF_TEXT;
67238     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
67239       aff = SQLITE_AFF_TEXT;
67240     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
67241         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
67242       aff = SQLITE_AFF_NONE;
67243 #ifndef SQLITE_OMIT_FLOATING_POINT
67244     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
67245         && aff==SQLITE_AFF_NUMERIC ){
67246       aff = SQLITE_AFF_REAL;
67247     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
67248         && aff==SQLITE_AFF_NUMERIC ){
67249       aff = SQLITE_AFF_REAL;
67250     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
67251         && aff==SQLITE_AFF_NUMERIC ){
67252       aff = SQLITE_AFF_REAL;
67253 #endif
67254     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
67255       aff = SQLITE_AFF_INTEGER;
67256       break;
67257     }
67258   }
67259
67260   return aff;
67261 }
67262
67263 /*
67264 ** This routine is called by the parser while in the middle of
67265 ** parsing a CREATE TABLE statement.  The pFirst token is the first
67266 ** token in the sequence of tokens that describe the type of the
67267 ** column currently under construction.   pLast is the last token
67268 ** in the sequence.  Use this information to construct a string
67269 ** that contains the typename of the column and store that string
67270 ** in zType.
67271 */ 
67272 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
67273   Table *p;
67274   Column *pCol;
67275
67276   p = pParse->pNewTable;
67277   if( p==0 || NEVER(p->nCol<1) ) return;
67278   pCol = &p->aCol[p->nCol-1];
67279   assert( pCol->zType==0 );
67280   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
67281   pCol->affinity = sqlite3AffinityType(pCol->zType);
67282 }
67283
67284 /*
67285 ** The expression is the default value for the most recently added column
67286 ** of the table currently under construction.
67287 **
67288 ** Default value expressions must be constant.  Raise an exception if this
67289 ** is not the case.
67290 **
67291 ** This routine is called by the parser while in the middle of
67292 ** parsing a CREATE TABLE statement.
67293 */
67294 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
67295   Table *p;
67296   Column *pCol;
67297   sqlite3 *db = pParse->db;
67298   p = pParse->pNewTable;
67299   if( p!=0 ){
67300     pCol = &(p->aCol[p->nCol-1]);
67301     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
67302       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
67303           pCol->zName);
67304     }else{
67305       /* A copy of pExpr is used instead of the original, as pExpr contains
67306       ** tokens that point to volatile memory. The 'span' of the expression
67307       ** is required by pragma table_info.
67308       */
67309       sqlite3ExprDelete(db, pCol->pDflt);
67310       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
67311       sqlite3DbFree(db, pCol->zDflt);
67312       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
67313                                      (int)(pSpan->zEnd - pSpan->zStart));
67314     }
67315   }
67316   sqlite3ExprDelete(db, pSpan->pExpr);
67317 }
67318
67319 /*
67320 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
67321 ** of columns that form the primary key.  If pList is NULL, then the
67322 ** most recently added column of the table is the primary key.
67323 **
67324 ** A table can have at most one primary key.  If the table already has
67325 ** a primary key (and this is the second primary key) then create an
67326 ** error.
67327 **
67328 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
67329 ** then we will try to use that column as the rowid.  Set the Table.iPKey
67330 ** field of the table under construction to be the index of the
67331 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
67332 ** no INTEGER PRIMARY KEY.
67333 **
67334 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
67335 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
67336 */
67337 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
67338   Parse *pParse,    /* Parsing context */
67339   ExprList *pList,  /* List of field names to be indexed */
67340   int onError,      /* What to do with a uniqueness conflict */
67341   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
67342   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
67343 ){
67344   Table *pTab = pParse->pNewTable;
67345   char *zType = 0;
67346   int iCol = -1, i;
67347   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
67348   if( pTab->tabFlags & TF_HasPrimaryKey ){
67349     sqlite3ErrorMsg(pParse, 
67350       "table \"%s\" has more than one primary key", pTab->zName);
67351     goto primary_key_exit;
67352   }
67353   pTab->tabFlags |= TF_HasPrimaryKey;
67354   if( pList==0 ){
67355     iCol = pTab->nCol - 1;
67356     pTab->aCol[iCol].isPrimKey = 1;
67357   }else{
67358     for(i=0; i<pList->nExpr; i++){
67359       for(iCol=0; iCol<pTab->nCol; iCol++){
67360         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
67361           break;
67362         }
67363       }
67364       if( iCol<pTab->nCol ){
67365         pTab->aCol[iCol].isPrimKey = 1;
67366       }
67367     }
67368     if( pList->nExpr>1 ) iCol = -1;
67369   }
67370   if( iCol>=0 && iCol<pTab->nCol ){
67371     zType = pTab->aCol[iCol].zType;
67372   }
67373   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
67374         && sortOrder==SQLITE_SO_ASC ){
67375     pTab->iPKey = iCol;
67376     pTab->keyConf = (u8)onError;
67377     assert( autoInc==0 || autoInc==1 );
67378     pTab->tabFlags |= autoInc*TF_Autoincrement;
67379   }else if( autoInc ){
67380 #ifndef SQLITE_OMIT_AUTOINCREMENT
67381     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
67382        "INTEGER PRIMARY KEY");
67383 #endif
67384   }else{
67385     Index *p;
67386     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
67387     if( p ){
67388       p->autoIndex = 2;
67389     }
67390     pList = 0;
67391   }
67392
67393 primary_key_exit:
67394   sqlite3ExprListDelete(pParse->db, pList);
67395   return;
67396 }
67397
67398 /*
67399 ** Add a new CHECK constraint to the table currently under construction.
67400 */
67401 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
67402   Parse *pParse,    /* Parsing context */
67403   Expr *pCheckExpr  /* The check expression */
67404 ){
67405   sqlite3 *db = pParse->db;
67406 #ifndef SQLITE_OMIT_CHECK
67407   Table *pTab = pParse->pNewTable;
67408   if( pTab && !IN_DECLARE_VTAB ){
67409     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
67410   }else
67411 #endif
67412   {
67413     sqlite3ExprDelete(db, pCheckExpr);
67414   }
67415 }
67416
67417 /*
67418 ** Set the collation function of the most recently parsed table column
67419 ** to the CollSeq given.
67420 */
67421 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
67422   Table *p;
67423   int i;
67424   char *zColl;              /* Dequoted name of collation sequence */
67425   sqlite3 *db;
67426
67427   if( (p = pParse->pNewTable)==0 ) return;
67428   i = p->nCol-1;
67429   db = pParse->db;
67430   zColl = sqlite3NameFromToken(db, pToken);
67431   if( !zColl ) return;
67432
67433   if( sqlite3LocateCollSeq(pParse, zColl) ){
67434     Index *pIdx;
67435     p->aCol[i].zColl = zColl;
67436   
67437     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
67438     ** then an index may have been created on this column before the
67439     ** collation type was added. Correct this if it is the case.
67440     */
67441     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
67442       assert( pIdx->nColumn==1 );
67443       if( pIdx->aiColumn[0]==i ){
67444         pIdx->azColl[0] = p->aCol[i].zColl;
67445       }
67446     }
67447   }else{
67448     sqlite3DbFree(db, zColl);
67449   }
67450 }
67451
67452 /*
67453 ** This function returns the collation sequence for database native text
67454 ** encoding identified by the string zName, length nName.
67455 **
67456 ** If the requested collation sequence is not available, or not available
67457 ** in the database native encoding, the collation factory is invoked to
67458 ** request it. If the collation factory does not supply such a sequence,
67459 ** and the sequence is available in another text encoding, then that is
67460 ** returned instead.
67461 **
67462 ** If no versions of the requested collations sequence are available, or
67463 ** another error occurs, NULL is returned and an error message written into
67464 ** pParse.
67465 **
67466 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
67467 ** invokes the collation factory if the named collation cannot be found
67468 ** and generates an error message.
67469 **
67470 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
67471 */
67472 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
67473   sqlite3 *db = pParse->db;
67474   u8 enc = ENC(db);
67475   u8 initbusy = db->init.busy;
67476   CollSeq *pColl;
67477
67478   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
67479   if( !initbusy && (!pColl || !pColl->xCmp) ){
67480     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
67481     if( !pColl ){
67482       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
67483     }
67484   }
67485
67486   return pColl;
67487 }
67488
67489
67490 /*
67491 ** Generate code that will increment the schema cookie.
67492 **
67493 ** The schema cookie is used to determine when the schema for the
67494 ** database changes.  After each schema change, the cookie value
67495 ** changes.  When a process first reads the schema it records the
67496 ** cookie.  Thereafter, whenever it goes to access the database,
67497 ** it checks the cookie to make sure the schema has not changed
67498 ** since it was last read.
67499 **
67500 ** This plan is not completely bullet-proof.  It is possible for
67501 ** the schema to change multiple times and for the cookie to be
67502 ** set back to prior value.  But schema changes are infrequent
67503 ** and the probability of hitting the same cookie value is only
67504 ** 1 chance in 2^32.  So we're safe enough.
67505 */
67506 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
67507   int r1 = sqlite3GetTempReg(pParse);
67508   sqlite3 *db = pParse->db;
67509   Vdbe *v = pParse->pVdbe;
67510   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
67511   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
67512   sqlite3ReleaseTempReg(pParse, r1);
67513 }
67514
67515 /*
67516 ** Measure the number of characters needed to output the given
67517 ** identifier.  The number returned includes any quotes used
67518 ** but does not include the null terminator.
67519 **
67520 ** The estimate is conservative.  It might be larger that what is
67521 ** really needed.
67522 */
67523 static int identLength(const char *z){
67524   int n;
67525   for(n=0; *z; n++, z++){
67526     if( *z=='"' ){ n++; }
67527   }
67528   return n + 2;
67529 }
67530
67531 /*
67532 ** The first parameter is a pointer to an output buffer. The second 
67533 ** parameter is a pointer to an integer that contains the offset at
67534 ** which to write into the output buffer. This function copies the
67535 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
67536 ** to the specified offset in the buffer and updates *pIdx to refer
67537 ** to the first byte after the last byte written before returning.
67538 ** 
67539 ** If the string zSignedIdent consists entirely of alpha-numeric
67540 ** characters, does not begin with a digit and is not an SQL keyword,
67541 ** then it is copied to the output buffer exactly as it is. Otherwise,
67542 ** it is quoted using double-quotes.
67543 */
67544 static void identPut(char *z, int *pIdx, char *zSignedIdent){
67545   unsigned char *zIdent = (unsigned char*)zSignedIdent;
67546   int i, j, needQuote;
67547   i = *pIdx;
67548
67549   for(j=0; zIdent[j]; j++){
67550     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
67551   }
67552   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
67553   if( !needQuote ){
67554     needQuote = zIdent[j];
67555   }
67556
67557   if( needQuote ) z[i++] = '"';
67558   for(j=0; zIdent[j]; j++){
67559     z[i++] = zIdent[j];
67560     if( zIdent[j]=='"' ) z[i++] = '"';
67561   }
67562   if( needQuote ) z[i++] = '"';
67563   z[i] = 0;
67564   *pIdx = i;
67565 }
67566
67567 /*
67568 ** Generate a CREATE TABLE statement appropriate for the given
67569 ** table.  Memory to hold the text of the statement is obtained
67570 ** from sqliteMalloc() and must be freed by the calling function.
67571 */
67572 static char *createTableStmt(sqlite3 *db, Table *p){
67573   int i, k, n;
67574   char *zStmt;
67575   char *zSep, *zSep2, *zEnd;
67576   Column *pCol;
67577   n = 0;
67578   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
67579     n += identLength(pCol->zName) + 5;
67580   }
67581   n += identLength(p->zName);
67582   if( n<50 ){ 
67583     zSep = "";
67584     zSep2 = ",";
67585     zEnd = ")";
67586   }else{
67587     zSep = "\n  ";
67588     zSep2 = ",\n  ";
67589     zEnd = "\n)";
67590   }
67591   n += 35 + 6*p->nCol;
67592   zStmt = sqlite3Malloc( n );
67593   if( zStmt==0 ){
67594     db->mallocFailed = 1;
67595     return 0;
67596   }
67597   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
67598   k = sqlite3Strlen30(zStmt);
67599   identPut(zStmt, &k, p->zName);
67600   zStmt[k++] = '(';
67601   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
67602     static const char * const azType[] = {
67603         /* SQLITE_AFF_TEXT    */ " TEXT",
67604         /* SQLITE_AFF_NONE    */ "",
67605         /* SQLITE_AFF_NUMERIC */ " NUM",
67606         /* SQLITE_AFF_INTEGER */ " INT",
67607         /* SQLITE_AFF_REAL    */ " REAL"
67608     };
67609     int len;
67610     const char *zType;
67611
67612     sqlite3_snprintf(n-k, &zStmt[k], zSep);
67613     k += sqlite3Strlen30(&zStmt[k]);
67614     zSep = zSep2;
67615     identPut(zStmt, &k, pCol->zName);
67616     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
67617     assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
67618     testcase( pCol->affinity==SQLITE_AFF_TEXT );
67619     testcase( pCol->affinity==SQLITE_AFF_NONE );
67620     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
67621     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
67622     testcase( pCol->affinity==SQLITE_AFF_REAL );
67623     
67624     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
67625     len = sqlite3Strlen30(zType);
67626     assert( pCol->affinity==SQLITE_AFF_NONE 
67627             || pCol->affinity==sqlite3AffinityType(zType) );
67628     memcpy(&zStmt[k], zType, len);
67629     k += len;
67630     assert( k<=n );
67631   }
67632   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
67633   return zStmt;
67634 }
67635
67636 /*
67637 ** This routine is called to report the final ")" that terminates
67638 ** a CREATE TABLE statement.
67639 **
67640 ** The table structure that other action routines have been building
67641 ** is added to the internal hash tables, assuming no errors have
67642 ** occurred.
67643 **
67644 ** An entry for the table is made in the master table on disk, unless
67645 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
67646 ** it means we are reading the sqlite_master table because we just
67647 ** connected to the database or because the sqlite_master table has
67648 ** recently changed, so the entry for this table already exists in
67649 ** the sqlite_master table.  We do not want to create it again.
67650 **
67651 ** If the pSelect argument is not NULL, it means that this routine
67652 ** was called to create a table generated from a 
67653 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
67654 ** the new table will match the result set of the SELECT.
67655 */
67656 SQLITE_PRIVATE void sqlite3EndTable(
67657   Parse *pParse,          /* Parse context */
67658   Token *pCons,           /* The ',' token after the last column defn. */
67659   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
67660   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
67661 ){
67662   Table *p;
67663   sqlite3 *db = pParse->db;
67664   int iDb;
67665
67666   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
67667     return;
67668   }
67669   p = pParse->pNewTable;
67670   if( p==0 ) return;
67671
67672   assert( !db->init.busy || !pSelect );
67673
67674   iDb = sqlite3SchemaToIndex(db, p->pSchema);
67675
67676 #ifndef SQLITE_OMIT_CHECK
67677   /* Resolve names in all CHECK constraint expressions.
67678   */
67679   if( p->pCheck ){
67680     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
67681     NameContext sNC;                /* Name context for pParse->pNewTable */
67682
67683     memset(&sNC, 0, sizeof(sNC));
67684     memset(&sSrc, 0, sizeof(sSrc));
67685     sSrc.nSrc = 1;
67686     sSrc.a[0].zName = p->zName;
67687     sSrc.a[0].pTab = p;
67688     sSrc.a[0].iCursor = -1;
67689     sNC.pParse = pParse;
67690     sNC.pSrcList = &sSrc;
67691     sNC.isCheck = 1;
67692     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
67693       return;
67694     }
67695   }
67696 #endif /* !defined(SQLITE_OMIT_CHECK) */
67697
67698   /* If the db->init.busy is 1 it means we are reading the SQL off the
67699   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
67700   ** So do not write to the disk again.  Extract the root page number
67701   ** for the table from the db->init.newTnum field.  (The page number
67702   ** should have been put there by the sqliteOpenCb routine.)
67703   */
67704   if( db->init.busy ){
67705     p->tnum = db->init.newTnum;
67706   }
67707
67708   /* If not initializing, then create a record for the new table
67709   ** in the SQLITE_MASTER table of the database.
67710   **
67711   ** If this is a TEMPORARY table, write the entry into the auxiliary
67712   ** file instead of into the main database file.
67713   */
67714   if( !db->init.busy ){
67715     int n;
67716     Vdbe *v;
67717     char *zType;    /* "view" or "table" */
67718     char *zType2;   /* "VIEW" or "TABLE" */
67719     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
67720
67721     v = sqlite3GetVdbe(pParse);
67722     if( NEVER(v==0) ) return;
67723
67724     sqlite3VdbeAddOp1(v, OP_Close, 0);
67725
67726     /* 
67727     ** Initialize zType for the new view or table.
67728     */
67729     if( p->pSelect==0 ){
67730       /* A regular table */
67731       zType = "table";
67732       zType2 = "TABLE";
67733 #ifndef SQLITE_OMIT_VIEW
67734     }else{
67735       /* A view */
67736       zType = "view";
67737       zType2 = "VIEW";
67738 #endif
67739     }
67740
67741     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
67742     ** statement to populate the new table. The root-page number for the
67743     ** new table is in register pParse->regRoot.
67744     **
67745     ** Once the SELECT has been coded by sqlite3Select(), it is in a
67746     ** suitable state to query for the column names and types to be used
67747     ** by the new table.
67748     **
67749     ** A shared-cache write-lock is not required to write to the new table,
67750     ** as a schema-lock must have already been obtained to create it. Since
67751     ** a schema-lock excludes all other database users, the write-lock would
67752     ** be redundant.
67753     */
67754     if( pSelect ){
67755       SelectDest dest;
67756       Table *pSelTab;
67757
67758       assert(pParse->nTab==1);
67759       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
67760       sqlite3VdbeChangeP5(v, 1);
67761       pParse->nTab = 2;
67762       sqlite3SelectDestInit(&dest, SRT_Table, 1);
67763       sqlite3Select(pParse, pSelect, &dest);
67764       sqlite3VdbeAddOp1(v, OP_Close, 1);
67765       if( pParse->nErr==0 ){
67766         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
67767         if( pSelTab==0 ) return;
67768         assert( p->aCol==0 );
67769         p->nCol = pSelTab->nCol;
67770         p->aCol = pSelTab->aCol;
67771         pSelTab->nCol = 0;
67772         pSelTab->aCol = 0;
67773         sqlite3DeleteTable(pSelTab);
67774       }
67775     }
67776
67777     /* Compute the complete text of the CREATE statement */
67778     if( pSelect ){
67779       zStmt = createTableStmt(db, p);
67780     }else{
67781       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
67782       zStmt = sqlite3MPrintf(db, 
67783           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
67784       );
67785     }
67786
67787     /* A slot for the record has already been allocated in the 
67788     ** SQLITE_MASTER table.  We just need to update that slot with all
67789     ** the information we've collected.
67790     */
67791     sqlite3NestedParse(pParse,
67792       "UPDATE %Q.%s "
67793          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
67794        "WHERE rowid=#%d",
67795       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
67796       zType,
67797       p->zName,
67798       p->zName,
67799       pParse->regRoot,
67800       zStmt,
67801       pParse->regRowid
67802     );
67803     sqlite3DbFree(db, zStmt);
67804     sqlite3ChangeCookie(pParse, iDb);
67805
67806 #ifndef SQLITE_OMIT_AUTOINCREMENT
67807     /* Check to see if we need to create an sqlite_sequence table for
67808     ** keeping track of autoincrement keys.
67809     */
67810     if( p->tabFlags & TF_Autoincrement ){
67811       Db *pDb = &db->aDb[iDb];
67812       if( pDb->pSchema->pSeqTab==0 ){
67813         sqlite3NestedParse(pParse,
67814           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
67815           pDb->zName
67816         );
67817       }
67818     }
67819 #endif
67820
67821     /* Reparse everything to update our internal data structures */
67822     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
67823         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
67824   }
67825
67826
67827   /* Add the table to the in-memory representation of the database.
67828   */
67829   if( db->init.busy ){
67830     Table *pOld;
67831     Schema *pSchema = p->pSchema;
67832     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
67833                              sqlite3Strlen30(p->zName),p);
67834     if( pOld ){
67835       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
67836       db->mallocFailed = 1;
67837       return;
67838     }
67839     pParse->pNewTable = 0;
67840     db->nTable++;
67841     db->flags |= SQLITE_InternChanges;
67842
67843 #ifndef SQLITE_OMIT_ALTERTABLE
67844     if( !p->pSelect ){
67845       const char *zName = (const char *)pParse->sNameToken.z;
67846       int nName;
67847       assert( !pSelect && pCons && pEnd );
67848       if( pCons->z==0 ){
67849         pCons = pEnd;
67850       }
67851       nName = (int)((const char *)pCons->z - zName);
67852       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
67853     }
67854 #endif
67855   }
67856 }
67857
67858 #ifndef SQLITE_OMIT_VIEW
67859 /*
67860 ** The parser calls this routine in order to create a new VIEW
67861 */
67862 SQLITE_PRIVATE void sqlite3CreateView(
67863   Parse *pParse,     /* The parsing context */
67864   Token *pBegin,     /* The CREATE token that begins the statement */
67865   Token *pName1,     /* The token that holds the name of the view */
67866   Token *pName2,     /* The token that holds the name of the view */
67867   Select *pSelect,   /* A SELECT statement that will become the new view */
67868   int isTemp,        /* TRUE for a TEMPORARY view */
67869   int noErr          /* Suppress error messages if VIEW already exists */
67870 ){
67871   Table *p;
67872   int n;
67873   const char *z;
67874   Token sEnd;
67875   DbFixer sFix;
67876   Token *pName;
67877   int iDb;
67878   sqlite3 *db = pParse->db;
67879
67880   if( pParse->nVar>0 ){
67881     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
67882     sqlite3SelectDelete(db, pSelect);
67883     return;
67884   }
67885   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
67886   p = pParse->pNewTable;
67887   if( p==0 ){
67888     sqlite3SelectDelete(db, pSelect);
67889     return;
67890   }
67891   assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
67892                              ** there could not have been an error */
67893   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
67894   iDb = sqlite3SchemaToIndex(db, p->pSchema);
67895   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
67896     && sqlite3FixSelect(&sFix, pSelect)
67897   ){
67898     sqlite3SelectDelete(db, pSelect);
67899     return;
67900   }
67901
67902   /* Make a copy of the entire SELECT statement that defines the view.
67903   ** This will force all the Expr.token.z values to be dynamically
67904   ** allocated rather than point to the input string - which means that
67905   ** they will persist after the current sqlite3_exec() call returns.
67906   */
67907   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
67908   sqlite3SelectDelete(db, pSelect);
67909   if( db->mallocFailed ){
67910     return;
67911   }
67912   if( !db->init.busy ){
67913     sqlite3ViewGetColumnNames(pParse, p);
67914   }
67915
67916   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
67917   ** the end.
67918   */
67919   sEnd = pParse->sLastToken;
67920   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
67921     sEnd.z += sEnd.n;
67922   }
67923   sEnd.n = 0;
67924   n = (int)(sEnd.z - pBegin->z);
67925   z = pBegin->z;
67926   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
67927   sEnd.z = &z[n-1];
67928   sEnd.n = 1;
67929
67930   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
67931   sqlite3EndTable(pParse, 0, &sEnd, 0);
67932   return;
67933 }
67934 #endif /* SQLITE_OMIT_VIEW */
67935
67936 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
67937 /*
67938 ** The Table structure pTable is really a VIEW.  Fill in the names of
67939 ** the columns of the view in the pTable structure.  Return the number
67940 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
67941 */
67942 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
67943   Table *pSelTab;   /* A fake table from which we get the result set */
67944   Select *pSel;     /* Copy of the SELECT that implements the view */
67945   int nErr = 0;     /* Number of errors encountered */
67946   int n;            /* Temporarily holds the number of cursors assigned */
67947   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
67948   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
67949
67950   assert( pTable );
67951
67952 #ifndef SQLITE_OMIT_VIRTUALTABLE
67953   if( sqlite3VtabCallConnect(pParse, pTable) ){
67954     return SQLITE_ERROR;
67955   }
67956   if( IsVirtual(pTable) ) return 0;
67957 #endif
67958
67959 #ifndef SQLITE_OMIT_VIEW
67960   /* A positive nCol means the columns names for this view are
67961   ** already known.
67962   */
67963   if( pTable->nCol>0 ) return 0;
67964
67965   /* A negative nCol is a special marker meaning that we are currently
67966   ** trying to compute the column names.  If we enter this routine with
67967   ** a negative nCol, it means two or more views form a loop, like this:
67968   **
67969   **     CREATE VIEW one AS SELECT * FROM two;
67970   **     CREATE VIEW two AS SELECT * FROM one;
67971   **
67972   ** Actually, the error above is now caught prior to reaching this point.
67973   ** But the following test is still important as it does come up
67974   ** in the following:
67975   ** 
67976   **     CREATE TABLE main.ex1(a);
67977   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
67978   **     SELECT * FROM temp.ex1;
67979   */
67980   if( pTable->nCol<0 ){
67981     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
67982     return 1;
67983   }
67984   assert( pTable->nCol>=0 );
67985
67986   /* If we get this far, it means we need to compute the table names.
67987   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
67988   ** "*" elements in the results set of the view and will assign cursors
67989   ** to the elements of the FROM clause.  But we do not want these changes
67990   ** to be permanent.  So the computation is done on a copy of the SELECT
67991   ** statement that defines the view.
67992   */
67993   assert( pTable->pSelect );
67994   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
67995   if( pSel ){
67996     u8 enableLookaside = db->lookaside.bEnabled;
67997     n = pParse->nTab;
67998     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
67999     pTable->nCol = -1;
68000     db->lookaside.bEnabled = 0;
68001 #ifndef SQLITE_OMIT_AUTHORIZATION
68002     xAuth = db->xAuth;
68003     db->xAuth = 0;
68004     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
68005     db->xAuth = xAuth;
68006 #else
68007     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
68008 #endif
68009     db->lookaside.bEnabled = enableLookaside;
68010     pParse->nTab = n;
68011     if( pSelTab ){
68012       assert( pTable->aCol==0 );
68013       pTable->nCol = pSelTab->nCol;
68014       pTable->aCol = pSelTab->aCol;
68015       pSelTab->nCol = 0;
68016       pSelTab->aCol = 0;
68017       sqlite3DeleteTable(pSelTab);
68018       pTable->pSchema->flags |= DB_UnresetViews;
68019     }else{
68020       pTable->nCol = 0;
68021       nErr++;
68022     }
68023     sqlite3SelectDelete(db, pSel);
68024   } else {
68025     nErr++;
68026   }
68027 #endif /* SQLITE_OMIT_VIEW */
68028   return nErr;  
68029 }
68030 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
68031
68032 #ifndef SQLITE_OMIT_VIEW
68033 /*
68034 ** Clear the column names from every VIEW in database idx.
68035 */
68036 static void sqliteViewResetAll(sqlite3 *db, int idx){
68037   HashElem *i;
68038   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
68039   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
68040     Table *pTab = sqliteHashData(i);
68041     if( pTab->pSelect ){
68042       sqliteResetColumnNames(pTab);
68043     }
68044   }
68045   DbClearProperty(db, idx, DB_UnresetViews);
68046 }
68047 #else
68048 # define sqliteViewResetAll(A,B)
68049 #endif /* SQLITE_OMIT_VIEW */
68050
68051 /*
68052 ** This function is called by the VDBE to adjust the internal schema
68053 ** used by SQLite when the btree layer moves a table root page. The
68054 ** root-page of a table or index in database iDb has changed from iFrom
68055 ** to iTo.
68056 **
68057 ** Ticket #1728:  The symbol table might still contain information
68058 ** on tables and/or indices that are the process of being deleted.
68059 ** If you are unlucky, one of those deleted indices or tables might
68060 ** have the same rootpage number as the real table or index that is
68061 ** being moved.  So we cannot stop searching after the first match 
68062 ** because the first match might be for one of the deleted indices
68063 ** or tables and not the table/index that is actually being moved.
68064 ** We must continue looping until all tables and indices with
68065 ** rootpage==iFrom have been converted to have a rootpage of iTo
68066 ** in order to be certain that we got the right one.
68067 */
68068 #ifndef SQLITE_OMIT_AUTOVACUUM
68069 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
68070   HashElem *pElem;
68071   Hash *pHash;
68072
68073   pHash = &pDb->pSchema->tblHash;
68074   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
68075     Table *pTab = sqliteHashData(pElem);
68076     if( pTab->tnum==iFrom ){
68077       pTab->tnum = iTo;
68078     }
68079   }
68080   pHash = &pDb->pSchema->idxHash;
68081   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
68082     Index *pIdx = sqliteHashData(pElem);
68083     if( pIdx->tnum==iFrom ){
68084       pIdx->tnum = iTo;
68085     }
68086   }
68087 }
68088 #endif
68089
68090 /*
68091 ** Write code to erase the table with root-page iTable from database iDb.
68092 ** Also write code to modify the sqlite_master table and internal schema
68093 ** if a root-page of another table is moved by the btree-layer whilst
68094 ** erasing iTable (this can happen with an auto-vacuum database).
68095 */ 
68096 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
68097   Vdbe *v = sqlite3GetVdbe(pParse);
68098   int r1 = sqlite3GetTempReg(pParse);
68099   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
68100   sqlite3MayAbort(pParse);
68101 #ifndef SQLITE_OMIT_AUTOVACUUM
68102   /* OP_Destroy stores an in integer r1. If this integer
68103   ** is non-zero, then it is the root page number of a table moved to
68104   ** location iTable. The following code modifies the sqlite_master table to
68105   ** reflect this.
68106   **
68107   ** The "#NNN" in the SQL is a special constant that means whatever value
68108   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
68109   ** token for additional information.
68110   */
68111   sqlite3NestedParse(pParse, 
68112      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
68113      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
68114 #endif
68115   sqlite3ReleaseTempReg(pParse, r1);
68116 }
68117
68118 /*
68119 ** Write VDBE code to erase table pTab and all associated indices on disk.
68120 ** Code to update the sqlite_master tables and internal schema definitions
68121 ** in case a root-page belonging to another table is moved by the btree layer
68122 ** is also added (this can happen with an auto-vacuum database).
68123 */
68124 static void destroyTable(Parse *pParse, Table *pTab){
68125 #ifdef SQLITE_OMIT_AUTOVACUUM
68126   Index *pIdx;
68127   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
68128   destroyRootPage(pParse, pTab->tnum, iDb);
68129   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68130     destroyRootPage(pParse, pIdx->tnum, iDb);
68131   }
68132 #else
68133   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
68134   ** is not defined), then it is important to call OP_Destroy on the
68135   ** table and index root-pages in order, starting with the numerically 
68136   ** largest root-page number. This guarantees that none of the root-pages
68137   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
68138   ** following were coded:
68139   **
68140   ** OP_Destroy 4 0
68141   ** ...
68142   ** OP_Destroy 5 0
68143   **
68144   ** and root page 5 happened to be the largest root-page number in the
68145   ** database, then root page 5 would be moved to page 4 by the 
68146   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
68147   ** a free-list page.
68148   */
68149   int iTab = pTab->tnum;
68150   int iDestroyed = 0;
68151
68152   while( 1 ){
68153     Index *pIdx;
68154     int iLargest = 0;
68155
68156     if( iDestroyed==0 || iTab<iDestroyed ){
68157       iLargest = iTab;
68158     }
68159     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68160       int iIdx = pIdx->tnum;
68161       assert( pIdx->pSchema==pTab->pSchema );
68162       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
68163         iLargest = iIdx;
68164       }
68165     }
68166     if( iLargest==0 ){
68167       return;
68168     }else{
68169       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
68170       destroyRootPage(pParse, iLargest, iDb);
68171       iDestroyed = iLargest;
68172     }
68173   }
68174 #endif
68175 }
68176
68177 /*
68178 ** This routine is called to do the work of a DROP TABLE statement.
68179 ** pName is the name of the table to be dropped.
68180 */
68181 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
68182   Table *pTab;
68183   Vdbe *v;
68184   sqlite3 *db = pParse->db;
68185   int iDb;
68186
68187   if( db->mallocFailed ){
68188     goto exit_drop_table;
68189   }
68190   assert( pParse->nErr==0 );
68191   assert( pName->nSrc==1 );
68192   pTab = sqlite3LocateTable(pParse, isView, 
68193                             pName->a[0].zName, pName->a[0].zDatabase);
68194
68195   if( pTab==0 ){
68196     if( noErr ){
68197       sqlite3ErrorClear(pParse);
68198     }
68199     goto exit_drop_table;
68200   }
68201   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68202   assert( iDb>=0 && iDb<db->nDb );
68203
68204   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
68205   ** it is initialized.
68206   */
68207   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
68208     goto exit_drop_table;
68209   }
68210 #ifndef SQLITE_OMIT_AUTHORIZATION
68211   {
68212     int code;
68213     const char *zTab = SCHEMA_TABLE(iDb);
68214     const char *zDb = db->aDb[iDb].zName;
68215     const char *zArg2 = 0;
68216     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
68217       goto exit_drop_table;
68218     }
68219     if( isView ){
68220       if( !OMIT_TEMPDB && iDb==1 ){
68221         code = SQLITE_DROP_TEMP_VIEW;
68222       }else{
68223         code = SQLITE_DROP_VIEW;
68224       }
68225 #ifndef SQLITE_OMIT_VIRTUALTABLE
68226     }else if( IsVirtual(pTab) ){
68227       code = SQLITE_DROP_VTABLE;
68228       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
68229 #endif
68230     }else{
68231       if( !OMIT_TEMPDB && iDb==1 ){
68232         code = SQLITE_DROP_TEMP_TABLE;
68233       }else{
68234         code = SQLITE_DROP_TABLE;
68235       }
68236     }
68237     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
68238       goto exit_drop_table;
68239     }
68240     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
68241       goto exit_drop_table;
68242     }
68243   }
68244 #endif
68245   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
68246     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
68247     goto exit_drop_table;
68248   }
68249
68250 #ifndef SQLITE_OMIT_VIEW
68251   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
68252   ** on a table.
68253   */
68254   if( isView && pTab->pSelect==0 ){
68255     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
68256     goto exit_drop_table;
68257   }
68258   if( !isView && pTab->pSelect ){
68259     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
68260     goto exit_drop_table;
68261   }
68262 #endif
68263
68264   /* Generate code to remove the table from the master table
68265   ** on disk.
68266   */
68267   v = sqlite3GetVdbe(pParse);
68268   if( v ){
68269     Trigger *pTrigger;
68270     Db *pDb = &db->aDb[iDb];
68271     sqlite3BeginWriteOperation(pParse, 1, iDb);
68272
68273 #ifndef SQLITE_OMIT_VIRTUALTABLE
68274     if( IsVirtual(pTab) ){
68275       sqlite3VdbeAddOp0(v, OP_VBegin);
68276     }
68277 #endif
68278     sqlite3FkDropTable(pParse, pName, pTab);
68279
68280     /* Drop all triggers associated with the table being dropped. Code
68281     ** is generated to remove entries from sqlite_master and/or
68282     ** sqlite_temp_master if required.
68283     */
68284     pTrigger = sqlite3TriggerList(pParse, pTab);
68285     while( pTrigger ){
68286       assert( pTrigger->pSchema==pTab->pSchema || 
68287           pTrigger->pSchema==db->aDb[1].pSchema );
68288       sqlite3DropTriggerPtr(pParse, pTrigger);
68289       pTrigger = pTrigger->pNext;
68290     }
68291
68292 #ifndef SQLITE_OMIT_AUTOINCREMENT
68293     /* Remove any entries of the sqlite_sequence table associated with
68294     ** the table being dropped. This is done before the table is dropped
68295     ** at the btree level, in case the sqlite_sequence table needs to
68296     ** move as a result of the drop (can happen in auto-vacuum mode).
68297     */
68298     if( pTab->tabFlags & TF_Autoincrement ){
68299       sqlite3NestedParse(pParse,
68300         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
68301         pDb->zName, pTab->zName
68302       );
68303     }
68304 #endif
68305
68306     /* Drop all SQLITE_MASTER table and index entries that refer to the
68307     ** table. The program name loops through the master table and deletes
68308     ** every row that refers to a table of the same name as the one being
68309     ** dropped. Triggers are handled seperately because a trigger can be
68310     ** created in the temp database that refers to a table in another
68311     ** database.
68312     */
68313     sqlite3NestedParse(pParse, 
68314         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
68315         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
68316
68317     /* Drop any statistics from the sqlite_stat1 table, if it exists */
68318     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
68319       sqlite3NestedParse(pParse,
68320         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
68321       );
68322     }
68323
68324     if( !isView && !IsVirtual(pTab) ){
68325       destroyTable(pParse, pTab);
68326     }
68327
68328     /* Remove the table entry from SQLite's internal schema and modify
68329     ** the schema cookie.
68330     */
68331     if( IsVirtual(pTab) ){
68332       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
68333     }
68334     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
68335     sqlite3ChangeCookie(pParse, iDb);
68336   }
68337   sqliteViewResetAll(db, iDb);
68338
68339 exit_drop_table:
68340   sqlite3SrcListDelete(db, pName);
68341 }
68342
68343 /*
68344 ** This routine is called to create a new foreign key on the table
68345 ** currently under construction.  pFromCol determines which columns
68346 ** in the current table point to the foreign key.  If pFromCol==0 then
68347 ** connect the key to the last column inserted.  pTo is the name of
68348 ** the table referred to.  pToCol is a list of tables in the other
68349 ** pTo table that the foreign key points to.  flags contains all
68350 ** information about the conflict resolution algorithms specified
68351 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
68352 **
68353 ** An FKey structure is created and added to the table currently
68354 ** under construction in the pParse->pNewTable field.
68355 **
68356 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
68357 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
68358 */
68359 SQLITE_PRIVATE void sqlite3CreateForeignKey(
68360   Parse *pParse,       /* Parsing context */
68361   ExprList *pFromCol,  /* Columns in this table that point to other table */
68362   Token *pTo,          /* Name of the other table */
68363   ExprList *pToCol,    /* Columns in the other table */
68364   int flags            /* Conflict resolution algorithms. */
68365 ){
68366   sqlite3 *db = pParse->db;
68367 #ifndef SQLITE_OMIT_FOREIGN_KEY
68368   FKey *pFKey = 0;
68369   FKey *pNextTo;
68370   Table *p = pParse->pNewTable;
68371   int nByte;
68372   int i;
68373   int nCol;
68374   char *z;
68375
68376   assert( pTo!=0 );
68377   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
68378   if( pFromCol==0 ){
68379     int iCol = p->nCol-1;
68380     if( NEVER(iCol<0) ) goto fk_end;
68381     if( pToCol && pToCol->nExpr!=1 ){
68382       sqlite3ErrorMsg(pParse, "foreign key on %s"
68383          " should reference only one column of table %T",
68384          p->aCol[iCol].zName, pTo);
68385       goto fk_end;
68386     }
68387     nCol = 1;
68388   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
68389     sqlite3ErrorMsg(pParse,
68390         "number of columns in foreign key does not match the number of "
68391         "columns in the referenced table");
68392     goto fk_end;
68393   }else{
68394     nCol = pFromCol->nExpr;
68395   }
68396   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
68397   if( pToCol ){
68398     for(i=0; i<pToCol->nExpr; i++){
68399       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
68400     }
68401   }
68402   pFKey = sqlite3DbMallocZero(db, nByte );
68403   if( pFKey==0 ){
68404     goto fk_end;
68405   }
68406   pFKey->pFrom = p;
68407   pFKey->pNextFrom = p->pFKey;
68408   z = (char*)&pFKey->aCol[nCol];
68409   pFKey->zTo = z;
68410   memcpy(z, pTo->z, pTo->n);
68411   z[pTo->n] = 0;
68412   sqlite3Dequote(z);
68413   z += pTo->n+1;
68414   pFKey->nCol = nCol;
68415   if( pFromCol==0 ){
68416     pFKey->aCol[0].iFrom = p->nCol-1;
68417   }else{
68418     for(i=0; i<nCol; i++){
68419       int j;
68420       for(j=0; j<p->nCol; j++){
68421         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
68422           pFKey->aCol[i].iFrom = j;
68423           break;
68424         }
68425       }
68426       if( j>=p->nCol ){
68427         sqlite3ErrorMsg(pParse, 
68428           "unknown column \"%s\" in foreign key definition", 
68429           pFromCol->a[i].zName);
68430         goto fk_end;
68431       }
68432     }
68433   }
68434   if( pToCol ){
68435     for(i=0; i<nCol; i++){
68436       int n = sqlite3Strlen30(pToCol->a[i].zName);
68437       pFKey->aCol[i].zCol = z;
68438       memcpy(z, pToCol->a[i].zName, n);
68439       z[n] = 0;
68440       z += n+1;
68441     }
68442   }
68443   pFKey->isDeferred = 0;
68444   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
68445   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
68446
68447   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
68448       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
68449   );
68450   if( pNextTo==pFKey ){
68451     db->mallocFailed = 1;
68452     goto fk_end;
68453   }
68454   if( pNextTo ){
68455     assert( pNextTo->pPrevTo==0 );
68456     pFKey->pNextTo = pNextTo;
68457     pNextTo->pPrevTo = pFKey;
68458   }
68459
68460   /* Link the foreign key to the table as the last step.
68461   */
68462   p->pFKey = pFKey;
68463   pFKey = 0;
68464
68465 fk_end:
68466   sqlite3DbFree(db, pFKey);
68467 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
68468   sqlite3ExprListDelete(db, pFromCol);
68469   sqlite3ExprListDelete(db, pToCol);
68470 }
68471
68472 /*
68473 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
68474 ** clause is seen as part of a foreign key definition.  The isDeferred
68475 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
68476 ** The behavior of the most recently created foreign key is adjusted
68477 ** accordingly.
68478 */
68479 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
68480 #ifndef SQLITE_OMIT_FOREIGN_KEY
68481   Table *pTab;
68482   FKey *pFKey;
68483   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
68484   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
68485   pFKey->isDeferred = (u8)isDeferred;
68486 #endif
68487 }
68488
68489 /*
68490 ** Generate code that will erase and refill index *pIdx.  This is
68491 ** used to initialize a newly created index or to recompute the
68492 ** content of an index in response to a REINDEX command.
68493 **
68494 ** if memRootPage is not negative, it means that the index is newly
68495 ** created.  The register specified by memRootPage contains the
68496 ** root page number of the index.  If memRootPage is negative, then
68497 ** the index already exists and must be cleared before being refilled and
68498 ** the root page number of the index is taken from pIndex->tnum.
68499 */
68500 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
68501   Table *pTab = pIndex->pTable;  /* The table that is indexed */
68502   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
68503   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
68504   int addr1;                     /* Address of top of loop */
68505   int tnum;                      /* Root page of index */
68506   Vdbe *v;                       /* Generate code into this virtual machine */
68507   KeyInfo *pKey;                 /* KeyInfo for index */
68508   int regIdxKey;                 /* Registers containing the index key */
68509   int regRecord;                 /* Register holding assemblied index record */
68510   sqlite3 *db = pParse->db;      /* The database connection */
68511   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
68512
68513 #ifndef SQLITE_OMIT_AUTHORIZATION
68514   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
68515       db->aDb[iDb].zName ) ){
68516     return;
68517   }
68518 #endif
68519
68520   /* Require a write-lock on the table to perform this operation */
68521   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
68522
68523   v = sqlite3GetVdbe(pParse);
68524   if( v==0 ) return;
68525   if( memRootPage>=0 ){
68526     tnum = memRootPage;
68527   }else{
68528     tnum = pIndex->tnum;
68529     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
68530   }
68531   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
68532   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
68533                     (char *)pKey, P4_KEYINFO_HANDOFF);
68534   if( memRootPage>=0 ){
68535     sqlite3VdbeChangeP5(v, 1);
68536   }
68537   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
68538   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
68539   regRecord = sqlite3GetTempReg(pParse);
68540   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
68541   if( pIndex->onError!=OE_None ){
68542     const int regRowid = regIdxKey + pIndex->nColumn;
68543     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
68544     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
68545
68546     /* The registers accessed by the OP_IsUnique opcode were allocated
68547     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
68548     ** call above. Just before that function was freed they were released
68549     ** (made available to the compiler for reuse) using 
68550     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
68551     ** opcode use the values stored within seems dangerous. However, since
68552     ** we can be sure that no other temp registers have been allocated
68553     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
68554     */
68555     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
68556     sqlite3HaltConstraint(
68557         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
68558   }
68559   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
68560   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
68561   sqlite3ReleaseTempReg(pParse, regRecord);
68562   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
68563   sqlite3VdbeJumpHere(v, addr1);
68564   sqlite3VdbeAddOp1(v, OP_Close, iTab);
68565   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
68566 }
68567
68568 /*
68569 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
68570 ** and pTblList is the name of the table that is to be indexed.  Both will 
68571 ** be NULL for a primary key or an index that is created to satisfy a
68572 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
68573 ** as the table to be indexed.  pParse->pNewTable is a table that is
68574 ** currently being constructed by a CREATE TABLE statement.
68575 **
68576 ** pList is a list of columns to be indexed.  pList will be NULL if this
68577 ** is a primary key or unique-constraint on the most recent column added
68578 ** to the table currently under construction.  
68579 **
68580 ** If the index is created successfully, return a pointer to the new Index
68581 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
68582 ** as the tables primary key (Index.autoIndex==2).
68583 */
68584 SQLITE_PRIVATE Index *sqlite3CreateIndex(
68585   Parse *pParse,     /* All information about this parse */
68586   Token *pName1,     /* First part of index name. May be NULL */
68587   Token *pName2,     /* Second part of index name. May be NULL */
68588   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
68589   ExprList *pList,   /* A list of columns to be indexed */
68590   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
68591   Token *pStart,     /* The CREATE token that begins this statement */
68592   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
68593   int sortOrder,     /* Sort order of primary key when pList==NULL */
68594   int ifNotExist     /* Omit error if index already exists */
68595 ){
68596   Index *pRet = 0;     /* Pointer to return */
68597   Table *pTab = 0;     /* Table to be indexed */
68598   Index *pIndex = 0;   /* The index to be created */
68599   char *zName = 0;     /* Name of the index */
68600   int nName;           /* Number of characters in zName */
68601   int i, j;
68602   Token nullId;        /* Fake token for an empty ID list */
68603   DbFixer sFix;        /* For assigning database names to pTable */
68604   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
68605   sqlite3 *db = pParse->db;
68606   Db *pDb;             /* The specific table containing the indexed database */
68607   int iDb;             /* Index of the database that is being written */
68608   Token *pName = 0;    /* Unqualified name of the index to create */
68609   struct ExprList_item *pListItem; /* For looping over pList */
68610   int nCol;
68611   int nExtra = 0;
68612   char *zExtra;
68613
68614   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
68615   assert( pParse->nErr==0 );      /* Never called with prior errors */
68616   if( db->mallocFailed || IN_DECLARE_VTAB ){
68617     goto exit_create_index;
68618   }
68619   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
68620     goto exit_create_index;
68621   }
68622
68623   /*
68624   ** Find the table that is to be indexed.  Return early if not found.
68625   */
68626   if( pTblName!=0 ){
68627
68628     /* Use the two-part index name to determine the database 
68629     ** to search for the table. 'Fix' the table name to this db
68630     ** before looking up the table.
68631     */
68632     assert( pName1 && pName2 );
68633     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
68634     if( iDb<0 ) goto exit_create_index;
68635
68636 #ifndef SQLITE_OMIT_TEMPDB
68637     /* If the index name was unqualified, check if the the table
68638     ** is a temp table. If so, set the database to 1. Do not do this
68639     ** if initialising a database schema.
68640     */
68641     if( !db->init.busy ){
68642       pTab = sqlite3SrcListLookup(pParse, pTblName);
68643       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
68644         iDb = 1;
68645       }
68646     }
68647 #endif
68648
68649     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
68650         sqlite3FixSrcList(&sFix, pTblName)
68651     ){
68652       /* Because the parser constructs pTblName from a single identifier,
68653       ** sqlite3FixSrcList can never fail. */
68654       assert(0);
68655     }
68656     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
68657         pTblName->a[0].zDatabase);
68658     if( !pTab || db->mallocFailed ) goto exit_create_index;
68659     assert( db->aDb[iDb].pSchema==pTab->pSchema );
68660   }else{
68661     assert( pName==0 );
68662     pTab = pParse->pNewTable;
68663     if( !pTab ) goto exit_create_index;
68664     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68665   }
68666   pDb = &db->aDb[iDb];
68667
68668   assert( pTab!=0 );
68669   assert( pParse->nErr==0 );
68670   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
68671        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
68672     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
68673     goto exit_create_index;
68674   }
68675 #ifndef SQLITE_OMIT_VIEW
68676   if( pTab->pSelect ){
68677     sqlite3ErrorMsg(pParse, "views may not be indexed");
68678     goto exit_create_index;
68679   }
68680 #endif
68681 #ifndef SQLITE_OMIT_VIRTUALTABLE
68682   if( IsVirtual(pTab) ){
68683     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
68684     goto exit_create_index;
68685   }
68686 #endif
68687
68688   /*
68689   ** Find the name of the index.  Make sure there is not already another
68690   ** index or table with the same name.  
68691   **
68692   ** Exception:  If we are reading the names of permanent indices from the
68693   ** sqlite_master table (because some other process changed the schema) and
68694   ** one of the index names collides with the name of a temporary table or
68695   ** index, then we will continue to process this index.
68696   **
68697   ** If pName==0 it means that we are
68698   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
68699   ** own name.
68700   */
68701   if( pName ){
68702     zName = sqlite3NameFromToken(db, pName);
68703     if( zName==0 ) goto exit_create_index;
68704     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
68705       goto exit_create_index;
68706     }
68707     if( !db->init.busy ){
68708       if( sqlite3FindTable(db, zName, 0)!=0 ){
68709         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
68710         goto exit_create_index;
68711       }
68712     }
68713     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
68714       if( !ifNotExist ){
68715         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
68716       }
68717       goto exit_create_index;
68718     }
68719   }else{
68720     int n;
68721     Index *pLoop;
68722     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
68723     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
68724     if( zName==0 ){
68725       goto exit_create_index;
68726     }
68727   }
68728
68729   /* Check for authorization to create an index.
68730   */
68731 #ifndef SQLITE_OMIT_AUTHORIZATION
68732   {
68733     const char *zDb = pDb->zName;
68734     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
68735       goto exit_create_index;
68736     }
68737     i = SQLITE_CREATE_INDEX;
68738     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
68739     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
68740       goto exit_create_index;
68741     }
68742   }
68743 #endif
68744
68745   /* If pList==0, it means this routine was called to make a primary
68746   ** key out of the last column added to the table under construction.
68747   ** So create a fake list to simulate this.
68748   */
68749   if( pList==0 ){
68750     nullId.z = pTab->aCol[pTab->nCol-1].zName;
68751     nullId.n = sqlite3Strlen30((char*)nullId.z);
68752     pList = sqlite3ExprListAppend(pParse, 0, 0);
68753     if( pList==0 ) goto exit_create_index;
68754     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
68755     pList->a[0].sortOrder = (u8)sortOrder;
68756   }
68757
68758   /* Figure out how many bytes of space are required to store explicitly
68759   ** specified collation sequence names.
68760   */
68761   for(i=0; i<pList->nExpr; i++){
68762     Expr *pExpr = pList->a[i].pExpr;
68763     if( pExpr ){
68764       CollSeq *pColl = pExpr->pColl;
68765       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
68766       ** failure we have quit before reaching this point. */
68767       if( ALWAYS(pColl) ){
68768         nExtra += (1 + sqlite3Strlen30(pColl->zName));
68769       }
68770     }
68771   }
68772
68773   /* 
68774   ** Allocate the index structure. 
68775   */
68776   nName = sqlite3Strlen30(zName);
68777   nCol = pList->nExpr;
68778   pIndex = sqlite3DbMallocZero(db, 
68779       sizeof(Index) +              /* Index structure  */
68780       sizeof(int)*nCol +           /* Index.aiColumn   */
68781       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
68782       sizeof(char *)*nCol +        /* Index.azColl     */
68783       sizeof(u8)*nCol +            /* Index.aSortOrder */
68784       nName + 1 +                  /* Index.zName      */
68785       nExtra                       /* Collation sequence names */
68786   );
68787   if( db->mallocFailed ){
68788     goto exit_create_index;
68789   }
68790   pIndex->azColl = (char**)(&pIndex[1]);
68791   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
68792   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
68793   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
68794   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
68795   zExtra = (char *)(&pIndex->zName[nName+1]);
68796   memcpy(pIndex->zName, zName, nName+1);
68797   pIndex->pTable = pTab;
68798   pIndex->nColumn = pList->nExpr;
68799   pIndex->onError = (u8)onError;
68800   pIndex->autoIndex = (u8)(pName==0);
68801   pIndex->pSchema = db->aDb[iDb].pSchema;
68802
68803   /* Check to see if we should honor DESC requests on index columns
68804   */
68805   if( pDb->pSchema->file_format>=4 ){
68806     sortOrderMask = -1;   /* Honor DESC */
68807   }else{
68808     sortOrderMask = 0;    /* Ignore DESC */
68809   }
68810
68811   /* Scan the names of the columns of the table to be indexed and
68812   ** load the column indices into the Index structure.  Report an error
68813   ** if any column is not found.
68814   **
68815   ** TODO:  Add a test to make sure that the same column is not named
68816   ** more than once within the same index.  Only the first instance of
68817   ** the column will ever be used by the optimizer.  Note that using the
68818   ** same column more than once cannot be an error because that would 
68819   ** break backwards compatibility - it needs to be a warning.
68820   */
68821   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
68822     const char *zColName = pListItem->zName;
68823     Column *pTabCol;
68824     int requestedSortOrder;
68825     char *zColl;                   /* Collation sequence name */
68826
68827     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
68828       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
68829     }
68830     if( j>=pTab->nCol ){
68831       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
68832         pTab->zName, zColName);
68833       goto exit_create_index;
68834     }
68835     pIndex->aiColumn[i] = j;
68836     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
68837     ** the way the "idxlist" non-terminal is constructed by the parser,
68838     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
68839     ** must exist or else there must have been an OOM error.  But if there
68840     ** was an OOM error, we would never reach this point. */
68841     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
68842       int nColl;
68843       zColl = pListItem->pExpr->pColl->zName;
68844       nColl = sqlite3Strlen30(zColl) + 1;
68845       assert( nExtra>=nColl );
68846       memcpy(zExtra, zColl, nColl);
68847       zColl = zExtra;
68848       zExtra += nColl;
68849       nExtra -= nColl;
68850     }else{
68851       zColl = pTab->aCol[j].zColl;
68852       if( !zColl ){
68853         zColl = db->pDfltColl->zName;
68854       }
68855     }
68856     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
68857       goto exit_create_index;
68858     }
68859     pIndex->azColl[i] = zColl;
68860     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
68861     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
68862   }
68863   sqlite3DefaultRowEst(pIndex);
68864
68865   if( pTab==pParse->pNewTable ){
68866     /* This routine has been called to create an automatic index as a
68867     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
68868     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
68869     ** i.e. one of:
68870     **
68871     ** CREATE TABLE t(x PRIMARY KEY, y);
68872     ** CREATE TABLE t(x, y, UNIQUE(x, y));
68873     **
68874     ** Either way, check to see if the table already has such an index. If
68875     ** so, don't bother creating this one. This only applies to
68876     ** automatically created indices. Users can do as they wish with
68877     ** explicit indices.
68878     **
68879     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
68880     ** (and thus suppressing the second one) even if they have different
68881     ** sort orders.
68882     **
68883     ** If there are different collating sequences or if the columns of
68884     ** the constraint occur in different orders, then the constraints are
68885     ** considered distinct and both result in separate indices.
68886     */
68887     Index *pIdx;
68888     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68889       int k;
68890       assert( pIdx->onError!=OE_None );
68891       assert( pIdx->autoIndex );
68892       assert( pIndex->onError!=OE_None );
68893
68894       if( pIdx->nColumn!=pIndex->nColumn ) continue;
68895       for(k=0; k<pIdx->nColumn; k++){
68896         const char *z1;
68897         const char *z2;
68898         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
68899         z1 = pIdx->azColl[k];
68900         z2 = pIndex->azColl[k];
68901         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
68902       }
68903       if( k==pIdx->nColumn ){
68904         if( pIdx->onError!=pIndex->onError ){
68905           /* This constraint creates the same index as a previous
68906           ** constraint specified somewhere in the CREATE TABLE statement.
68907           ** However the ON CONFLICT clauses are different. If both this 
68908           ** constraint and the previous equivalent constraint have explicit
68909           ** ON CONFLICT clauses this is an error. Otherwise, use the
68910           ** explicitly specified behaviour for the index.
68911           */
68912           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
68913             sqlite3ErrorMsg(pParse, 
68914                 "conflicting ON CONFLICT clauses specified", 0);
68915           }
68916           if( pIdx->onError==OE_Default ){
68917             pIdx->onError = pIndex->onError;
68918           }
68919         }
68920         goto exit_create_index;
68921       }
68922     }
68923   }
68924
68925   /* Link the new Index structure to its table and to the other
68926   ** in-memory database structures. 
68927   */
68928   if( db->init.busy ){
68929     Index *p;
68930     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
68931                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
68932                           pIndex);
68933     if( p ){
68934       assert( p==pIndex );  /* Malloc must have failed */
68935       db->mallocFailed = 1;
68936       goto exit_create_index;
68937     }
68938     db->flags |= SQLITE_InternChanges;
68939     if( pTblName!=0 ){
68940       pIndex->tnum = db->init.newTnum;
68941     }
68942   }
68943
68944   /* If the db->init.busy is 0 then create the index on disk.  This
68945   ** involves writing the index into the master table and filling in the
68946   ** index with the current table contents.
68947   **
68948   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
68949   ** command.  db->init.busy is 1 when a database is opened and 
68950   ** CREATE INDEX statements are read out of the master table.  In
68951   ** the latter case the index already exists on disk, which is why
68952   ** we don't want to recreate it.
68953   **
68954   ** If pTblName==0 it means this index is generated as a primary key
68955   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
68956   ** has just been created, it contains no data and the index initialization
68957   ** step can be skipped.
68958   */
68959   else{ /* if( db->init.busy==0 ) */
68960     Vdbe *v;
68961     char *zStmt;
68962     int iMem = ++pParse->nMem;
68963
68964     v = sqlite3GetVdbe(pParse);
68965     if( v==0 ) goto exit_create_index;
68966
68967
68968     /* Create the rootpage for the index
68969     */
68970     sqlite3BeginWriteOperation(pParse, 1, iDb);
68971     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
68972
68973     /* Gather the complete text of the CREATE INDEX statement into
68974     ** the zStmt variable
68975     */
68976     if( pStart ){
68977       assert( pEnd!=0 );
68978       /* A named index with an explicit CREATE INDEX statement */
68979       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
68980         onError==OE_None ? "" : " UNIQUE",
68981         pEnd->z - pName->z + 1,
68982         pName->z);
68983     }else{
68984       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
68985       /* zStmt = sqlite3MPrintf(""); */
68986       zStmt = 0;
68987     }
68988
68989     /* Add an entry in sqlite_master for this index
68990     */
68991     sqlite3NestedParse(pParse, 
68992         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
68993         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
68994         pIndex->zName,
68995         pTab->zName,
68996         iMem,
68997         zStmt
68998     );
68999     sqlite3DbFree(db, zStmt);
69000
69001     /* Fill the index with data and reparse the schema. Code an OP_Expire
69002     ** to invalidate all pre-compiled statements.
69003     */
69004     if( pTblName ){
69005       sqlite3RefillIndex(pParse, pIndex, iMem);
69006       sqlite3ChangeCookie(pParse, iDb);
69007       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
69008          sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
69009       sqlite3VdbeAddOp1(v, OP_Expire, 0);
69010     }
69011   }
69012
69013   /* When adding an index to the list of indices for a table, make
69014   ** sure all indices labeled OE_Replace come after all those labeled
69015   ** OE_Ignore.  This is necessary for the correct constraint check
69016   ** processing (in sqlite3GenerateConstraintChecks()) as part of
69017   ** UPDATE and INSERT statements.  
69018   */
69019   if( db->init.busy || pTblName==0 ){
69020     if( onError!=OE_Replace || pTab->pIndex==0
69021          || pTab->pIndex->onError==OE_Replace){
69022       pIndex->pNext = pTab->pIndex;
69023       pTab->pIndex = pIndex;
69024     }else{
69025       Index *pOther = pTab->pIndex;
69026       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
69027         pOther = pOther->pNext;
69028       }
69029       pIndex->pNext = pOther->pNext;
69030       pOther->pNext = pIndex;
69031     }
69032     pRet = pIndex;
69033     pIndex = 0;
69034   }
69035
69036   /* Clean up before exiting */
69037 exit_create_index:
69038   if( pIndex ){
69039     sqlite3_free(pIndex->zColAff);
69040     sqlite3DbFree(db, pIndex);
69041   }
69042   sqlite3ExprListDelete(db, pList);
69043   sqlite3SrcListDelete(db, pTblName);
69044   sqlite3DbFree(db, zName);
69045   return pRet;
69046 }
69047
69048 /*
69049 ** Fill the Index.aiRowEst[] array with default information - information
69050 ** to be used when we have not run the ANALYZE command.
69051 **
69052 ** aiRowEst[0] is suppose to contain the number of elements in the index.
69053 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
69054 ** number of rows in the table that match any particular value of the
69055 ** first column of the index.  aiRowEst[2] is an estimate of the number
69056 ** of rows that match any particular combiniation of the first 2 columns
69057 ** of the index.  And so forth.  It must always be the case that
69058 *
69059 **           aiRowEst[N]<=aiRowEst[N-1]
69060 **           aiRowEst[N]>=1
69061 **
69062 ** Apart from that, we have little to go on besides intuition as to
69063 ** how aiRowEst[] should be initialized.  The numbers generated here
69064 ** are based on typical values found in actual indices.
69065 */
69066 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
69067   unsigned *a = pIdx->aiRowEst;
69068   int i;
69069   assert( a!=0 );
69070   a[0] = 1000000;
69071   for(i=pIdx->nColumn; i>=5; i--){
69072     a[i] = 5;
69073   }
69074   while( i>=1 ){
69075     a[i] = 11 - i;
69076     i--;
69077   }
69078   if( pIdx->onError!=OE_None ){
69079     a[pIdx->nColumn] = 1;
69080   }
69081 }
69082
69083 /*
69084 ** This routine will drop an existing named index.  This routine
69085 ** implements the DROP INDEX statement.
69086 */
69087 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
69088   Index *pIndex;
69089   Vdbe *v;
69090   sqlite3 *db = pParse->db;
69091   int iDb;
69092
69093   assert( pParse->nErr==0 );   /* Never called with prior errors */
69094   if( db->mallocFailed ){
69095     goto exit_drop_index;
69096   }
69097   assert( pName->nSrc==1 );
69098   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
69099     goto exit_drop_index;
69100   }
69101   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
69102   if( pIndex==0 ){
69103     if( !ifExists ){
69104       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
69105     }
69106     pParse->checkSchema = 1;
69107     goto exit_drop_index;
69108   }
69109   if( pIndex->autoIndex ){
69110     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
69111       "or PRIMARY KEY constraint cannot be dropped", 0);
69112     goto exit_drop_index;
69113   }
69114   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
69115 #ifndef SQLITE_OMIT_AUTHORIZATION
69116   {
69117     int code = SQLITE_DROP_INDEX;
69118     Table *pTab = pIndex->pTable;
69119     const char *zDb = db->aDb[iDb].zName;
69120     const char *zTab = SCHEMA_TABLE(iDb);
69121     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
69122       goto exit_drop_index;
69123     }
69124     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
69125     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
69126       goto exit_drop_index;
69127     }
69128   }
69129 #endif
69130
69131   /* Generate code to remove the index and from the master table */
69132   v = sqlite3GetVdbe(pParse);
69133   if( v ){
69134     sqlite3BeginWriteOperation(pParse, 1, iDb);
69135     sqlite3NestedParse(pParse,
69136        "DELETE FROM %Q.%s WHERE name=%Q",
69137        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
69138        pIndex->zName
69139     );
69140     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
69141       sqlite3NestedParse(pParse,
69142         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
69143         db->aDb[iDb].zName, pIndex->zName
69144       );
69145     }
69146     sqlite3ChangeCookie(pParse, iDb);
69147     destroyRootPage(pParse, pIndex->tnum, iDb);
69148     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
69149   }
69150
69151 exit_drop_index:
69152   sqlite3SrcListDelete(db, pName);
69153 }
69154
69155 /*
69156 ** pArray is a pointer to an array of objects.  Each object in the
69157 ** array is szEntry bytes in size.  This routine allocates a new
69158 ** object on the end of the array.
69159 **
69160 ** *pnEntry is the number of entries already in use.  *pnAlloc is
69161 ** the previously allocated size of the array.  initSize is the
69162 ** suggested initial array size allocation.
69163 **
69164 ** The index of the new entry is returned in *pIdx.
69165 **
69166 ** This routine returns a pointer to the array of objects.  This
69167 ** might be the same as the pArray parameter or it might be a different
69168 ** pointer if the array was resized.
69169 */
69170 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
69171   sqlite3 *db,      /* Connection to notify of malloc failures */
69172   void *pArray,     /* Array of objects.  Might be reallocated */
69173   int szEntry,      /* Size of each object in the array */
69174   int initSize,     /* Suggested initial allocation, in elements */
69175   int *pnEntry,     /* Number of objects currently in use */
69176   int *pnAlloc,     /* Current size of the allocation, in elements */
69177   int *pIdx         /* Write the index of a new slot here */
69178 ){
69179   char *z;
69180   if( *pnEntry >= *pnAlloc ){
69181     void *pNew;
69182     int newSize;
69183     newSize = (*pnAlloc)*2 + initSize;
69184     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
69185     if( pNew==0 ){
69186       *pIdx = -1;
69187       return pArray;
69188     }
69189     *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
69190     pArray = pNew;
69191   }
69192   z = (char*)pArray;
69193   memset(&z[*pnEntry * szEntry], 0, szEntry);
69194   *pIdx = *pnEntry;
69195   ++*pnEntry;
69196   return pArray;
69197 }
69198
69199 /*
69200 ** Append a new element to the given IdList.  Create a new IdList if
69201 ** need be.
69202 **
69203 ** A new IdList is returned, or NULL if malloc() fails.
69204 */
69205 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
69206   int i;
69207   if( pList==0 ){
69208     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
69209     if( pList==0 ) return 0;
69210     pList->nAlloc = 0;
69211   }
69212   pList->a = sqlite3ArrayAllocate(
69213       db,
69214       pList->a,
69215       sizeof(pList->a[0]),
69216       5,
69217       &pList->nId,
69218       &pList->nAlloc,
69219       &i
69220   );
69221   if( i<0 ){
69222     sqlite3IdListDelete(db, pList);
69223     return 0;
69224   }
69225   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
69226   return pList;
69227 }
69228
69229 /*
69230 ** Delete an IdList.
69231 */
69232 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
69233   int i;
69234   if( pList==0 ) return;
69235   for(i=0; i<pList->nId; i++){
69236     sqlite3DbFree(db, pList->a[i].zName);
69237   }
69238   sqlite3DbFree(db, pList->a);
69239   sqlite3DbFree(db, pList);
69240 }
69241
69242 /*
69243 ** Return the index in pList of the identifier named zId.  Return -1
69244 ** if not found.
69245 */
69246 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
69247   int i;
69248   if( pList==0 ) return -1;
69249   for(i=0; i<pList->nId; i++){
69250     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
69251   }
69252   return -1;
69253 }
69254
69255 /*
69256 ** Expand the space allocated for the given SrcList object by
69257 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
69258 ** New slots are zeroed.
69259 **
69260 ** For example, suppose a SrcList initially contains two entries: A,B.
69261 ** To append 3 new entries onto the end, do this:
69262 **
69263 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
69264 **
69265 ** After the call above it would contain:  A, B, nil, nil, nil.
69266 ** If the iStart argument had been 1 instead of 2, then the result
69267 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
69268 ** the iStart value would be 0.  The result then would
69269 ** be: nil, nil, nil, A, B.
69270 **
69271 ** If a memory allocation fails the SrcList is unchanged.  The
69272 ** db->mallocFailed flag will be set to true.
69273 */
69274 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
69275   sqlite3 *db,       /* Database connection to notify of OOM errors */
69276   SrcList *pSrc,     /* The SrcList to be enlarged */
69277   int nExtra,        /* Number of new slots to add to pSrc->a[] */
69278   int iStart         /* Index in pSrc->a[] of first new slot */
69279 ){
69280   int i;
69281
69282   /* Sanity checking on calling parameters */
69283   assert( iStart>=0 );
69284   assert( nExtra>=1 );
69285   assert( pSrc!=0 );
69286   assert( iStart<=pSrc->nSrc );
69287
69288   /* Allocate additional space if needed */
69289   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
69290     SrcList *pNew;
69291     int nAlloc = pSrc->nSrc+nExtra;
69292     int nGot;
69293     pNew = sqlite3DbRealloc(db, pSrc,
69294                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
69295     if( pNew==0 ){
69296       assert( db->mallocFailed );
69297       return pSrc;
69298     }
69299     pSrc = pNew;
69300     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
69301     pSrc->nAlloc = (u16)nGot;
69302   }
69303
69304   /* Move existing slots that come after the newly inserted slots
69305   ** out of the way */
69306   for(i=pSrc->nSrc-1; i>=iStart; i--){
69307     pSrc->a[i+nExtra] = pSrc->a[i];
69308   }
69309   pSrc->nSrc += (i16)nExtra;
69310
69311   /* Zero the newly allocated slots */
69312   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
69313   for(i=iStart; i<iStart+nExtra; i++){
69314     pSrc->a[i].iCursor = -1;
69315   }
69316
69317   /* Return a pointer to the enlarged SrcList */
69318   return pSrc;
69319 }
69320
69321
69322 /*
69323 ** Append a new table name to the given SrcList.  Create a new SrcList if
69324 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
69325 **
69326 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
69327 ** SrcList might be the same as the SrcList that was input or it might be
69328 ** a new one.  If an OOM error does occurs, then the prior value of pList
69329 ** that is input to this routine is automatically freed.
69330 **
69331 ** If pDatabase is not null, it means that the table has an optional
69332 ** database name prefix.  Like this:  "database.table".  The pDatabase
69333 ** points to the table name and the pTable points to the database name.
69334 ** The SrcList.a[].zName field is filled with the table name which might
69335 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
69336 ** SrcList.a[].zDatabase is filled with the database name from pTable,
69337 ** or with NULL if no database is specified.
69338 **
69339 ** In other words, if call like this:
69340 **
69341 **         sqlite3SrcListAppend(D,A,B,0);
69342 **
69343 ** Then B is a table name and the database name is unspecified.  If called
69344 ** like this:
69345 **
69346 **         sqlite3SrcListAppend(D,A,B,C);
69347 **
69348 ** Then C is the table name and B is the database name.  If C is defined
69349 ** then so is B.  In other words, we never have a case where:
69350 **
69351 **         sqlite3SrcListAppend(D,A,0,C);
69352 **
69353 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
69354 ** before being added to the SrcList.
69355 */
69356 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
69357   sqlite3 *db,        /* Connection to notify of malloc failures */
69358   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
69359   Token *pTable,      /* Table to append */
69360   Token *pDatabase    /* Database of the table */
69361 ){
69362   struct SrcList_item *pItem;
69363   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
69364   if( pList==0 ){
69365     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
69366     if( pList==0 ) return 0;
69367     pList->nAlloc = 1;
69368   }
69369   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
69370   if( db->mallocFailed ){
69371     sqlite3SrcListDelete(db, pList);
69372     return 0;
69373   }
69374   pItem = &pList->a[pList->nSrc-1];
69375   if( pDatabase && pDatabase->z==0 ){
69376     pDatabase = 0;
69377   }
69378   if( pDatabase ){
69379     Token *pTemp = pDatabase;
69380     pDatabase = pTable;
69381     pTable = pTemp;
69382   }
69383   pItem->zName = sqlite3NameFromToken(db, pTable);
69384   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
69385   return pList;
69386 }
69387
69388 /*
69389 ** Assign VdbeCursor index numbers to all tables in a SrcList
69390 */
69391 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
69392   int i;
69393   struct SrcList_item *pItem;
69394   assert(pList || pParse->db->mallocFailed );
69395   if( pList ){
69396     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
69397       if( pItem->iCursor>=0 ) break;
69398       pItem->iCursor = pParse->nTab++;
69399       if( pItem->pSelect ){
69400         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
69401       }
69402     }
69403   }
69404 }
69405
69406 /*
69407 ** Delete an entire SrcList including all its substructure.
69408 */
69409 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
69410   int i;
69411   struct SrcList_item *pItem;
69412   if( pList==0 ) return;
69413   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
69414     sqlite3DbFree(db, pItem->zDatabase);
69415     sqlite3DbFree(db, pItem->zName);
69416     sqlite3DbFree(db, pItem->zAlias);
69417     sqlite3DbFree(db, pItem->zIndex);
69418     sqlite3DeleteTable(pItem->pTab);
69419     sqlite3SelectDelete(db, pItem->pSelect);
69420     sqlite3ExprDelete(db, pItem->pOn);
69421     sqlite3IdListDelete(db, pItem->pUsing);
69422   }
69423   sqlite3DbFree(db, pList);
69424 }
69425
69426 /*
69427 ** This routine is called by the parser to add a new term to the
69428 ** end of a growing FROM clause.  The "p" parameter is the part of
69429 ** the FROM clause that has already been constructed.  "p" is NULL
69430 ** if this is the first term of the FROM clause.  pTable and pDatabase
69431 ** are the name of the table and database named in the FROM clause term.
69432 ** pDatabase is NULL if the database name qualifier is missing - the
69433 ** usual case.  If the term has a alias, then pAlias points to the
69434 ** alias token.  If the term is a subquery, then pSubquery is the
69435 ** SELECT statement that the subquery encodes.  The pTable and
69436 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
69437 ** parameters are the content of the ON and USING clauses.
69438 **
69439 ** Return a new SrcList which encodes is the FROM with the new
69440 ** term added.
69441 */
69442 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
69443   Parse *pParse,          /* Parsing context */
69444   SrcList *p,             /* The left part of the FROM clause already seen */
69445   Token *pTable,          /* Name of the table to add to the FROM clause */
69446   Token *pDatabase,       /* Name of the database containing pTable */
69447   Token *pAlias,          /* The right-hand side of the AS subexpression */
69448   Select *pSubquery,      /* A subquery used in place of a table name */
69449   Expr *pOn,              /* The ON clause of a join */
69450   IdList *pUsing          /* The USING clause of a join */
69451 ){
69452   struct SrcList_item *pItem;
69453   sqlite3 *db = pParse->db;
69454   if( !p && (pOn || pUsing) ){
69455     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
69456       (pOn ? "ON" : "USING")
69457     );
69458     goto append_from_error;
69459   }
69460   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
69461   if( p==0 || NEVER(p->nSrc==0) ){
69462     goto append_from_error;
69463   }
69464   pItem = &p->a[p->nSrc-1];
69465   assert( pAlias!=0 );
69466   if( pAlias->n ){
69467     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
69468   }
69469   pItem->pSelect = pSubquery;
69470   pItem->pOn = pOn;
69471   pItem->pUsing = pUsing;
69472   return p;
69473
69474  append_from_error:
69475   assert( p==0 );
69476   sqlite3ExprDelete(db, pOn);
69477   sqlite3IdListDelete(db, pUsing);
69478   sqlite3SelectDelete(db, pSubquery);
69479   return 0;
69480 }
69481
69482 /*
69483 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
69484 ** element of the source-list passed as the second argument.
69485 */
69486 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
69487   assert( pIndexedBy!=0 );
69488   if( p && ALWAYS(p->nSrc>0) ){
69489     struct SrcList_item *pItem = &p->a[p->nSrc-1];
69490     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
69491     if( pIndexedBy->n==1 && !pIndexedBy->z ){
69492       /* A "NOT INDEXED" clause was supplied. See parse.y 
69493       ** construct "indexed_opt" for details. */
69494       pItem->notIndexed = 1;
69495     }else{
69496       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
69497     }
69498   }
69499 }
69500
69501 /*
69502 ** When building up a FROM clause in the parser, the join operator
69503 ** is initially attached to the left operand.  But the code generator
69504 ** expects the join operator to be on the right operand.  This routine
69505 ** Shifts all join operators from left to right for an entire FROM
69506 ** clause.
69507 **
69508 ** Example: Suppose the join is like this:
69509 **
69510 **           A natural cross join B
69511 **
69512 ** The operator is "natural cross join".  The A and B operands are stored
69513 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
69514 ** operator with A.  This routine shifts that operator over to B.
69515 */
69516 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
69517   if( p && p->a ){
69518     int i;
69519     for(i=p->nSrc-1; i>0; i--){
69520       p->a[i].jointype = p->a[i-1].jointype;
69521     }
69522     p->a[0].jointype = 0;
69523   }
69524 }
69525
69526 /*
69527 ** Begin a transaction
69528 */
69529 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
69530   sqlite3 *db;
69531   Vdbe *v;
69532   int i;
69533
69534   assert( pParse!=0 );
69535   db = pParse->db;
69536   assert( db!=0 );
69537 /*  if( db->aDb[0].pBt==0 ) return; */
69538   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
69539     return;
69540   }
69541   v = sqlite3GetVdbe(pParse);
69542   if( !v ) return;
69543   if( type!=TK_DEFERRED ){
69544     for(i=0; i<db->nDb; i++){
69545       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
69546       sqlite3VdbeUsesBtree(v, i);
69547     }
69548   }
69549   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
69550 }
69551
69552 /*
69553 ** Commit a transaction
69554 */
69555 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
69556   sqlite3 *db;
69557   Vdbe *v;
69558
69559   assert( pParse!=0 );
69560   db = pParse->db;
69561   assert( db!=0 );
69562 /*  if( db->aDb[0].pBt==0 ) return; */
69563   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
69564     return;
69565   }
69566   v = sqlite3GetVdbe(pParse);
69567   if( v ){
69568     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
69569   }
69570 }
69571
69572 /*
69573 ** Rollback a transaction
69574 */
69575 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
69576   sqlite3 *db;
69577   Vdbe *v;
69578
69579   assert( pParse!=0 );
69580   db = pParse->db;
69581   assert( db!=0 );
69582 /*  if( db->aDb[0].pBt==0 ) return; */
69583   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
69584     return;
69585   }
69586   v = sqlite3GetVdbe(pParse);
69587   if( v ){
69588     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
69589   }
69590 }
69591
69592 /*
69593 ** This function is called by the parser when it parses a command to create,
69594 ** release or rollback an SQL savepoint. 
69595 */
69596 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
69597   char *zName = sqlite3NameFromToken(pParse->db, pName);
69598   if( zName ){
69599     Vdbe *v = sqlite3GetVdbe(pParse);
69600 #ifndef SQLITE_OMIT_AUTHORIZATION
69601     static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
69602     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
69603 #endif
69604     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
69605       sqlite3DbFree(pParse->db, zName);
69606       return;
69607     }
69608     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
69609   }
69610 }
69611
69612 /*
69613 ** Make sure the TEMP database is open and available for use.  Return
69614 ** the number of errors.  Leave any error messages in the pParse structure.
69615 */
69616 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
69617   sqlite3 *db = pParse->db;
69618   if( db->aDb[1].pBt==0 && !pParse->explain ){
69619     int rc;
69620     static const int flags = 
69621           SQLITE_OPEN_READWRITE |
69622           SQLITE_OPEN_CREATE |
69623           SQLITE_OPEN_EXCLUSIVE |
69624           SQLITE_OPEN_DELETEONCLOSE |
69625           SQLITE_OPEN_TEMP_DB;
69626
69627     rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
69628                                  &db->aDb[1].pBt);
69629     if( rc!=SQLITE_OK ){
69630       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
69631         "file for storing temporary tables");
69632       pParse->rc = rc;
69633       return 1;
69634     }
69635     assert( db->aDb[1].pSchema );
69636     sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
69637                             db->dfltJournalMode);
69638   }
69639   return 0;
69640 }
69641
69642 /*
69643 ** Generate VDBE code that will verify the schema cookie and start
69644 ** a read-transaction for all named database files.
69645 **
69646 ** It is important that all schema cookies be verified and all
69647 ** read transactions be started before anything else happens in
69648 ** the VDBE program.  But this routine can be called after much other
69649 ** code has been generated.  So here is what we do:
69650 **
69651 ** The first time this routine is called, we code an OP_Goto that
69652 ** will jump to a subroutine at the end of the program.  Then we
69653 ** record every database that needs its schema verified in the
69654 ** pParse->cookieMask field.  Later, after all other code has been
69655 ** generated, the subroutine that does the cookie verifications and
69656 ** starts the transactions will be coded and the OP_Goto P2 value
69657 ** will be made to point to that subroutine.  The generation of the
69658 ** cookie verification subroutine code happens in sqlite3FinishCoding().
69659 **
69660 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
69661 ** schema on any databases.  This can be used to position the OP_Goto
69662 ** early in the code, before we know if any database tables will be used.
69663 */
69664 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
69665   Parse *pToplevel = sqlite3ParseToplevel(pParse);
69666
69667   if( pToplevel->cookieGoto==0 ){
69668     Vdbe *v = sqlite3GetVdbe(pToplevel);
69669     if( v==0 ) return;  /* This only happens if there was a prior error */
69670     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
69671   }
69672   if( iDb>=0 ){
69673     sqlite3 *db = pToplevel->db;
69674     int mask;
69675
69676     assert( iDb<db->nDb );
69677     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
69678     assert( iDb<SQLITE_MAX_ATTACHED+2 );
69679     mask = 1<<iDb;
69680     if( (pToplevel->cookieMask & mask)==0 ){
69681       pToplevel->cookieMask |= mask;
69682       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
69683       if( !OMIT_TEMPDB && iDb==1 ){
69684         sqlite3OpenTempDatabase(pToplevel);
69685       }
69686     }
69687   }
69688 }
69689
69690 /*
69691 ** Generate VDBE code that prepares for doing an operation that
69692 ** might change the database.
69693 **
69694 ** This routine starts a new transaction if we are not already within
69695 ** a transaction.  If we are already within a transaction, then a checkpoint
69696 ** is set if the setStatement parameter is true.  A checkpoint should
69697 ** be set for operations that might fail (due to a constraint) part of
69698 ** the way through and which will need to undo some writes without having to
69699 ** rollback the whole transaction.  For operations where all constraints
69700 ** can be checked before any changes are made to the database, it is never
69701 ** necessary to undo a write and the checkpoint should not be set.
69702 */
69703 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
69704   Parse *pToplevel = sqlite3ParseToplevel(pParse);
69705   sqlite3CodeVerifySchema(pParse, iDb);
69706   pToplevel->writeMask |= 1<<iDb;
69707   pToplevel->isMultiWrite |= setStatement;
69708 }
69709
69710 /*
69711 ** Indicate that the statement currently under construction might write
69712 ** more than one entry (example: deleting one row then inserting another,
69713 ** inserting multiple rows in a table, or inserting a row and index entries.)
69714 ** If an abort occurs after some of these writes have completed, then it will
69715 ** be necessary to undo the completed writes.
69716 */
69717 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
69718   Parse *pToplevel = sqlite3ParseToplevel(pParse);
69719   pToplevel->isMultiWrite = 1;
69720 }
69721
69722 /* 
69723 ** The code generator calls this routine if is discovers that it is
69724 ** possible to abort a statement prior to completion.  In order to 
69725 ** perform this abort without corrupting the database, we need to make
69726 ** sure that the statement is protected by a statement transaction.
69727 **
69728 ** Technically, we only need to set the mayAbort flag if the
69729 ** isMultiWrite flag was previously set.  There is a time dependency
69730 ** such that the abort must occur after the multiwrite.  This makes
69731 ** some statements involving the REPLACE conflict resolution algorithm
69732 ** go a little faster.  But taking advantage of this time dependency
69733 ** makes it more difficult to prove that the code is correct (in 
69734 ** particular, it prevents us from writing an effective
69735 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
69736 ** to take the safe route and skip the optimization.
69737 */
69738 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
69739   Parse *pToplevel = sqlite3ParseToplevel(pParse);
69740   pToplevel->mayAbort = 1;
69741 }
69742
69743 /*
69744 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
69745 ** error. The onError parameter determines which (if any) of the statement
69746 ** and/or current transaction is rolled back.
69747 */
69748 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
69749   Vdbe *v = sqlite3GetVdbe(pParse);
69750   if( onError==OE_Abort ){
69751     sqlite3MayAbort(pParse);
69752   }
69753   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
69754 }
69755
69756 /*
69757 ** Check to see if pIndex uses the collating sequence pColl.  Return
69758 ** true if it does and false if it does not.
69759 */
69760 #ifndef SQLITE_OMIT_REINDEX
69761 static int collationMatch(const char *zColl, Index *pIndex){
69762   int i;
69763   assert( zColl!=0 );
69764   for(i=0; i<pIndex->nColumn; i++){
69765     const char *z = pIndex->azColl[i];
69766     assert( z!=0 );
69767     if( 0==sqlite3StrICmp(z, zColl) ){
69768       return 1;
69769     }
69770   }
69771   return 0;
69772 }
69773 #endif
69774
69775 /*
69776 ** Recompute all indices of pTab that use the collating sequence pColl.
69777 ** If pColl==0 then recompute all indices of pTab.
69778 */
69779 #ifndef SQLITE_OMIT_REINDEX
69780 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
69781   Index *pIndex;              /* An index associated with pTab */
69782
69783   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
69784     if( zColl==0 || collationMatch(zColl, pIndex) ){
69785       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
69786       sqlite3BeginWriteOperation(pParse, 0, iDb);
69787       sqlite3RefillIndex(pParse, pIndex, -1);
69788     }
69789   }
69790 }
69791 #endif
69792
69793 /*
69794 ** Recompute all indices of all tables in all databases where the
69795 ** indices use the collating sequence pColl.  If pColl==0 then recompute
69796 ** all indices everywhere.
69797 */
69798 #ifndef SQLITE_OMIT_REINDEX
69799 static void reindexDatabases(Parse *pParse, char const *zColl){
69800   Db *pDb;                    /* A single database */
69801   int iDb;                    /* The database index number */
69802   sqlite3 *db = pParse->db;   /* The database connection */
69803   HashElem *k;                /* For looping over tables in pDb */
69804   Table *pTab;                /* A table in the database */
69805
69806   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
69807     assert( pDb!=0 );
69808     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
69809       pTab = (Table*)sqliteHashData(k);
69810       reindexTable(pParse, pTab, zColl);
69811     }
69812   }
69813 }
69814 #endif
69815
69816 /*
69817 ** Generate code for the REINDEX command.
69818 **
69819 **        REINDEX                            -- 1
69820 **        REINDEX  <collation>               -- 2
69821 **        REINDEX  ?<database>.?<tablename>  -- 3
69822 **        REINDEX  ?<database>.?<indexname>  -- 4
69823 **
69824 ** Form 1 causes all indices in all attached databases to be rebuilt.
69825 ** Form 2 rebuilds all indices in all databases that use the named
69826 ** collating function.  Forms 3 and 4 rebuild the named index or all
69827 ** indices associated with the named table.
69828 */
69829 #ifndef SQLITE_OMIT_REINDEX
69830 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
69831   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
69832   char *z;                    /* Name of a table or index */
69833   const char *zDb;            /* Name of the database */
69834   Table *pTab;                /* A table in the database */
69835   Index *pIndex;              /* An index associated with pTab */
69836   int iDb;                    /* The database index number */
69837   sqlite3 *db = pParse->db;   /* The database connection */
69838   Token *pObjName;            /* Name of the table or index to be reindexed */
69839
69840   /* Read the database schema. If an error occurs, leave an error message
69841   ** and code in pParse and return NULL. */
69842   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
69843     return;
69844   }
69845
69846   if( pName1==0 ){
69847     reindexDatabases(pParse, 0);
69848     return;
69849   }else if( NEVER(pName2==0) || pName2->z==0 ){
69850     char *zColl;
69851     assert( pName1->z );
69852     zColl = sqlite3NameFromToken(pParse->db, pName1);
69853     if( !zColl ) return;
69854     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
69855     if( pColl ){
69856       reindexDatabases(pParse, zColl);
69857       sqlite3DbFree(db, zColl);
69858       return;
69859     }
69860     sqlite3DbFree(db, zColl);
69861   }
69862   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
69863   if( iDb<0 ) return;
69864   z = sqlite3NameFromToken(db, pObjName);
69865   if( z==0 ) return;
69866   zDb = db->aDb[iDb].zName;
69867   pTab = sqlite3FindTable(db, z, zDb);
69868   if( pTab ){
69869     reindexTable(pParse, pTab, 0);
69870     sqlite3DbFree(db, z);
69871     return;
69872   }
69873   pIndex = sqlite3FindIndex(db, z, zDb);
69874   sqlite3DbFree(db, z);
69875   if( pIndex ){
69876     sqlite3BeginWriteOperation(pParse, 0, iDb);
69877     sqlite3RefillIndex(pParse, pIndex, -1);
69878     return;
69879   }
69880   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
69881 }
69882 #endif
69883
69884 /*
69885 ** Return a dynamicly allocated KeyInfo structure that can be used
69886 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
69887 **
69888 ** If successful, a pointer to the new structure is returned. In this case
69889 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
69890 ** pointer. If an error occurs (out of memory or missing collation 
69891 ** sequence), NULL is returned and the state of pParse updated to reflect
69892 ** the error.
69893 */
69894 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
69895   int i;
69896   int nCol = pIdx->nColumn;
69897   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
69898   sqlite3 *db = pParse->db;
69899   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
69900
69901   if( pKey ){
69902     pKey->db = pParse->db;
69903     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
69904     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
69905     for(i=0; i<nCol; i++){
69906       char *zColl = pIdx->azColl[i];
69907       assert( zColl );
69908       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
69909       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
69910     }
69911     pKey->nField = (u16)nCol;
69912   }
69913
69914   if( pParse->nErr ){
69915     sqlite3DbFree(db, pKey);
69916     pKey = 0;
69917   }
69918   return pKey;
69919 }
69920
69921 /************** End of build.c ***********************************************/
69922 /************** Begin file callback.c ****************************************/
69923 /*
69924 ** 2005 May 23 
69925 **
69926 ** The author disclaims copyright to this source code.  In place of
69927 ** a legal notice, here is a blessing:
69928 **
69929 **    May you do good and not evil.
69930 **    May you find forgiveness for yourself and forgive others.
69931 **    May you share freely, never taking more than you give.
69932 **
69933 *************************************************************************
69934 **
69935 ** This file contains functions used to access the internal hash tables
69936 ** of user defined functions and collation sequences.
69937 */
69938
69939
69940 /*
69941 ** Invoke the 'collation needed' callback to request a collation sequence
69942 ** in the encoding enc of name zName, length nName.
69943 */
69944 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
69945   assert( !db->xCollNeeded || !db->xCollNeeded16 );
69946   if( db->xCollNeeded ){
69947     char *zExternal = sqlite3DbStrDup(db, zName);
69948     if( !zExternal ) return;
69949     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
69950     sqlite3DbFree(db, zExternal);
69951   }
69952 #ifndef SQLITE_OMIT_UTF16
69953   if( db->xCollNeeded16 ){
69954     char const *zExternal;
69955     sqlite3_value *pTmp = sqlite3ValueNew(db);
69956     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
69957     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
69958     if( zExternal ){
69959       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
69960     }
69961     sqlite3ValueFree(pTmp);
69962   }
69963 #endif
69964 }
69965
69966 /*
69967 ** This routine is called if the collation factory fails to deliver a
69968 ** collation function in the best encoding but there may be other versions
69969 ** of this collation function (for other text encodings) available. Use one
69970 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
69971 ** possible.
69972 */
69973 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
69974   CollSeq *pColl2;
69975   char *z = pColl->zName;
69976   int i;
69977   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
69978   for(i=0; i<3; i++){
69979     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
69980     if( pColl2->xCmp!=0 ){
69981       memcpy(pColl, pColl2, sizeof(CollSeq));
69982       pColl->xDel = 0;         /* Do not copy the destructor */
69983       return SQLITE_OK;
69984     }
69985   }
69986   return SQLITE_ERROR;
69987 }
69988
69989 /*
69990 ** This function is responsible for invoking the collation factory callback
69991 ** or substituting a collation sequence of a different encoding when the
69992 ** requested collation sequence is not available in the desired encoding.
69993 ** 
69994 ** If it is not NULL, then pColl must point to the database native encoding 
69995 ** collation sequence with name zName, length nName.
69996 **
69997 ** The return value is either the collation sequence to be used in database
69998 ** db for collation type name zName, length nName, or NULL, if no collation
69999 ** sequence can be found.
70000 **
70001 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
70002 */
70003 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
70004   sqlite3* db,          /* The database connection */
70005   u8 enc,               /* The desired encoding for the collating sequence */
70006   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
70007   const char *zName     /* Collating sequence name */
70008 ){
70009   CollSeq *p;
70010
70011   p = pColl;
70012   if( !p ){
70013     p = sqlite3FindCollSeq(db, enc, zName, 0);
70014   }
70015   if( !p || !p->xCmp ){
70016     /* No collation sequence of this type for this encoding is registered.
70017     ** Call the collation factory to see if it can supply us with one.
70018     */
70019     callCollNeeded(db, enc, zName);
70020     p = sqlite3FindCollSeq(db, enc, zName, 0);
70021   }
70022   if( p && !p->xCmp && synthCollSeq(db, p) ){
70023     p = 0;
70024   }
70025   assert( !p || p->xCmp );
70026   return p;
70027 }
70028
70029 /*
70030 ** This routine is called on a collation sequence before it is used to
70031 ** check that it is defined. An undefined collation sequence exists when
70032 ** a database is loaded that contains references to collation sequences
70033 ** that have not been defined by sqlite3_create_collation() etc.
70034 **
70035 ** If required, this routine calls the 'collation needed' callback to
70036 ** request a definition of the collating sequence. If this doesn't work, 
70037 ** an equivalent collating sequence that uses a text encoding different
70038 ** from the main database is substituted, if one is available.
70039 */
70040 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
70041   if( pColl ){
70042     const char *zName = pColl->zName;
70043     sqlite3 *db = pParse->db;
70044     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
70045     if( !p ){
70046       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
70047       pParse->nErr++;
70048       return SQLITE_ERROR;
70049     }
70050     assert( p==pColl );
70051   }
70052   return SQLITE_OK;
70053 }
70054
70055
70056
70057 /*
70058 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
70059 ** specified by zName and nName is not found and parameter 'create' is
70060 ** true, then create a new entry. Otherwise return NULL.
70061 **
70062 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
70063 ** array of three CollSeq structures. The first is the collation sequence
70064 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
70065 **
70066 ** Stored immediately after the three collation sequences is a copy of
70067 ** the collation sequence name. A pointer to this string is stored in
70068 ** each collation sequence structure.
70069 */
70070 static CollSeq *findCollSeqEntry(
70071   sqlite3 *db,          /* Database connection */
70072   const char *zName,    /* Name of the collating sequence */
70073   int create            /* Create a new entry if true */
70074 ){
70075   CollSeq *pColl;
70076   int nName = sqlite3Strlen30(zName);
70077   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
70078
70079   if( 0==pColl && create ){
70080     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
70081     if( pColl ){
70082       CollSeq *pDel = 0;
70083       pColl[0].zName = (char*)&pColl[3];
70084       pColl[0].enc = SQLITE_UTF8;
70085       pColl[1].zName = (char*)&pColl[3];
70086       pColl[1].enc = SQLITE_UTF16LE;
70087       pColl[2].zName = (char*)&pColl[3];
70088       pColl[2].enc = SQLITE_UTF16BE;
70089       memcpy(pColl[0].zName, zName, nName);
70090       pColl[0].zName[nName] = 0;
70091       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
70092
70093       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
70094       ** return the pColl pointer to be deleted (because it wasn't added
70095       ** to the hash table).
70096       */
70097       assert( pDel==0 || pDel==pColl );
70098       if( pDel!=0 ){
70099         db->mallocFailed = 1;
70100         sqlite3DbFree(db, pDel);
70101         pColl = 0;
70102       }
70103     }
70104   }
70105   return pColl;
70106 }
70107
70108 /*
70109 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
70110 ** Return the CollSeq* pointer for the collation sequence named zName
70111 ** for the encoding 'enc' from the database 'db'.
70112 **
70113 ** If the entry specified is not found and 'create' is true, then create a
70114 ** new entry.  Otherwise return NULL.
70115 **
70116 ** A separate function sqlite3LocateCollSeq() is a wrapper around
70117 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
70118 ** if necessary and generates an error message if the collating sequence
70119 ** cannot be found.
70120 **
70121 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
70122 */
70123 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
70124   sqlite3 *db,
70125   u8 enc,
70126   const char *zName,
70127   int create
70128 ){
70129   CollSeq *pColl;
70130   if( zName ){
70131     pColl = findCollSeqEntry(db, zName, create);
70132   }else{
70133     pColl = db->pDfltColl;
70134   }
70135   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
70136   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
70137   if( pColl ) pColl += enc-1;
70138   return pColl;
70139 }
70140
70141 /* During the search for the best function definition, this procedure
70142 ** is called to test how well the function passed as the first argument
70143 ** matches the request for a function with nArg arguments in a system
70144 ** that uses encoding enc. The value returned indicates how well the
70145 ** request is matched. A higher value indicates a better match.
70146 **
70147 ** The returned value is always between 0 and 6, as follows:
70148 **
70149 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
70150 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
70151 **    encoding is requested, or vice versa.
70152 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
70153 **    requested, or vice versa.
70154 ** 3: A variable arguments function using the same text encoding.
70155 ** 4: A function with the exact number of arguments requested that
70156 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
70157 ** 5: A function with the exact number of arguments requested that
70158 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
70159 ** 6: An exact match.
70160 **
70161 */
70162 static int matchQuality(FuncDef *p, int nArg, u8 enc){
70163   int match = 0;
70164   if( p->nArg==-1 || p->nArg==nArg 
70165    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
70166   ){
70167     match = 1;
70168     if( p->nArg==nArg || nArg==-1 ){
70169       match = 4;
70170     }
70171     if( enc==p->iPrefEnc ){
70172       match += 2;
70173     }
70174     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
70175              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
70176       match += 1;
70177     }
70178   }
70179   return match;
70180 }
70181
70182 /*
70183 ** Search a FuncDefHash for a function with the given name.  Return
70184 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
70185 */
70186 static FuncDef *functionSearch(
70187   FuncDefHash *pHash,  /* Hash table to search */
70188   int h,               /* Hash of the name */
70189   const char *zFunc,   /* Name of function */
70190   int nFunc            /* Number of bytes in zFunc */
70191 ){
70192   FuncDef *p;
70193   for(p=pHash->a[h]; p; p=p->pHash){
70194     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
70195       return p;
70196     }
70197   }
70198   return 0;
70199 }
70200
70201 /*
70202 ** Insert a new FuncDef into a FuncDefHash hash table.
70203 */
70204 SQLITE_PRIVATE void sqlite3FuncDefInsert(
70205   FuncDefHash *pHash,  /* The hash table into which to insert */
70206   FuncDef *pDef        /* The function definition to insert */
70207 ){
70208   FuncDef *pOther;
70209   int nName = sqlite3Strlen30(pDef->zName);
70210   u8 c1 = (u8)pDef->zName[0];
70211   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
70212   pOther = functionSearch(pHash, h, pDef->zName, nName);
70213   if( pOther ){
70214     assert( pOther!=pDef && pOther->pNext!=pDef );
70215     pDef->pNext = pOther->pNext;
70216     pOther->pNext = pDef;
70217   }else{
70218     pDef->pNext = 0;
70219     pDef->pHash = pHash->a[h];
70220     pHash->a[h] = pDef;
70221   }
70222 }
70223   
70224   
70225
70226 /*
70227 ** Locate a user function given a name, a number of arguments and a flag
70228 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
70229 ** pointer to the FuncDef structure that defines that function, or return
70230 ** NULL if the function does not exist.
70231 **
70232 ** If the createFlag argument is true, then a new (blank) FuncDef
70233 ** structure is created and liked into the "db" structure if a
70234 ** no matching function previously existed.  When createFlag is true
70235 ** and the nArg parameter is -1, then only a function that accepts
70236 ** any number of arguments will be returned.
70237 **
70238 ** If createFlag is false and nArg is -1, then the first valid
70239 ** function found is returned.  A function is valid if either xFunc
70240 ** or xStep is non-zero.
70241 **
70242 ** If createFlag is false, then a function with the required name and
70243 ** number of arguments may be returned even if the eTextRep flag does not
70244 ** match that requested.
70245 */
70246 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
70247   sqlite3 *db,       /* An open database */
70248   const char *zName, /* Name of the function.  Not null-terminated */
70249   int nName,         /* Number of characters in the name */
70250   int nArg,          /* Number of arguments.  -1 means any number */
70251   u8 enc,            /* Preferred text encoding */
70252   int createFlag     /* Create new entry if true and does not otherwise exist */
70253 ){
70254   FuncDef *p;         /* Iterator variable */
70255   FuncDef *pBest = 0; /* Best match found so far */
70256   int bestScore = 0;  /* Score of best match */
70257   int h;              /* Hash value */
70258
70259
70260   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
70261   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
70262
70263   /* First search for a match amongst the application-defined functions.
70264   */
70265   p = functionSearch(&db->aFunc, h, zName, nName);
70266   while( p ){
70267     int score = matchQuality(p, nArg, enc);
70268     if( score>bestScore ){
70269       pBest = p;
70270       bestScore = score;
70271     }
70272     p = p->pNext;
70273   }
70274
70275   /* If no match is found, search the built-in functions.
70276   **
70277   ** Except, if createFlag is true, that means that we are trying to
70278   ** install a new function.  Whatever FuncDef structure is returned will
70279   ** have fields overwritten with new information appropriate for the
70280   ** new function.  But the FuncDefs for built-in functions are read-only.
70281   ** So we must not search for built-ins when creating a new function.
70282   */ 
70283   if( !createFlag && !pBest ){
70284     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
70285     p = functionSearch(pHash, h, zName, nName);
70286     while( p ){
70287       int score = matchQuality(p, nArg, enc);
70288       if( score>bestScore ){
70289         pBest = p;
70290         bestScore = score;
70291       }
70292       p = p->pNext;
70293     }
70294   }
70295
70296   /* If the createFlag parameter is true and the search did not reveal an
70297   ** exact match for the name, number of arguments and encoding, then add a
70298   ** new entry to the hash table and return it.
70299   */
70300   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
70301       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
70302     pBest->zName = (char *)&pBest[1];
70303     pBest->nArg = (u16)nArg;
70304     pBest->iPrefEnc = enc;
70305     memcpy(pBest->zName, zName, nName);
70306     pBest->zName[nName] = 0;
70307     sqlite3FuncDefInsert(&db->aFunc, pBest);
70308   }
70309
70310   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
70311     return pBest;
70312   }
70313   return 0;
70314 }
70315
70316 /*
70317 ** Free all resources held by the schema structure. The void* argument points
70318 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
70319 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
70320 ** of the schema hash tables).
70321 **
70322 ** The Schema.cache_size variable is not cleared.
70323 */
70324 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
70325   Hash temp1;
70326   Hash temp2;
70327   HashElem *pElem;
70328   Schema *pSchema = (Schema *)p;
70329
70330   temp1 = pSchema->tblHash;
70331   temp2 = pSchema->trigHash;
70332   sqlite3HashInit(&pSchema->trigHash);
70333   sqlite3HashClear(&pSchema->idxHash);
70334   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
70335     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
70336   }
70337   sqlite3HashClear(&temp2);
70338   sqlite3HashInit(&pSchema->tblHash);
70339   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
70340     Table *pTab = sqliteHashData(pElem);
70341     assert( pTab->dbMem==0 );
70342     sqlite3DeleteTable(pTab);
70343   }
70344   sqlite3HashClear(&temp1);
70345   sqlite3HashClear(&pSchema->fkeyHash);
70346   pSchema->pSeqTab = 0;
70347   pSchema->flags &= ~DB_SchemaLoaded;
70348 }
70349
70350 /*
70351 ** Find and return the schema associated with a BTree.  Create
70352 ** a new one if necessary.
70353 */
70354 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
70355   Schema * p;
70356   if( pBt ){
70357     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
70358   }else{
70359     p = (Schema *)sqlite3MallocZero(sizeof(Schema));
70360   }
70361   if( !p ){
70362     db->mallocFailed = 1;
70363   }else if ( 0==p->file_format ){
70364     sqlite3HashInit(&p->tblHash);
70365     sqlite3HashInit(&p->idxHash);
70366     sqlite3HashInit(&p->trigHash);
70367     sqlite3HashInit(&p->fkeyHash);
70368     p->enc = SQLITE_UTF8;
70369   }
70370   return p;
70371 }
70372
70373 /************** End of callback.c ********************************************/
70374 /************** Begin file delete.c ******************************************/
70375 /*
70376 ** 2001 September 15
70377 **
70378 ** The author disclaims copyright to this source code.  In place of
70379 ** a legal notice, here is a blessing:
70380 **
70381 **    May you do good and not evil.
70382 **    May you find forgiveness for yourself and forgive others.
70383 **    May you share freely, never taking more than you give.
70384 **
70385 *************************************************************************
70386 ** This file contains C code routines that are called by the parser
70387 ** in order to generate code for DELETE FROM statements.
70388 */
70389
70390 /*
70391 ** Look up every table that is named in pSrc.  If any table is not found,
70392 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
70393 ** are found, return a pointer to the last table.
70394 */
70395 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
70396   struct SrcList_item *pItem = pSrc->a;
70397   Table *pTab;
70398   assert( pItem && pSrc->nSrc==1 );
70399   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
70400   sqlite3DeleteTable(pItem->pTab);
70401   pItem->pTab = pTab;
70402   if( pTab ){
70403     pTab->nRef++;
70404   }
70405   if( sqlite3IndexedByLookup(pParse, pItem) ){
70406     pTab = 0;
70407   }
70408   return pTab;
70409 }
70410
70411 /*
70412 ** Check to make sure the given table is writable.  If it is not
70413 ** writable, generate an error message and return 1.  If it is
70414 ** writable return 0;
70415 */
70416 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
70417   /* A table is not writable under the following circumstances:
70418   **
70419   **   1) It is a virtual table and no implementation of the xUpdate method
70420   **      has been provided, or
70421   **   2) It is a system table (i.e. sqlite_master), this call is not
70422   **      part of a nested parse and writable_schema pragma has not 
70423   **      been specified.
70424   **
70425   ** In either case leave an error message in pParse and return non-zero.
70426   */
70427   if( ( IsVirtual(pTab) 
70428      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
70429    || ( (pTab->tabFlags & TF_Readonly)!=0
70430      && (pParse->db->flags & SQLITE_WriteSchema)==0
70431      && pParse->nested==0 )
70432   ){
70433     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
70434     return 1;
70435   }
70436
70437 #ifndef SQLITE_OMIT_VIEW
70438   if( !viewOk && pTab->pSelect ){
70439     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
70440     return 1;
70441   }
70442 #endif
70443   return 0;
70444 }
70445
70446
70447 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
70448 /*
70449 ** Evaluate a view and store its result in an ephemeral table.  The
70450 ** pWhere argument is an optional WHERE clause that restricts the
70451 ** set of rows in the view that are to be added to the ephemeral table.
70452 */
70453 SQLITE_PRIVATE void sqlite3MaterializeView(
70454   Parse *pParse,       /* Parsing context */
70455   Table *pView,        /* View definition */
70456   Expr *pWhere,        /* Optional WHERE clause to be added */
70457   int iCur             /* Cursor number for ephemerial table */
70458 ){
70459   SelectDest dest;
70460   Select *pDup;
70461   sqlite3 *db = pParse->db;
70462
70463   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
70464   if( pWhere ){
70465     SrcList *pFrom;
70466     
70467     pWhere = sqlite3ExprDup(db, pWhere, 0);
70468     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
70469     if( pFrom ){
70470       assert( pFrom->nSrc==1 );
70471       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
70472       pFrom->a[0].pSelect = pDup;
70473       assert( pFrom->a[0].pOn==0 );
70474       assert( pFrom->a[0].pUsing==0 );
70475     }else{
70476       sqlite3SelectDelete(db, pDup);
70477     }
70478     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
70479   }
70480   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
70481   sqlite3Select(pParse, pDup, &dest);
70482   sqlite3SelectDelete(db, pDup);
70483 }
70484 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
70485
70486 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
70487 /*
70488 ** Generate an expression tree to implement the WHERE, ORDER BY,
70489 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
70490 **
70491 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
70492 **                            \__________________________/
70493 **                               pLimitWhere (pInClause)
70494 */
70495 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
70496   Parse *pParse,               /* The parser context */
70497   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
70498   Expr *pWhere,                /* The WHERE clause.  May be null */
70499   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
70500   Expr *pLimit,                /* The LIMIT clause.  May be null */
70501   Expr *pOffset,               /* The OFFSET clause.  May be null */
70502   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
70503 ){
70504   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
70505   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
70506   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
70507   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
70508   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
70509   Select *pSelect = NULL;      /* Complete SELECT tree */
70510
70511   /* Check that there isn't an ORDER BY without a LIMIT clause.
70512   */
70513   if( pOrderBy && (pLimit == 0) ) {
70514     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
70515     pParse->parseError = 1;
70516     goto limit_where_cleanup_2;
70517   }
70518
70519   /* We only need to generate a select expression if there
70520   ** is a limit/offset term to enforce.
70521   */
70522   if( pLimit == 0 ) {
70523     /* if pLimit is null, pOffset will always be null as well. */
70524     assert( pOffset == 0 );
70525     return pWhere;
70526   }
70527
70528   /* Generate a select expression tree to enforce the limit/offset 
70529   ** term for the DELETE or UPDATE statement.  For example:
70530   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
70531   ** becomes:
70532   **   DELETE FROM table_a WHERE rowid IN ( 
70533   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
70534   **   );
70535   */
70536
70537   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
70538   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
70539   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
70540   if( pEList == 0 ) goto limit_where_cleanup_2;
70541
70542   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
70543   ** and the SELECT subtree. */
70544   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
70545   if( pSelectSrc == 0 ) {
70546     sqlite3ExprListDelete(pParse->db, pEList);
70547     goto limit_where_cleanup_2;
70548   }
70549
70550   /* generate the SELECT expression tree. */
70551   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
70552                              pOrderBy,0,pLimit,pOffset);
70553   if( pSelect == 0 ) return 0;
70554
70555   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
70556   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
70557   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
70558   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
70559   if( pInClause == 0 ) goto limit_where_cleanup_1;
70560
70561   pInClause->x.pSelect = pSelect;
70562   pInClause->flags |= EP_xIsSelect;
70563   sqlite3ExprSetHeight(pParse, pInClause);
70564   return pInClause;
70565
70566   /* something went wrong. clean up anything allocated. */
70567 limit_where_cleanup_1:
70568   sqlite3SelectDelete(pParse->db, pSelect);
70569   return 0;
70570
70571 limit_where_cleanup_2:
70572   sqlite3ExprDelete(pParse->db, pWhere);
70573   sqlite3ExprListDelete(pParse->db, pOrderBy);
70574   sqlite3ExprDelete(pParse->db, pLimit);
70575   sqlite3ExprDelete(pParse->db, pOffset);
70576   return 0;
70577 }
70578 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
70579
70580 /*
70581 ** Generate code for a DELETE FROM statement.
70582 **
70583 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
70584 **                 \________/       \________________/
70585 **                  pTabList              pWhere
70586 */
70587 SQLITE_PRIVATE void sqlite3DeleteFrom(
70588   Parse *pParse,         /* The parser context */
70589   SrcList *pTabList,     /* The table from which we should delete things */
70590   Expr *pWhere           /* The WHERE clause.  May be null */
70591 ){
70592   Vdbe *v;               /* The virtual database engine */
70593   Table *pTab;           /* The table from which records will be deleted */
70594   const char *zDb;       /* Name of database holding pTab */
70595   int end, addr = 0;     /* A couple addresses of generated code */
70596   int i;                 /* Loop counter */
70597   WhereInfo *pWInfo;     /* Information about the WHERE clause */
70598   Index *pIdx;           /* For looping over indices of the table */
70599   int iCur;              /* VDBE Cursor number for pTab */
70600   sqlite3 *db;           /* Main database structure */
70601   AuthContext sContext;  /* Authorization context */
70602   NameContext sNC;       /* Name context to resolve expressions in */
70603   int iDb;               /* Database number */
70604   int memCnt = -1;       /* Memory cell used for change counting */
70605   int rcauth;            /* Value returned by authorization callback */
70606
70607 #ifndef SQLITE_OMIT_TRIGGER
70608   int isView;                  /* True if attempting to delete from a view */
70609   Trigger *pTrigger;           /* List of table triggers, if required */
70610 #endif
70611
70612   memset(&sContext, 0, sizeof(sContext));
70613   db = pParse->db;
70614   if( pParse->nErr || db->mallocFailed ){
70615     goto delete_from_cleanup;
70616   }
70617   assert( pTabList->nSrc==1 );
70618
70619   /* Locate the table which we want to delete.  This table has to be
70620   ** put in an SrcList structure because some of the subroutines we
70621   ** will be calling are designed to work with multiple tables and expect
70622   ** an SrcList* parameter instead of just a Table* parameter.
70623   */
70624   pTab = sqlite3SrcListLookup(pParse, pTabList);
70625   if( pTab==0 )  goto delete_from_cleanup;
70626
70627   /* Figure out if we have any triggers and if the table being
70628   ** deleted from is a view
70629   */
70630 #ifndef SQLITE_OMIT_TRIGGER
70631   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
70632   isView = pTab->pSelect!=0;
70633 #else
70634 # define pTrigger 0
70635 # define isView 0
70636 #endif
70637 #ifdef SQLITE_OMIT_VIEW
70638 # undef isView
70639 # define isView 0
70640 #endif
70641
70642   /* If pTab is really a view, make sure it has been initialized.
70643   */
70644   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
70645     goto delete_from_cleanup;
70646   }
70647
70648   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
70649     goto delete_from_cleanup;
70650   }
70651   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
70652   assert( iDb<db->nDb );
70653   zDb = db->aDb[iDb].zName;
70654   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
70655   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
70656   if( rcauth==SQLITE_DENY ){
70657     goto delete_from_cleanup;
70658   }
70659   assert(!isView || pTrigger);
70660
70661   /* Assign  cursor number to the table and all its indices.
70662   */
70663   assert( pTabList->nSrc==1 );
70664   iCur = pTabList->a[0].iCursor = pParse->nTab++;
70665   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
70666     pParse->nTab++;
70667   }
70668
70669   /* Start the view context
70670   */
70671   if( isView ){
70672     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
70673   }
70674
70675   /* Begin generating code.
70676   */
70677   v = sqlite3GetVdbe(pParse);
70678   if( v==0 ){
70679     goto delete_from_cleanup;
70680   }
70681   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
70682   sqlite3BeginWriteOperation(pParse, 1, iDb);
70683
70684   /* If we are trying to delete from a view, realize that view into
70685   ** a ephemeral table.
70686   */
70687 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
70688   if( isView ){
70689     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
70690   }
70691 #endif
70692
70693   /* Resolve the column names in the WHERE clause.
70694   */
70695   memset(&sNC, 0, sizeof(sNC));
70696   sNC.pParse = pParse;
70697   sNC.pSrcList = pTabList;
70698   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
70699     goto delete_from_cleanup;
70700   }
70701
70702   /* Initialize the counter of the number of rows deleted, if
70703   ** we are counting rows.
70704   */
70705   if( db->flags & SQLITE_CountRows ){
70706     memCnt = ++pParse->nMem;
70707     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
70708   }
70709
70710 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
70711   /* Special case: A DELETE without a WHERE clause deletes everything.
70712   ** It is easier just to erase the whole table. Prior to version 3.6.5,
70713   ** this optimization caused the row change count (the value returned by 
70714   ** API function sqlite3_count_changes) to be set incorrectly.  */
70715   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
70716    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
70717   ){
70718     assert( !isView );
70719     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
70720                       pTab->zName, P4_STATIC);
70721     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
70722       assert( pIdx->pSchema==pTab->pSchema );
70723       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
70724     }
70725   }else
70726 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
70727   /* The usual case: There is a WHERE clause so we have to scan through
70728   ** the table and pick which records to delete.
70729   */
70730   {
70731     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
70732     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
70733     int regRowid;                   /* Actual register containing rowids */
70734
70735     /* Collect rowids of every row to be deleted.
70736     */
70737     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
70738     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
70739     if( pWInfo==0 ) goto delete_from_cleanup;
70740     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
70741     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
70742     if( db->flags & SQLITE_CountRows ){
70743       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
70744     }
70745     sqlite3WhereEnd(pWInfo);
70746
70747     /* Delete every item whose key was written to the list during the
70748     ** database scan.  We have to delete items after the scan is complete
70749     ** because deleting an item can change the scan order.  */
70750     end = sqlite3VdbeMakeLabel(v);
70751
70752     /* Unless this is a view, open cursors for the table we are 
70753     ** deleting from and all its indices. If this is a view, then the
70754     ** only effect this statement has is to fire the INSTEAD OF 
70755     ** triggers.  */
70756     if( !isView ){
70757       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
70758     }
70759
70760     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
70761
70762     /* Delete the row */
70763 #ifndef SQLITE_OMIT_VIRTUALTABLE
70764     if( IsVirtual(pTab) ){
70765       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
70766       sqlite3VtabMakeWritable(pParse, pTab);
70767       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
70768       sqlite3MayAbort(pParse);
70769     }else
70770 #endif
70771     {
70772       int count = (pParse->nested==0);    /* True to count changes */
70773       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
70774     }
70775
70776     /* End of the delete loop */
70777     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
70778     sqlite3VdbeResolveLabel(v, end);
70779
70780     /* Close the cursors open on the table and its indexes. */
70781     if( !isView && !IsVirtual(pTab) ){
70782       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
70783         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
70784       }
70785       sqlite3VdbeAddOp1(v, OP_Close, iCur);
70786     }
70787   }
70788
70789   /* Update the sqlite_sequence table by storing the content of the
70790   ** maximum rowid counter values recorded while inserting into
70791   ** autoincrement tables.
70792   */
70793   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
70794     sqlite3AutoincrementEnd(pParse);
70795   }
70796
70797   /* Return the number of rows that were deleted. If this routine is 
70798   ** generating code because of a call to sqlite3NestedParse(), do not
70799   ** invoke the callback function.
70800   */
70801   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
70802     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
70803     sqlite3VdbeSetNumCols(v, 1);
70804     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
70805   }
70806
70807 delete_from_cleanup:
70808   sqlite3AuthContextPop(&sContext);
70809   sqlite3SrcListDelete(db, pTabList);
70810   sqlite3ExprDelete(db, pWhere);
70811   return;
70812 }
70813 /* Make sure "isView" and other macros defined above are undefined. Otherwise
70814 ** thely may interfere with compilation of other functions in this file
70815 ** (or in another file, if this file becomes part of the amalgamation).  */
70816 #ifdef isView
70817  #undef isView
70818 #endif
70819 #ifdef pTrigger
70820  #undef pTrigger
70821 #endif
70822
70823 /*
70824 ** This routine generates VDBE code that causes a single row of a
70825 ** single table to be deleted.
70826 **
70827 ** The VDBE must be in a particular state when this routine is called.
70828 ** These are the requirements:
70829 **
70830 **   1.  A read/write cursor pointing to pTab, the table containing the row
70831 **       to be deleted, must be opened as cursor number $iCur.
70832 **
70833 **   2.  Read/write cursors for all indices of pTab must be open as
70834 **       cursor number base+i for the i-th index.
70835 **
70836 **   3.  The record number of the row to be deleted must be stored in
70837 **       memory cell iRowid.
70838 **
70839 ** This routine generates code to remove both the table record and all 
70840 ** index entries that point to that record.
70841 */
70842 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
70843   Parse *pParse,     /* Parsing context */
70844   Table *pTab,       /* Table containing the row to be deleted */
70845   int iCur,          /* Cursor number for the table */
70846   int iRowid,        /* Memory cell that contains the rowid to delete */
70847   int count,         /* If non-zero, increment the row change counter */
70848   Trigger *pTrigger, /* List of triggers to (potentially) fire */
70849   int onconf         /* Default ON CONFLICT policy for triggers */
70850 ){
70851   Vdbe *v = pParse->pVdbe;        /* Vdbe */
70852   int iOld = 0;                   /* First register in OLD.* array */
70853   int iLabel;                     /* Label resolved to end of generated code */
70854
70855   /* Vdbe is guaranteed to have been allocated by this stage. */
70856   assert( v );
70857
70858   /* Seek cursor iCur to the row to delete. If this row no longer exists 
70859   ** (this can happen if a trigger program has already deleted it), do
70860   ** not attempt to delete it or fire any DELETE triggers.  */
70861   iLabel = sqlite3VdbeMakeLabel(v);
70862   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
70863  
70864   /* If there are any triggers to fire, allocate a range of registers to
70865   ** use for the old.* references in the triggers.  */
70866   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
70867     u32 mask;                     /* Mask of OLD.* columns in use */
70868     int iCol;                     /* Iterator used while populating OLD.* */
70869
70870     /* TODO: Could use temporary registers here. Also could attempt to
70871     ** avoid copying the contents of the rowid register.  */
70872     mask = sqlite3TriggerColmask(
70873         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
70874     );
70875     mask |= sqlite3FkOldmask(pParse, pTab);
70876     iOld = pParse->nMem+1;
70877     pParse->nMem += (1 + pTab->nCol);
70878
70879     /* Populate the OLD.* pseudo-table register array. These values will be 
70880     ** used by any BEFORE and AFTER triggers that exist.  */
70881     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
70882     for(iCol=0; iCol<pTab->nCol; iCol++){
70883       if( mask==0xffffffff || mask&(1<<iCol) ){
70884         int iTarget = iOld + iCol + 1;
70885         sqlite3VdbeAddOp3(v, OP_Column, iCur, iCol, iTarget);
70886         sqlite3ColumnDefault(v, pTab, iCol, iTarget);
70887       }
70888     }
70889
70890     /* Invoke BEFORE DELETE trigger programs. */
70891     sqlite3CodeRowTrigger(pParse, pTrigger, 
70892         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
70893     );
70894
70895     /* Seek the cursor to the row to be deleted again. It may be that
70896     ** the BEFORE triggers coded above have already removed the row
70897     ** being deleted. Do not attempt to delete the row a second time, and 
70898     ** do not fire AFTER triggers.  */
70899     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
70900
70901     /* Do FK processing. This call checks that any FK constraints that
70902     ** refer to this table (i.e. constraints attached to other tables) 
70903     ** are not violated by deleting this row.  */
70904     sqlite3FkCheck(pParse, pTab, iOld, 0);
70905   }
70906
70907   /* Delete the index and table entries. Skip this step if pTab is really
70908   ** a view (in which case the only effect of the DELETE statement is to
70909   ** fire the INSTEAD OF triggers).  */ 
70910   if( pTab->pSelect==0 ){
70911     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
70912     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
70913     if( count ){
70914       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
70915     }
70916   }
70917
70918   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
70919   ** handle rows (possibly in other tables) that refer via a foreign key
70920   ** to the row just deleted. */ 
70921   sqlite3FkActions(pParse, pTab, 0, iOld);
70922
70923   /* Invoke AFTER DELETE trigger programs. */
70924   sqlite3CodeRowTrigger(pParse, pTrigger, 
70925       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
70926   );
70927
70928   /* Jump here if the row had already been deleted before any BEFORE
70929   ** trigger programs were invoked. Or if a trigger program throws a 
70930   ** RAISE(IGNORE) exception.  */
70931   sqlite3VdbeResolveLabel(v, iLabel);
70932 }
70933
70934 /*
70935 ** This routine generates VDBE code that causes the deletion of all
70936 ** index entries associated with a single row of a single table.
70937 **
70938 ** The VDBE must be in a particular state when this routine is called.
70939 ** These are the requirements:
70940 **
70941 **   1.  A read/write cursor pointing to pTab, the table containing the row
70942 **       to be deleted, must be opened as cursor number "iCur".
70943 **
70944 **   2.  Read/write cursors for all indices of pTab must be open as
70945 **       cursor number iCur+i for the i-th index.
70946 **
70947 **   3.  The "iCur" cursor must be pointing to the row that is to be
70948 **       deleted.
70949 */
70950 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
70951   Parse *pParse,     /* Parsing and code generating context */
70952   Table *pTab,       /* Table containing the row to be deleted */
70953   int iCur,          /* Cursor number for the table */
70954   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
70955 ){
70956   int i;
70957   Index *pIdx;
70958   int r1;
70959
70960   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
70961     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
70962     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
70963     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
70964   }
70965 }
70966
70967 /*
70968 ** Generate code that will assemble an index key and put it in register
70969 ** regOut.  The key with be for index pIdx which is an index on pTab.
70970 ** iCur is the index of a cursor open on the pTab table and pointing to
70971 ** the entry that needs indexing.
70972 **
70973 ** Return a register number which is the first in a block of
70974 ** registers that holds the elements of the index key.  The
70975 ** block of registers has already been deallocated by the time
70976 ** this routine returns.
70977 */
70978 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
70979   Parse *pParse,     /* Parsing context */
70980   Index *pIdx,       /* The index for which to generate a key */
70981   int iCur,          /* Cursor number for the pIdx->pTable table */
70982   int regOut,        /* Write the new index key to this register */
70983   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
70984 ){
70985   Vdbe *v = pParse->pVdbe;
70986   int j;
70987   Table *pTab = pIdx->pTable;
70988   int regBase;
70989   int nCol;
70990
70991   nCol = pIdx->nColumn;
70992   regBase = sqlite3GetTempRange(pParse, nCol+1);
70993   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
70994   for(j=0; j<nCol; j++){
70995     int idx = pIdx->aiColumn[j];
70996     if( idx==pTab->iPKey ){
70997       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
70998     }else{
70999       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
71000       sqlite3ColumnDefault(v, pTab, idx, -1);
71001     }
71002   }
71003   if( doMakeRec ){
71004     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
71005     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
71006   }
71007   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
71008   return regBase;
71009 }
71010
71011 /************** End of delete.c **********************************************/
71012 /************** Begin file func.c ********************************************/
71013 /*
71014 ** 2002 February 23
71015 **
71016 ** The author disclaims copyright to this source code.  In place of
71017 ** a legal notice, here is a blessing:
71018 **
71019 **    May you do good and not evil.
71020 **    May you find forgiveness for yourself and forgive others.
71021 **    May you share freely, never taking more than you give.
71022 **
71023 *************************************************************************
71024 ** This file contains the C functions that implement various SQL
71025 ** functions of SQLite.  
71026 **
71027 ** There is only one exported symbol in this file - the function
71028 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
71029 ** All other code has file scope.
71030 */
71031
71032 /*
71033 ** Return the collating function associated with a function.
71034 */
71035 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
71036   return context->pColl;
71037 }
71038
71039 /*
71040 ** Implementation of the non-aggregate min() and max() functions
71041 */
71042 static void minmaxFunc(
71043   sqlite3_context *context,
71044   int argc,
71045   sqlite3_value **argv
71046 ){
71047   int i;
71048   int mask;    /* 0 for min() or 0xffffffff for max() */
71049   int iBest;
71050   CollSeq *pColl;
71051
71052   assert( argc>1 );
71053   mask = sqlite3_user_data(context)==0 ? 0 : -1;
71054   pColl = sqlite3GetFuncCollSeq(context);
71055   assert( pColl );
71056   assert( mask==-1 || mask==0 );
71057   iBest = 0;
71058   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
71059   for(i=1; i<argc; i++){
71060     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
71061     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
71062       testcase( mask==0 );
71063       iBest = i;
71064     }
71065   }
71066   sqlite3_result_value(context, argv[iBest]);
71067 }
71068
71069 /*
71070 ** Return the type of the argument.
71071 */
71072 static void typeofFunc(
71073   sqlite3_context *context,
71074   int NotUsed,
71075   sqlite3_value **argv
71076 ){
71077   const char *z = 0;
71078   UNUSED_PARAMETER(NotUsed);
71079   switch( sqlite3_value_type(argv[0]) ){
71080     case SQLITE_INTEGER: z = "integer"; break;
71081     case SQLITE_TEXT:    z = "text";    break;
71082     case SQLITE_FLOAT:   z = "real";    break;
71083     case SQLITE_BLOB:    z = "blob";    break;
71084     default:             z = "null";    break;
71085   }
71086   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
71087 }
71088
71089
71090 /*
71091 ** Implementation of the length() function
71092 */
71093 static void lengthFunc(
71094   sqlite3_context *context,
71095   int argc,
71096   sqlite3_value **argv
71097 ){
71098   int len;
71099
71100   assert( argc==1 );
71101   UNUSED_PARAMETER(argc);
71102   switch( sqlite3_value_type(argv[0]) ){
71103     case SQLITE_BLOB:
71104     case SQLITE_INTEGER:
71105     case SQLITE_FLOAT: {
71106       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
71107       break;
71108     }
71109     case SQLITE_TEXT: {
71110       const unsigned char *z = sqlite3_value_text(argv[0]);
71111       if( z==0 ) return;
71112       len = 0;
71113       while( *z ){
71114         len++;
71115         SQLITE_SKIP_UTF8(z);
71116       }
71117       sqlite3_result_int(context, len);
71118       break;
71119     }
71120     default: {
71121       sqlite3_result_null(context);
71122       break;
71123     }
71124   }
71125 }
71126
71127 /*
71128 ** Implementation of the abs() function.
71129 **
71130 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
71131 ** the numeric argument X. 
71132 */
71133 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71134   assert( argc==1 );
71135   UNUSED_PARAMETER(argc);
71136   switch( sqlite3_value_type(argv[0]) ){
71137     case SQLITE_INTEGER: {
71138       i64 iVal = sqlite3_value_int64(argv[0]);
71139       if( iVal<0 ){
71140         if( (iVal<<1)==0 ){
71141           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
71142           ** abs(X) throws an integer overflow error since there is no
71143           ** equivalent positive 64-bit two complement value. */
71144           sqlite3_result_error(context, "integer overflow", -1);
71145           return;
71146         }
71147         iVal = -iVal;
71148       } 
71149       sqlite3_result_int64(context, iVal);
71150       break;
71151     }
71152     case SQLITE_NULL: {
71153       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
71154       sqlite3_result_null(context);
71155       break;
71156     }
71157     default: {
71158       /* Because sqlite3_value_double() returns 0.0 if the argument is not
71159       ** something that can be converted into a number, we have:
71160       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
71161       ** cannot be converted to a numeric value. 
71162       */
71163       double rVal = sqlite3_value_double(argv[0]);
71164       if( rVal<0 ) rVal = -rVal;
71165       sqlite3_result_double(context, rVal);
71166       break;
71167     }
71168   }
71169 }
71170
71171 /*
71172 ** Implementation of the substr() function.
71173 **
71174 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
71175 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
71176 ** of x.  If x is text, then we actually count UTF-8 characters.
71177 ** If x is a blob, then we count bytes.
71178 **
71179 ** If p1 is negative, then we begin abs(p1) from the end of x[].
71180 **
71181 ** If p2 is negative, return the p2 characters preceeding p1.
71182 */
71183 static void substrFunc(
71184   sqlite3_context *context,
71185   int argc,
71186   sqlite3_value **argv
71187 ){
71188   const unsigned char *z;
71189   const unsigned char *z2;
71190   int len;
71191   int p0type;
71192   i64 p1, p2;
71193   int negP2 = 0;
71194
71195   assert( argc==3 || argc==2 );
71196   if( sqlite3_value_type(argv[1])==SQLITE_NULL
71197    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
71198   ){
71199     return;
71200   }
71201   p0type = sqlite3_value_type(argv[0]);
71202   p1 = sqlite3_value_int(argv[1]);
71203   if( p0type==SQLITE_BLOB ){
71204     len = sqlite3_value_bytes(argv[0]);
71205     z = sqlite3_value_blob(argv[0]);
71206     if( z==0 ) return;
71207     assert( len==sqlite3_value_bytes(argv[0]) );
71208   }else{
71209     z = sqlite3_value_text(argv[0]);
71210     if( z==0 ) return;
71211     len = 0;
71212     if( p1<0 ){
71213       for(z2=z; *z2; len++){
71214         SQLITE_SKIP_UTF8(z2);
71215       }
71216     }
71217   }
71218   if( argc==3 ){
71219     p2 = sqlite3_value_int(argv[2]);
71220     if( p2<0 ){
71221       p2 = -p2;
71222       negP2 = 1;
71223     }
71224   }else{
71225     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
71226   }
71227   if( p1<0 ){
71228     p1 += len;
71229     if( p1<0 ){
71230       p2 += p1;
71231       if( p2<0 ) p2 = 0;
71232       p1 = 0;
71233     }
71234   }else if( p1>0 ){
71235     p1--;
71236   }else if( p2>0 ){
71237     p2--;
71238   }
71239   if( negP2 ){
71240     p1 -= p2;
71241     if( p1<0 ){
71242       p2 += p1;
71243       p1 = 0;
71244     }
71245   }
71246   assert( p1>=0 && p2>=0 );
71247   if( p0type!=SQLITE_BLOB ){
71248     while( *z && p1 ){
71249       SQLITE_SKIP_UTF8(z);
71250       p1--;
71251     }
71252     for(z2=z; *z2 && p2; p2--){
71253       SQLITE_SKIP_UTF8(z2);
71254     }
71255     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
71256   }else{
71257     if( p1+p2>len ){
71258       p2 = len-p1;
71259       if( p2<0 ) p2 = 0;
71260     }
71261     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
71262   }
71263 }
71264
71265 /*
71266 ** Implementation of the round() function
71267 */
71268 #ifndef SQLITE_OMIT_FLOATING_POINT
71269 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71270   int n = 0;
71271   double r;
71272   char *zBuf;
71273   assert( argc==1 || argc==2 );
71274   if( argc==2 ){
71275     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
71276     n = sqlite3_value_int(argv[1]);
71277     if( n>30 ) n = 30;
71278     if( n<0 ) n = 0;
71279   }
71280   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
71281   r = sqlite3_value_double(argv[0]);
71282   zBuf = sqlite3_mprintf("%.*f",n,r);
71283   if( zBuf==0 ){
71284     sqlite3_result_error_nomem(context);
71285   }else{
71286     sqlite3AtoF(zBuf, &r);
71287     sqlite3_free(zBuf);
71288     sqlite3_result_double(context, r);
71289   }
71290 }
71291 #endif
71292
71293 /*
71294 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
71295 ** allocation fails, call sqlite3_result_error_nomem() to notify
71296 ** the database handle that malloc() has failed and return NULL.
71297 ** If nByte is larger than the maximum string or blob length, then
71298 ** raise an SQLITE_TOOBIG exception and return NULL.
71299 */
71300 static void *contextMalloc(sqlite3_context *context, i64 nByte){
71301   char *z;
71302   sqlite3 *db = sqlite3_context_db_handle(context);
71303   assert( nByte>0 );
71304   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
71305   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
71306   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
71307     sqlite3_result_error_toobig(context);
71308     z = 0;
71309   }else{
71310     z = sqlite3Malloc((int)nByte);
71311     if( !z ){
71312       sqlite3_result_error_nomem(context);
71313     }
71314   }
71315   return z;
71316 }
71317
71318 /*
71319 ** Implementation of the upper() and lower() SQL functions.
71320 */
71321 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71322   char *z1;
71323   const char *z2;
71324   int i, n;
71325   UNUSED_PARAMETER(argc);
71326   z2 = (char*)sqlite3_value_text(argv[0]);
71327   n = sqlite3_value_bytes(argv[0]);
71328   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
71329   assert( z2==(char*)sqlite3_value_text(argv[0]) );
71330   if( z2 ){
71331     z1 = contextMalloc(context, ((i64)n)+1);
71332     if( z1 ){
71333       memcpy(z1, z2, n+1);
71334       for(i=0; z1[i]; i++){
71335         z1[i] = (char)sqlite3Toupper(z1[i]);
71336       }
71337       sqlite3_result_text(context, z1, -1, sqlite3_free);
71338     }
71339   }
71340 }
71341 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71342   u8 *z1;
71343   const char *z2;
71344   int i, n;
71345   UNUSED_PARAMETER(argc);
71346   z2 = (char*)sqlite3_value_text(argv[0]);
71347   n = sqlite3_value_bytes(argv[0]);
71348   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
71349   assert( z2==(char*)sqlite3_value_text(argv[0]) );
71350   if( z2 ){
71351     z1 = contextMalloc(context, ((i64)n)+1);
71352     if( z1 ){
71353       memcpy(z1, z2, n+1);
71354       for(i=0; z1[i]; i++){
71355         z1[i] = sqlite3Tolower(z1[i]);
71356       }
71357       sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
71358     }
71359   }
71360 }
71361
71362
71363 #if 0  /* This function is never used. */
71364 /*
71365 ** The COALESCE() and IFNULL() functions used to be implemented as shown
71366 ** here.  But now they are implemented as VDBE code so that unused arguments
71367 ** do not have to be computed.  This legacy implementation is retained as
71368 ** comment.
71369 */
71370 /*
71371 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
71372 ** All three do the same thing.  They return the first non-NULL
71373 ** argument.
71374 */
71375 static void ifnullFunc(
71376   sqlite3_context *context,
71377   int argc,
71378   sqlite3_value **argv
71379 ){
71380   int i;
71381   for(i=0; i<argc; i++){
71382     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
71383       sqlite3_result_value(context, argv[i]);
71384       break;
71385     }
71386   }
71387 }
71388 #endif /* NOT USED */
71389 #define ifnullFunc versionFunc   /* Substitute function - never called */
71390
71391 /*
71392 ** Implementation of random().  Return a random integer.  
71393 */
71394 static void randomFunc(
71395   sqlite3_context *context,
71396   int NotUsed,
71397   sqlite3_value **NotUsed2
71398 ){
71399   sqlite_int64 r;
71400   UNUSED_PARAMETER2(NotUsed, NotUsed2);
71401   sqlite3_randomness(sizeof(r), &r);
71402   if( r<0 ){
71403     /* We need to prevent a random number of 0x8000000000000000 
71404     ** (or -9223372036854775808) since when you do abs() of that
71405     ** number of you get the same value back again.  To do this
71406     ** in a way that is testable, mask the sign bit off of negative
71407     ** values, resulting in a positive value.  Then take the 
71408     ** 2s complement of that positive value.  The end result can
71409     ** therefore be no less than -9223372036854775807.
71410     */
71411     r = -(r ^ (((sqlite3_int64)1)<<63));
71412   }
71413   sqlite3_result_int64(context, r);
71414 }
71415
71416 /*
71417 ** Implementation of randomblob(N).  Return a random blob
71418 ** that is N bytes long.
71419 */
71420 static void randomBlob(
71421   sqlite3_context *context,
71422   int argc,
71423   sqlite3_value **argv
71424 ){
71425   int n;
71426   unsigned char *p;
71427   assert( argc==1 );
71428   UNUSED_PARAMETER(argc);
71429   n = sqlite3_value_int(argv[0]);
71430   if( n<1 ){
71431     n = 1;
71432   }
71433   p = contextMalloc(context, n);
71434   if( p ){
71435     sqlite3_randomness(n, p);
71436     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
71437   }
71438 }
71439
71440 /*
71441 ** Implementation of the last_insert_rowid() SQL function.  The return
71442 ** value is the same as the sqlite3_last_insert_rowid() API function.
71443 */
71444 static void last_insert_rowid(
71445   sqlite3_context *context, 
71446   int NotUsed, 
71447   sqlite3_value **NotUsed2
71448 ){
71449   sqlite3 *db = sqlite3_context_db_handle(context);
71450   UNUSED_PARAMETER2(NotUsed, NotUsed2);
71451   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
71452 }
71453
71454 /*
71455 ** Implementation of the changes() SQL function.  The return value is the
71456 ** same as the sqlite3_changes() API function.
71457 */
71458 static void changes(
71459   sqlite3_context *context,
71460   int NotUsed,
71461   sqlite3_value **NotUsed2
71462 ){
71463   sqlite3 *db = sqlite3_context_db_handle(context);
71464   UNUSED_PARAMETER2(NotUsed, NotUsed2);
71465   sqlite3_result_int(context, sqlite3_changes(db));
71466 }
71467
71468 /*
71469 ** Implementation of the total_changes() SQL function.  The return value is
71470 ** the same as the sqlite3_total_changes() API function.
71471 */
71472 static void total_changes(
71473   sqlite3_context *context,
71474   int NotUsed,
71475   sqlite3_value **NotUsed2
71476 ){
71477   sqlite3 *db = sqlite3_context_db_handle(context);
71478   UNUSED_PARAMETER2(NotUsed, NotUsed2);
71479   sqlite3_result_int(context, sqlite3_total_changes(db));
71480 }
71481
71482 /*
71483 ** A structure defining how to do GLOB-style comparisons.
71484 */
71485 struct compareInfo {
71486   u8 matchAll;
71487   u8 matchOne;
71488   u8 matchSet;
71489   u8 noCase;
71490 };
71491
71492 /*
71493 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
71494 ** character is exactly one byte in size.  Also, all characters are
71495 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
71496 ** whereas only characters less than 0x80 do in ASCII.
71497 */
71498 #if defined(SQLITE_EBCDIC)
71499 # define sqlite3Utf8Read(A,C)    (*(A++))
71500 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
71501 #else
71502 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
71503 #endif
71504
71505 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
71506 /* The correct SQL-92 behavior is for the LIKE operator to ignore
71507 ** case.  Thus  'a' LIKE 'A' would be true. */
71508 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
71509 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
71510 ** is case sensitive causing 'a' LIKE 'A' to be false */
71511 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
71512
71513 /*
71514 ** Compare two UTF-8 strings for equality where the first string can
71515 ** potentially be a "glob" expression.  Return true (1) if they
71516 ** are the same and false (0) if they are different.
71517 **
71518 ** Globbing rules:
71519 **
71520 **      '*'       Matches any sequence of zero or more characters.
71521 **
71522 **      '?'       Matches exactly one character.
71523 **
71524 **     [...]      Matches one character from the enclosed list of
71525 **                characters.
71526 **
71527 **     [^...]     Matches one character not in the enclosed list.
71528 **
71529 ** With the [...] and [^...] matching, a ']' character can be included
71530 ** in the list by making it the first character after '[' or '^'.  A
71531 ** range of characters can be specified using '-'.  Example:
71532 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
71533 ** it the last character in the list.
71534 **
71535 ** This routine is usually quick, but can be N**2 in the worst case.
71536 **
71537 ** Hints: to match '*' or '?', put them in "[]".  Like this:
71538 **
71539 **         abc[*]xyz        Matches "abc*xyz" only
71540 */
71541 static int patternCompare(
71542   const u8 *zPattern,              /* The glob pattern */
71543   const u8 *zString,               /* The string to compare against the glob */
71544   const struct compareInfo *pInfo, /* Information about how to do the compare */
71545   const int esc                    /* The escape character */
71546 ){
71547   int c, c2;
71548   int invert;
71549   int seen;
71550   u8 matchOne = pInfo->matchOne;
71551   u8 matchAll = pInfo->matchAll;
71552   u8 matchSet = pInfo->matchSet;
71553   u8 noCase = pInfo->noCase; 
71554   int prevEscape = 0;     /* True if the previous character was 'escape' */
71555
71556   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
71557     if( !prevEscape && c==matchAll ){
71558       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
71559                || c == matchOne ){
71560         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
71561           return 0;
71562         }
71563       }
71564       if( c==0 ){
71565         return 1;
71566       }else if( c==esc ){
71567         c = sqlite3Utf8Read(zPattern, &zPattern);
71568         if( c==0 ){
71569           return 0;
71570         }
71571       }else if( c==matchSet ){
71572         assert( esc==0 );         /* This is GLOB, not LIKE */
71573         assert( matchSet<0x80 );  /* '[' is a single-byte character */
71574         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
71575           SQLITE_SKIP_UTF8(zString);
71576         }
71577         return *zString!=0;
71578       }
71579       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
71580         if( noCase ){
71581           GlogUpperToLower(c2);
71582           GlogUpperToLower(c);
71583           while( c2 != 0 && c2 != c ){
71584             c2 = sqlite3Utf8Read(zString, &zString);
71585             GlogUpperToLower(c2);
71586           }
71587         }else{
71588           while( c2 != 0 && c2 != c ){
71589             c2 = sqlite3Utf8Read(zString, &zString);
71590           }
71591         }
71592         if( c2==0 ) return 0;
71593         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
71594       }
71595       return 0;
71596     }else if( !prevEscape && c==matchOne ){
71597       if( sqlite3Utf8Read(zString, &zString)==0 ){
71598         return 0;
71599       }
71600     }else if( c==matchSet ){
71601       int prior_c = 0;
71602       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
71603       seen = 0;
71604       invert = 0;
71605       c = sqlite3Utf8Read(zString, &zString);
71606       if( c==0 ) return 0;
71607       c2 = sqlite3Utf8Read(zPattern, &zPattern);
71608       if( c2=='^' ){
71609         invert = 1;
71610         c2 = sqlite3Utf8Read(zPattern, &zPattern);
71611       }
71612       if( c2==']' ){
71613         if( c==']' ) seen = 1;
71614         c2 = sqlite3Utf8Read(zPattern, &zPattern);
71615       }
71616       while( c2 && c2!=']' ){
71617         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
71618           c2 = sqlite3Utf8Read(zPattern, &zPattern);
71619           if( c>=prior_c && c<=c2 ) seen = 1;
71620           prior_c = 0;
71621         }else{
71622           if( c==c2 ){
71623             seen = 1;
71624           }
71625           prior_c = c2;
71626         }
71627         c2 = sqlite3Utf8Read(zPattern, &zPattern);
71628       }
71629       if( c2==0 || (seen ^ invert)==0 ){
71630         return 0;
71631       }
71632     }else if( esc==c && !prevEscape ){
71633       prevEscape = 1;
71634     }else{
71635       c2 = sqlite3Utf8Read(zString, &zString);
71636       if( noCase ){
71637         GlogUpperToLower(c);
71638         GlogUpperToLower(c2);
71639       }
71640       if( c!=c2 ){
71641         return 0;
71642       }
71643       prevEscape = 0;
71644     }
71645   }
71646   return *zString==0;
71647 }
71648
71649 /*
71650 ** Count the number of times that the LIKE operator (or GLOB which is
71651 ** just a variation of LIKE) gets called.  This is used for testing
71652 ** only.
71653 */
71654 #ifdef SQLITE_TEST
71655 SQLITE_API int sqlite3_like_count = 0;
71656 #endif
71657
71658
71659 /*
71660 ** Implementation of the like() SQL function.  This function implements
71661 ** the build-in LIKE operator.  The first argument to the function is the
71662 ** pattern and the second argument is the string.  So, the SQL statements:
71663 **
71664 **       A LIKE B
71665 **
71666 ** is implemented as like(B,A).
71667 **
71668 ** This same function (with a different compareInfo structure) computes
71669 ** the GLOB operator.
71670 */
71671 static void likeFunc(
71672   sqlite3_context *context, 
71673   int argc, 
71674   sqlite3_value **argv
71675 ){
71676   const unsigned char *zA, *zB;
71677   int escape = 0;
71678   int nPat;
71679   sqlite3 *db = sqlite3_context_db_handle(context);
71680
71681   zB = sqlite3_value_text(argv[0]);
71682   zA = sqlite3_value_text(argv[1]);
71683
71684   /* Limit the length of the LIKE or GLOB pattern to avoid problems
71685   ** of deep recursion and N*N behavior in patternCompare().
71686   */
71687   nPat = sqlite3_value_bytes(argv[0]);
71688   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
71689   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
71690   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
71691     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
71692     return;
71693   }
71694   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
71695
71696   if( argc==3 ){
71697     /* The escape character string must consist of a single UTF-8 character.
71698     ** Otherwise, return an error.
71699     */
71700     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
71701     if( zEsc==0 ) return;
71702     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
71703       sqlite3_result_error(context, 
71704           "ESCAPE expression must be a single character", -1);
71705       return;
71706     }
71707     escape = sqlite3Utf8Read(zEsc, &zEsc);
71708   }
71709   if( zA && zB ){
71710     struct compareInfo *pInfo = sqlite3_user_data(context);
71711 #ifdef SQLITE_TEST
71712     sqlite3_like_count++;
71713 #endif
71714     
71715     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
71716   }
71717 }
71718
71719 /*
71720 ** Implementation of the NULLIF(x,y) function.  The result is the first
71721 ** argument if the arguments are different.  The result is NULL if the
71722 ** arguments are equal to each other.
71723 */
71724 static void nullifFunc(
71725   sqlite3_context *context,
71726   int NotUsed,
71727   sqlite3_value **argv
71728 ){
71729   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
71730   UNUSED_PARAMETER(NotUsed);
71731   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
71732     sqlite3_result_value(context, argv[0]);
71733   }
71734 }
71735
71736 /*
71737 ** Implementation of the sqlite_version() function.  The result is the version
71738 ** of the SQLite library that is running.
71739 */
71740 static void versionFunc(
71741   sqlite3_context *context,
71742   int NotUsed,
71743   sqlite3_value **NotUsed2
71744 ){
71745   UNUSED_PARAMETER2(NotUsed, NotUsed2);
71746   sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
71747 }
71748
71749 /*
71750 ** Implementation of the sqlite_source_id() function. The result is a string
71751 ** that identifies the particular version of the source code used to build
71752 ** SQLite.
71753 */
71754 static void sourceidFunc(
71755   sqlite3_context *context,
71756   int NotUsed,
71757   sqlite3_value **NotUsed2
71758 ){
71759   UNUSED_PARAMETER2(NotUsed, NotUsed2);
71760   sqlite3_result_text(context, SQLITE_SOURCE_ID, -1, SQLITE_STATIC);
71761 }
71762
71763 /* Array for converting from half-bytes (nybbles) into ASCII hex
71764 ** digits. */
71765 static const char hexdigits[] = {
71766   '0', '1', '2', '3', '4', '5', '6', '7',
71767   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
71768 };
71769
71770 /*
71771 ** EXPERIMENTAL - This is not an official function.  The interface may
71772 ** change.  This function may disappear.  Do not write code that depends
71773 ** on this function.
71774 **
71775 ** Implementation of the QUOTE() function.  This function takes a single
71776 ** argument.  If the argument is numeric, the return value is the same as
71777 ** the argument.  If the argument is NULL, the return value is the string
71778 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
71779 ** single-quote escapes.
71780 */
71781 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71782   assert( argc==1 );
71783   UNUSED_PARAMETER(argc);
71784   switch( sqlite3_value_type(argv[0]) ){
71785     case SQLITE_INTEGER:
71786     case SQLITE_FLOAT: {
71787       sqlite3_result_value(context, argv[0]);
71788       break;
71789     }
71790     case SQLITE_BLOB: {
71791       char *zText = 0;
71792       char const *zBlob = sqlite3_value_blob(argv[0]);
71793       int nBlob = sqlite3_value_bytes(argv[0]);
71794       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
71795       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
71796       if( zText ){
71797         int i;
71798         for(i=0; i<nBlob; i++){
71799           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
71800           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
71801         }
71802         zText[(nBlob*2)+2] = '\'';
71803         zText[(nBlob*2)+3] = '\0';
71804         zText[0] = 'X';
71805         zText[1] = '\'';
71806         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
71807         sqlite3_free(zText);
71808       }
71809       break;
71810     }
71811     case SQLITE_TEXT: {
71812       int i,j;
71813       u64 n;
71814       const unsigned char *zArg = sqlite3_value_text(argv[0]);
71815       char *z;
71816
71817       if( zArg==0 ) return;
71818       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
71819       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
71820       if( z ){
71821         z[0] = '\'';
71822         for(i=0, j=1; zArg[i]; i++){
71823           z[j++] = zArg[i];
71824           if( zArg[i]=='\'' ){
71825             z[j++] = '\'';
71826           }
71827         }
71828         z[j++] = '\'';
71829         z[j] = 0;
71830         sqlite3_result_text(context, z, j, sqlite3_free);
71831       }
71832       break;
71833     }
71834     default: {
71835       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
71836       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
71837       break;
71838     }
71839   }
71840 }
71841
71842 /*
71843 ** The hex() function.  Interpret the argument as a blob.  Return
71844 ** a hexadecimal rendering as text.
71845 */
71846 static void hexFunc(
71847   sqlite3_context *context,
71848   int argc,
71849   sqlite3_value **argv
71850 ){
71851   int i, n;
71852   const unsigned char *pBlob;
71853   char *zHex, *z;
71854   assert( argc==1 );
71855   UNUSED_PARAMETER(argc);
71856   pBlob = sqlite3_value_blob(argv[0]);
71857   n = sqlite3_value_bytes(argv[0]);
71858   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
71859   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
71860   if( zHex ){
71861     for(i=0; i<n; i++, pBlob++){
71862       unsigned char c = *pBlob;
71863       *(z++) = hexdigits[(c>>4)&0xf];
71864       *(z++) = hexdigits[c&0xf];
71865     }
71866     *z = 0;
71867     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
71868   }
71869 }
71870
71871 /*
71872 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
71873 */
71874 static void zeroblobFunc(
71875   sqlite3_context *context,
71876   int argc,
71877   sqlite3_value **argv
71878 ){
71879   i64 n;
71880   sqlite3 *db = sqlite3_context_db_handle(context);
71881   assert( argc==1 );
71882   UNUSED_PARAMETER(argc);
71883   n = sqlite3_value_int64(argv[0]);
71884   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
71885   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
71886   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
71887     sqlite3_result_error_toobig(context);
71888   }else{
71889     sqlite3_result_zeroblob(context, (int)n);
71890   }
71891 }
71892
71893 /*
71894 ** The replace() function.  Three arguments are all strings: call
71895 ** them A, B, and C. The result is also a string which is derived
71896 ** from A by replacing every occurance of B with C.  The match
71897 ** must be exact.  Collating sequences are not used.
71898 */
71899 static void replaceFunc(
71900   sqlite3_context *context,
71901   int argc,
71902   sqlite3_value **argv
71903 ){
71904   const unsigned char *zStr;        /* The input string A */
71905   const unsigned char *zPattern;    /* The pattern string B */
71906   const unsigned char *zRep;        /* The replacement string C */
71907   unsigned char *zOut;              /* The output */
71908   int nStr;                /* Size of zStr */
71909   int nPattern;            /* Size of zPattern */
71910   int nRep;                /* Size of zRep */
71911   i64 nOut;                /* Maximum size of zOut */
71912   int loopLimit;           /* Last zStr[] that might match zPattern[] */
71913   int i, j;                /* Loop counters */
71914
71915   assert( argc==3 );
71916   UNUSED_PARAMETER(argc);
71917   zStr = sqlite3_value_text(argv[0]);
71918   if( zStr==0 ) return;
71919   nStr = sqlite3_value_bytes(argv[0]);
71920   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
71921   zPattern = sqlite3_value_text(argv[1]);
71922   if( zPattern==0 ){
71923     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
71924             || sqlite3_context_db_handle(context)->mallocFailed );
71925     return;
71926   }
71927   if( zPattern[0]==0 ){
71928     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
71929     sqlite3_result_value(context, argv[0]);
71930     return;
71931   }
71932   nPattern = sqlite3_value_bytes(argv[1]);
71933   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
71934   zRep = sqlite3_value_text(argv[2]);
71935   if( zRep==0 ) return;
71936   nRep = sqlite3_value_bytes(argv[2]);
71937   assert( zRep==sqlite3_value_text(argv[2]) );
71938   nOut = nStr + 1;
71939   assert( nOut<SQLITE_MAX_LENGTH );
71940   zOut = contextMalloc(context, (i64)nOut);
71941   if( zOut==0 ){
71942     return;
71943   }
71944   loopLimit = nStr - nPattern;  
71945   for(i=j=0; i<=loopLimit; i++){
71946     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
71947       zOut[j++] = zStr[i];
71948     }else{
71949       u8 *zOld;
71950       sqlite3 *db = sqlite3_context_db_handle(context);
71951       nOut += nRep - nPattern;
71952       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
71953       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
71954       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
71955         sqlite3_result_error_toobig(context);
71956         sqlite3DbFree(db, zOut);
71957         return;
71958       }
71959       zOld = zOut;
71960       zOut = sqlite3_realloc(zOut, (int)nOut);
71961       if( zOut==0 ){
71962         sqlite3_result_error_nomem(context);
71963         sqlite3DbFree(db, zOld);
71964         return;
71965       }
71966       memcpy(&zOut[j], zRep, nRep);
71967       j += nRep;
71968       i += nPattern-1;
71969     }
71970   }
71971   assert( j+nStr-i+1==nOut );
71972   memcpy(&zOut[j], &zStr[i], nStr-i);
71973   j += nStr - i;
71974   assert( j<=nOut );
71975   zOut[j] = 0;
71976   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
71977 }
71978
71979 /*
71980 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
71981 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
71982 */
71983 static void trimFunc(
71984   sqlite3_context *context,
71985   int argc,
71986   sqlite3_value **argv
71987 ){
71988   const unsigned char *zIn;         /* Input string */
71989   const unsigned char *zCharSet;    /* Set of characters to trim */
71990   int nIn;                          /* Number of bytes in input */
71991   int flags;                        /* 1: trimleft  2: trimright  3: trim */
71992   int i;                            /* Loop counter */
71993   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
71994   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
71995   int nChar;                        /* Number of characters in zCharSet */
71996
71997   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
71998     return;
71999   }
72000   zIn = sqlite3_value_text(argv[0]);
72001   if( zIn==0 ) return;
72002   nIn = sqlite3_value_bytes(argv[0]);
72003   assert( zIn==sqlite3_value_text(argv[0]) );
72004   if( argc==1 ){
72005     static const unsigned char lenOne[] = { 1 };
72006     static unsigned char * const azOne[] = { (u8*)" " };
72007     nChar = 1;
72008     aLen = (u8*)lenOne;
72009     azChar = (unsigned char **)azOne;
72010     zCharSet = 0;
72011   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
72012     return;
72013   }else{
72014     const unsigned char *z;
72015     for(z=zCharSet, nChar=0; *z; nChar++){
72016       SQLITE_SKIP_UTF8(z);
72017     }
72018     if( nChar>0 ){
72019       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
72020       if( azChar==0 ){
72021         return;
72022       }
72023       aLen = (unsigned char*)&azChar[nChar];
72024       for(z=zCharSet, nChar=0; *z; nChar++){
72025         azChar[nChar] = (unsigned char *)z;
72026         SQLITE_SKIP_UTF8(z);
72027         aLen[nChar] = (u8)(z - azChar[nChar]);
72028       }
72029     }
72030   }
72031   if( nChar>0 ){
72032     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
72033     if( flags & 1 ){
72034       while( nIn>0 ){
72035         int len = 0;
72036         for(i=0; i<nChar; i++){
72037           len = aLen[i];
72038           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
72039         }
72040         if( i>=nChar ) break;
72041         zIn += len;
72042         nIn -= len;
72043       }
72044     }
72045     if( flags & 2 ){
72046       while( nIn>0 ){
72047         int len = 0;
72048         for(i=0; i<nChar; i++){
72049           len = aLen[i];
72050           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
72051         }
72052         if( i>=nChar ) break;
72053         nIn -= len;
72054       }
72055     }
72056     if( zCharSet ){
72057       sqlite3_free(azChar);
72058     }
72059   }
72060   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
72061 }
72062
72063
72064 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
72065 ** is only available if the SQLITE_SOUNDEX compile-time option is used
72066 ** when SQLite is built.
72067 */
72068 #ifdef SQLITE_SOUNDEX
72069 /*
72070 ** Compute the soundex encoding of a word.
72071 **
72072 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
72073 ** soundex encoding of the string X. 
72074 */
72075 static void soundexFunc(
72076   sqlite3_context *context,
72077   int argc,
72078   sqlite3_value **argv
72079 ){
72080   char zResult[8];
72081   const u8 *zIn;
72082   int i, j;
72083   static const unsigned char iCode[] = {
72084     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72085     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72086     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72087     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72088     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
72089     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
72090     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
72091     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
72092   };
72093   assert( argc==1 );
72094   zIn = (u8*)sqlite3_value_text(argv[0]);
72095   if( zIn==0 ) zIn = (u8*)"";
72096   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
72097   if( zIn[i] ){
72098     u8 prevcode = iCode[zIn[i]&0x7f];
72099     zResult[0] = sqlite3Toupper(zIn[i]);
72100     for(j=1; j<4 && zIn[i]; i++){
72101       int code = iCode[zIn[i]&0x7f];
72102       if( code>0 ){
72103         if( code!=prevcode ){
72104           prevcode = code;
72105           zResult[j++] = code + '0';
72106         }
72107       }else{
72108         prevcode = 0;
72109       }
72110     }
72111     while( j<4 ){
72112       zResult[j++] = '0';
72113     }
72114     zResult[j] = 0;
72115     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
72116   }else{
72117     /* IMP: R-64894-50321 The string "?000" is returned if the argument
72118     ** is NULL or contains no ASCII alphabetic characters. */
72119     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
72120   }
72121 }
72122 #endif /* SQLITE_SOUNDEX */
72123
72124 #ifndef SQLITE_OMIT_LOAD_EXTENSION
72125 /*
72126 ** A function that loads a shared-library extension then returns NULL.
72127 */
72128 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
72129   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
72130   const char *zProc;
72131   sqlite3 *db = sqlite3_context_db_handle(context);
72132   char *zErrMsg = 0;
72133
72134   if( argc==2 ){
72135     zProc = (const char *)sqlite3_value_text(argv[1]);
72136   }else{
72137     zProc = 0;
72138   }
72139   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
72140     sqlite3_result_error(context, zErrMsg, -1);
72141     sqlite3_free(zErrMsg);
72142   }
72143 }
72144 #endif
72145
72146
72147 /*
72148 ** An instance of the following structure holds the context of a
72149 ** sum() or avg() aggregate computation.
72150 */
72151 typedef struct SumCtx SumCtx;
72152 struct SumCtx {
72153   double rSum;      /* Floating point sum */
72154   i64 iSum;         /* Integer sum */   
72155   i64 cnt;          /* Number of elements summed */
72156   u8 overflow;      /* True if integer overflow seen */
72157   u8 approx;        /* True if non-integer value was input to the sum */
72158 };
72159
72160 /*
72161 ** Routines used to compute the sum, average, and total.
72162 **
72163 ** The SUM() function follows the (broken) SQL standard which means
72164 ** that it returns NULL if it sums over no inputs.  TOTAL returns
72165 ** 0.0 in that case.  In addition, TOTAL always returns a float where
72166 ** SUM might return an integer if it never encounters a floating point
72167 ** value.  TOTAL never fails, but SUM might through an exception if
72168 ** it overflows an integer.
72169 */
72170 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
72171   SumCtx *p;
72172   int type;
72173   assert( argc==1 );
72174   UNUSED_PARAMETER(argc);
72175   p = sqlite3_aggregate_context(context, sizeof(*p));
72176   type = sqlite3_value_numeric_type(argv[0]);
72177   if( p && type!=SQLITE_NULL ){
72178     p->cnt++;
72179     if( type==SQLITE_INTEGER ){
72180       i64 v = sqlite3_value_int64(argv[0]);
72181       p->rSum += v;
72182       if( (p->approx|p->overflow)==0 ){
72183         i64 iNewSum = p->iSum + v;
72184         int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
72185         int s2 = (int)(v       >> (sizeof(i64)*8-1));
72186         int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
72187         p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
72188         p->iSum = iNewSum;
72189       }
72190     }else{
72191       p->rSum += sqlite3_value_double(argv[0]);
72192       p->approx = 1;
72193     }
72194   }
72195 }
72196 static void sumFinalize(sqlite3_context *context){
72197   SumCtx *p;
72198   p = sqlite3_aggregate_context(context, 0);
72199   if( p && p->cnt>0 ){
72200     if( p->overflow ){
72201       sqlite3_result_error(context,"integer overflow",-1);
72202     }else if( p->approx ){
72203       sqlite3_result_double(context, p->rSum);
72204     }else{
72205       sqlite3_result_int64(context, p->iSum);
72206     }
72207   }
72208 }
72209 static void avgFinalize(sqlite3_context *context){
72210   SumCtx *p;
72211   p = sqlite3_aggregate_context(context, 0);
72212   if( p && p->cnt>0 ){
72213     sqlite3_result_double(context, p->rSum/(double)p->cnt);
72214   }
72215 }
72216 static void totalFinalize(sqlite3_context *context){
72217   SumCtx *p;
72218   p = sqlite3_aggregate_context(context, 0);
72219   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
72220   sqlite3_result_double(context, p ? p->rSum : (double)0);
72221 }
72222
72223 /*
72224 ** The following structure keeps track of state information for the
72225 ** count() aggregate function.
72226 */
72227 typedef struct CountCtx CountCtx;
72228 struct CountCtx {
72229   i64 n;
72230 };
72231
72232 /*
72233 ** Routines to implement the count() aggregate function.
72234 */
72235 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
72236   CountCtx *p;
72237   p = sqlite3_aggregate_context(context, sizeof(*p));
72238   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
72239     p->n++;
72240   }
72241
72242 #ifndef SQLITE_OMIT_DEPRECATED
72243   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
72244   ** sure it still operates correctly, verify that its count agrees with our 
72245   ** internal count when using count(*) and when the total count can be
72246   ** expressed as a 32-bit integer. */
72247   assert( argc==1 || p==0 || p->n>0x7fffffff
72248           || p->n==sqlite3_aggregate_count(context) );
72249 #endif
72250 }   
72251 static void countFinalize(sqlite3_context *context){
72252   CountCtx *p;
72253   p = sqlite3_aggregate_context(context, 0);
72254   sqlite3_result_int64(context, p ? p->n : 0);
72255 }
72256
72257 /*
72258 ** Routines to implement min() and max() aggregate functions.
72259 */
72260 static void minmaxStep(
72261   sqlite3_context *context, 
72262   int NotUsed, 
72263   sqlite3_value **argv
72264 ){
72265   Mem *pArg  = (Mem *)argv[0];
72266   Mem *pBest;
72267   UNUSED_PARAMETER(NotUsed);
72268
72269   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
72270   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
72271   if( !pBest ) return;
72272
72273   if( pBest->flags ){
72274     int max;
72275     int cmp;
72276     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
72277     /* This step function is used for both the min() and max() aggregates,
72278     ** the only difference between the two being that the sense of the
72279     ** comparison is inverted. For the max() aggregate, the
72280     ** sqlite3_user_data() function returns (void *)-1. For min() it
72281     ** returns (void *)db, where db is the sqlite3* database pointer.
72282     ** Therefore the next statement sets variable 'max' to 1 for the max()
72283     ** aggregate, or 0 for min().
72284     */
72285     max = sqlite3_user_data(context)!=0;
72286     cmp = sqlite3MemCompare(pBest, pArg, pColl);
72287     if( (max && cmp<0) || (!max && cmp>0) ){
72288       sqlite3VdbeMemCopy(pBest, pArg);
72289     }
72290   }else{
72291     sqlite3VdbeMemCopy(pBest, pArg);
72292   }
72293 }
72294 static void minMaxFinalize(sqlite3_context *context){
72295   sqlite3_value *pRes;
72296   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
72297   if( pRes ){
72298     if( ALWAYS(pRes->flags) ){
72299       sqlite3_result_value(context, pRes);
72300     }
72301     sqlite3VdbeMemRelease(pRes);
72302   }
72303 }
72304
72305 /*
72306 ** group_concat(EXPR, ?SEPARATOR?)
72307 */
72308 static void groupConcatStep(
72309   sqlite3_context *context,
72310   int argc,
72311   sqlite3_value **argv
72312 ){
72313   const char *zVal;
72314   StrAccum *pAccum;
72315   const char *zSep;
72316   int nVal, nSep;
72317   assert( argc==1 || argc==2 );
72318   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
72319   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
72320
72321   if( pAccum ){
72322     sqlite3 *db = sqlite3_context_db_handle(context);
72323     int firstTerm = pAccum->useMalloc==0;
72324     pAccum->useMalloc = 1;
72325     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
72326     if( !firstTerm ){
72327       if( argc==2 ){
72328         zSep = (char*)sqlite3_value_text(argv[1]);
72329         nSep = sqlite3_value_bytes(argv[1]);
72330       }else{
72331         zSep = ",";
72332         nSep = 1;
72333       }
72334       sqlite3StrAccumAppend(pAccum, zSep, nSep);
72335     }
72336     zVal = (char*)sqlite3_value_text(argv[0]);
72337     nVal = sqlite3_value_bytes(argv[0]);
72338     sqlite3StrAccumAppend(pAccum, zVal, nVal);
72339   }
72340 }
72341 static void groupConcatFinalize(sqlite3_context *context){
72342   StrAccum *pAccum;
72343   pAccum = sqlite3_aggregate_context(context, 0);
72344   if( pAccum ){
72345     if( pAccum->tooBig ){
72346       sqlite3_result_error_toobig(context);
72347     }else if( pAccum->mallocFailed ){
72348       sqlite3_result_error_nomem(context);
72349     }else{    
72350       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
72351                           sqlite3_free);
72352     }
72353   }
72354 }
72355
72356 /*
72357 ** This function registered all of the above C functions as SQL
72358 ** functions.  This should be the only routine in this file with
72359 ** external linkage.
72360 */
72361 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
72362 #ifndef SQLITE_OMIT_ALTERTABLE
72363   sqlite3AlterFunctions(db);
72364 #endif
72365   if( !db->mallocFailed ){
72366     int rc = sqlite3_overload_function(db, "MATCH", 2);
72367     assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
72368     if( rc==SQLITE_NOMEM ){
72369       db->mallocFailed = 1;
72370     }
72371   }
72372 }
72373
72374 /*
72375 ** Set the LIKEOPT flag on the 2-argument function with the given name.
72376 */
72377 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
72378   FuncDef *pDef;
72379   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
72380                              2, SQLITE_UTF8, 0);
72381   if( ALWAYS(pDef) ){
72382     pDef->flags = flagVal;
72383   }
72384 }
72385
72386 /*
72387 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
72388 ** parameter determines whether or not the LIKE operator is case
72389 ** sensitive.  GLOB is always case sensitive.
72390 */
72391 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
72392   struct compareInfo *pInfo;
72393   if( caseSensitive ){
72394     pInfo = (struct compareInfo*)&likeInfoAlt;
72395   }else{
72396     pInfo = (struct compareInfo*)&likeInfoNorm;
72397   }
72398   sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0);
72399   sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0);
72400   sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY, 
72401       (struct compareInfo*)&globInfo, likeFunc, 0,0);
72402   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
72403   setLikeOptFlag(db, "like", 
72404       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
72405 }
72406
72407 /*
72408 ** pExpr points to an expression which implements a function.  If
72409 ** it is appropriate to apply the LIKE optimization to that function
72410 ** then set aWc[0] through aWc[2] to the wildcard characters and
72411 ** return TRUE.  If the function is not a LIKE-style function then
72412 ** return FALSE.
72413 */
72414 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
72415   FuncDef *pDef;
72416   if( pExpr->op!=TK_FUNCTION 
72417    || !pExpr->x.pList 
72418    || pExpr->x.pList->nExpr!=2
72419   ){
72420     return 0;
72421   }
72422   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
72423   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
72424                              sqlite3Strlen30(pExpr->u.zToken),
72425                              2, SQLITE_UTF8, 0);
72426   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
72427     return 0;
72428   }
72429
72430   /* The memcpy() statement assumes that the wildcard characters are
72431   ** the first three statements in the compareInfo structure.  The
72432   ** asserts() that follow verify that assumption
72433   */
72434   memcpy(aWc, pDef->pUserData, 3);
72435   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
72436   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
72437   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
72438   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
72439   return 1;
72440 }
72441
72442 /*
72443 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
72444 ** to the global function hash table.  This occurs at start-time (as
72445 ** a consequence of calling sqlite3_initialize()).
72446 **
72447 ** After this routine runs
72448 */
72449 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
72450   /*
72451   ** The following array holds FuncDef structures for all of the functions
72452   ** defined in this file.
72453   **
72454   ** The array cannot be constant since changes are made to the
72455   ** FuncDef.pHash elements at start-time.  The elements of this array
72456   ** are read-only after initialization is complete.
72457   */
72458   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
72459     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
72460     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
72461     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
72462     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
72463     FUNCTION(trim,               1, 3, 0, trimFunc         ),
72464     FUNCTION(trim,               2, 3, 0, trimFunc         ),
72465     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
72466     FUNCTION(min,                0, 0, 1, 0                ),
72467     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
72468     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
72469     FUNCTION(max,                0, 1, 1, 0                ),
72470     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
72471     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
72472     FUNCTION(length,             1, 0, 0, lengthFunc       ),
72473     FUNCTION(substr,             2, 0, 0, substrFunc       ),
72474     FUNCTION(substr,             3, 0, 0, substrFunc       ),
72475     FUNCTION(abs,                1, 0, 0, absFunc          ),
72476 #ifndef SQLITE_OMIT_FLOATING_POINT
72477     FUNCTION(round,              1, 0, 0, roundFunc        ),
72478     FUNCTION(round,              2, 0, 0, roundFunc        ),
72479 #endif
72480     FUNCTION(upper,              1, 0, 0, upperFunc        ),
72481     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
72482     FUNCTION(coalesce,           1, 0, 0, 0                ),
72483     FUNCTION(coalesce,           0, 0, 0, 0                ),
72484 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
72485     {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0},
72486     FUNCTION(hex,                1, 0, 0, hexFunc          ),
72487 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
72488     {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0},
72489     FUNCTION(random,             0, 0, 0, randomFunc       ),
72490     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
72491     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
72492     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
72493     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
72494     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
72495     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
72496     FUNCTION(changes,            0, 0, 0, changes          ),
72497     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
72498     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
72499     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
72500   #ifdef SQLITE_SOUNDEX
72501     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
72502   #endif
72503   #ifndef SQLITE_OMIT_LOAD_EXTENSION
72504     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
72505     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
72506   #endif
72507     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
72508     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
72509     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
72510  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
72511     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0},
72512     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
72513     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
72514     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
72515   
72516     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
72517   #ifdef SQLITE_CASE_SENSITIVE_LIKE
72518     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
72519     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
72520   #else
72521     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
72522     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
72523   #endif
72524   };
72525
72526   int i;
72527   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
72528   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
72529
72530   for(i=0; i<ArraySize(aBuiltinFunc); i++){
72531     sqlite3FuncDefInsert(pHash, &aFunc[i]);
72532   }
72533   sqlite3RegisterDateTimeFunctions();
72534 }
72535
72536 /************** End of func.c ************************************************/
72537 /************** Begin file fkey.c ********************************************/
72538 /*
72539 **
72540 ** The author disclaims copyright to this source code.  In place of
72541 ** a legal notice, here is a blessing:
72542 **
72543 **    May you do good and not evil.
72544 **    May you find forgiveness for yourself and forgive others.
72545 **    May you share freely, never taking more than you give.
72546 **
72547 *************************************************************************
72548 ** This file contains code used by the compiler to add foreign key
72549 ** support to compiled SQL statements.
72550 */
72551
72552 #ifndef SQLITE_OMIT_FOREIGN_KEY
72553 #ifndef SQLITE_OMIT_TRIGGER
72554
72555 /*
72556 ** Deferred and Immediate FKs
72557 ** --------------------------
72558 **
72559 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
72560 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
72561 ** is returned and the current statement transaction rolled back. If a 
72562 ** deferred foreign key constraint is violated, no action is taken 
72563 ** immediately. However if the application attempts to commit the 
72564 ** transaction before fixing the constraint violation, the attempt fails.
72565 **
72566 ** Deferred constraints are implemented using a simple counter associated
72567 ** with the database handle. The counter is set to zero each time a 
72568 ** database transaction is opened. Each time a statement is executed 
72569 ** that causes a foreign key violation, the counter is incremented. Each
72570 ** time a statement is executed that removes an existing violation from
72571 ** the database, the counter is decremented. When the transaction is
72572 ** committed, the commit fails if the current value of the counter is
72573 ** greater than zero. This scheme has two big drawbacks:
72574 **
72575 **   * When a commit fails due to a deferred foreign key constraint, 
72576 **     there is no way to tell which foreign constraint is not satisfied,
72577 **     or which row it is not satisfied for.
72578 **
72579 **   * If the database contains foreign key violations when the 
72580 **     transaction is opened, this may cause the mechanism to malfunction.
72581 **
72582 ** Despite these problems, this approach is adopted as it seems simpler
72583 ** than the alternatives.
72584 **
72585 ** INSERT operations:
72586 **
72587 **   I.1) For each FK for which the table is the child table, search
72588 **        the parent table for a match. If none is found increment the
72589 **        constraint counter.
72590 **
72591 **   I.2) For each FK for which the table is the parent table, 
72592 **        search the child table for rows that correspond to the new
72593 **        row in the parent table. Decrement the counter for each row
72594 **        found (as the constraint is now satisfied).
72595 **
72596 ** DELETE operations:
72597 **
72598 **   D.1) For each FK for which the table is the child table, 
72599 **        search the parent table for a row that corresponds to the 
72600 **        deleted row in the child table. If such a row is not found, 
72601 **        decrement the counter.
72602 **
72603 **   D.2) For each FK for which the table is the parent table, search 
72604 **        the child table for rows that correspond to the deleted row 
72605 **        in the parent table. For each found increment the counter.
72606 **
72607 ** UPDATE operations:
72608 **
72609 **   An UPDATE command requires that all 4 steps above are taken, but only
72610 **   for FK constraints for which the affected columns are actually 
72611 **   modified (values must be compared at runtime).
72612 **
72613 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
72614 ** This simplifies the implementation a bit.
72615 **
72616 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
72617 ** resolution is considered to delete rows before the new row is inserted.
72618 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
72619 ** is thrown, even if the FK constraint would be satisfied after the new 
72620 ** row is inserted.
72621 **
72622 ** Immediate constraints are usually handled similarly. The only difference 
72623 ** is that the counter used is stored as part of each individual statement
72624 ** object (struct Vdbe). If, after the statement has run, its immediate
72625 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
72626 ** and the statement transaction is rolled back. An exception is an INSERT
72627 ** statement that inserts a single row only (no triggers). In this case,
72628 ** instead of using a counter, an exception is thrown immediately if the
72629 ** INSERT violates a foreign key constraint. This is necessary as such
72630 ** an INSERT does not open a statement transaction.
72631 **
72632 ** TODO: How should dropping a table be handled? How should renaming a 
72633 ** table be handled?
72634 **
72635 **
72636 ** Query API Notes
72637 ** ---------------
72638 **
72639 ** Before coding an UPDATE or DELETE row operation, the code-generator
72640 ** for those two operations needs to know whether or not the operation
72641 ** requires any FK processing and, if so, which columns of the original
72642 ** row are required by the FK processing VDBE code (i.e. if FKs were
72643 ** implemented using triggers, which of the old.* columns would be 
72644 ** accessed). No information is required by the code-generator before
72645 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
72646 ** generation code to query for this information are:
72647 **
72648 **   sqlite3FkRequired() - Test to see if FK processing is required.
72649 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
72650 **
72651 **
72652 ** Externally accessible module functions
72653 ** --------------------------------------
72654 **
72655 **   sqlite3FkCheck()    - Check for foreign key violations.
72656 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
72657 **   sqlite3FkDelete()   - Delete an FKey structure.
72658 */
72659
72660 /*
72661 ** VDBE Calling Convention
72662 ** -----------------------
72663 **
72664 ** Example:
72665 **
72666 **   For the following INSERT statement:
72667 **
72668 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
72669 **     INSERT INTO t1 VALUES(1, 2, 3.1);
72670 **
72671 **   Register (x):        2    (type integer)
72672 **   Register (x+1):      1    (type integer)
72673 **   Register (x+2):      NULL (type NULL)
72674 **   Register (x+3):      3.1  (type real)
72675 */
72676
72677 /*
72678 ** A foreign key constraint requires that the key columns in the parent
72679 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
72680 ** Given that pParent is the parent table for foreign key constraint pFKey, 
72681 ** search the schema a unique index on the parent key columns. 
72682 **
72683 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
72684 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
72685 ** is set to point to the unique index. 
72686 ** 
72687 ** If the parent key consists of a single column (the foreign key constraint
72688 ** is not a composite foreign key), output variable *paiCol is set to NULL.
72689 ** Otherwise, it is set to point to an allocated array of size N, where
72690 ** N is the number of columns in the parent key. The first element of the
72691 ** array is the index of the child table column that is mapped by the FK
72692 ** constraint to the parent table column stored in the left-most column
72693 ** of index *ppIdx. The second element of the array is the index of the
72694 ** child table column that corresponds to the second left-most column of
72695 ** *ppIdx, and so on.
72696 **
72697 ** If the required index cannot be found, either because:
72698 **
72699 **   1) The named parent key columns do not exist, or
72700 **
72701 **   2) The named parent key columns do exist, but are not subject to a
72702 **      UNIQUE or PRIMARY KEY constraint, or
72703 **
72704 **   3) No parent key columns were provided explicitly as part of the
72705 **      foreign key definition, and the parent table does not have a
72706 **      PRIMARY KEY, or
72707 **
72708 **   4) No parent key columns were provided explicitly as part of the
72709 **      foreign key definition, and the PRIMARY KEY of the parent table 
72710 **      consists of a a different number of columns to the child key in 
72711 **      the child table.
72712 **
72713 ** then non-zero is returned, and a "foreign key mismatch" error loaded
72714 ** into pParse. If an OOM error occurs, non-zero is returned and the
72715 ** pParse->db->mallocFailed flag is set.
72716 */
72717 static int locateFkeyIndex(
72718   Parse *pParse,                  /* Parse context to store any error in */
72719   Table *pParent,                 /* Parent table of FK constraint pFKey */
72720   FKey *pFKey,                    /* Foreign key to find index for */
72721   Index **ppIdx,                  /* OUT: Unique index on parent table */
72722   int **paiCol                    /* OUT: Map of index columns in pFKey */
72723 ){
72724   Index *pIdx = 0;                    /* Value to return via *ppIdx */
72725   int *aiCol = 0;                     /* Value to return via *paiCol */
72726   int nCol = pFKey->nCol;             /* Number of columns in parent key */
72727   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
72728
72729   /* The caller is responsible for zeroing output parameters. */
72730   assert( ppIdx && *ppIdx==0 );
72731   assert( !paiCol || *paiCol==0 );
72732   assert( pParse );
72733
72734   /* If this is a non-composite (single column) foreign key, check if it 
72735   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
72736   ** and *paiCol set to zero and return early. 
72737   **
72738   ** Otherwise, for a composite foreign key (more than one column), allocate
72739   ** space for the aiCol array (returned via output parameter *paiCol).
72740   ** Non-composite foreign keys do not require the aiCol array.
72741   */
72742   if( nCol==1 ){
72743     /* The FK maps to the IPK if any of the following are true:
72744     **
72745     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
72746     **      mapped to the primary key of table pParent, or
72747     **   2) The FK is explicitly mapped to a column declared as INTEGER
72748     **      PRIMARY KEY.
72749     */
72750     if( pParent->iPKey>=0 ){
72751       if( !zKey ) return 0;
72752       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
72753     }
72754   }else if( paiCol ){
72755     assert( nCol>1 );
72756     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
72757     if( !aiCol ) return 1;
72758     *paiCol = aiCol;
72759   }
72760
72761   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
72762     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
72763       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
72764       ** of columns. If each indexed column corresponds to a foreign key
72765       ** column of pFKey, then this index is a winner.  */
72766
72767       if( zKey==0 ){
72768         /* If zKey is NULL, then this foreign key is implicitly mapped to 
72769         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
72770         ** identified by the test (Index.autoIndex==2).  */
72771         if( pIdx->autoIndex==2 ){
72772           if( aiCol ){
72773             int i;
72774             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
72775           }
72776           break;
72777         }
72778       }else{
72779         /* If zKey is non-NULL, then this foreign key was declared to
72780         ** map to an explicit list of columns in table pParent. Check if this
72781         ** index matches those columns. Also, check that the index uses
72782         ** the default collation sequences for each column. */
72783         int i, j;
72784         for(i=0; i<nCol; i++){
72785           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
72786           char *zDfltColl;                  /* Def. collation for column */
72787           char *zIdxCol;                    /* Name of indexed column */
72788
72789           /* If the index uses a collation sequence that is different from
72790           ** the default collation sequence for the column, this index is
72791           ** unusable. Bail out early in this case.  */
72792           zDfltColl = pParent->aCol[iCol].zColl;
72793           if( !zDfltColl ){
72794             zDfltColl = "BINARY";
72795           }
72796           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
72797
72798           zIdxCol = pParent->aCol[iCol].zName;
72799           for(j=0; j<nCol; j++){
72800             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
72801               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
72802               break;
72803             }
72804           }
72805           if( j==nCol ) break;
72806         }
72807         if( i==nCol ) break;      /* pIdx is usable */
72808       }
72809     }
72810   }
72811
72812   if( !pIdx ){
72813     if( !pParse->disableTriggers ){
72814       sqlite3ErrorMsg(pParse, "foreign key mismatch");
72815     }
72816     sqlite3DbFree(pParse->db, aiCol);
72817     return 1;
72818   }
72819
72820   *ppIdx = pIdx;
72821   return 0;
72822 }
72823
72824 /*
72825 ** This function is called when a row is inserted into or deleted from the 
72826 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
72827 ** on the child table of pFKey, this function is invoked twice for each row
72828 ** affected - once to "delete" the old row, and then again to "insert" the
72829 ** new row.
72830 **
72831 ** Each time it is called, this function generates VDBE code to locate the
72832 ** row in the parent table that corresponds to the row being inserted into 
72833 ** or deleted from the child table. If the parent row can be found, no 
72834 ** special action is taken. Otherwise, if the parent row can *not* be
72835 ** found in the parent table:
72836 **
72837 **   Operation | FK type   | Action taken
72838 **   --------------------------------------------------------------------------
72839 **   INSERT      immediate   Increment the "immediate constraint counter".
72840 **
72841 **   DELETE      immediate   Decrement the "immediate constraint counter".
72842 **
72843 **   INSERT      deferred    Increment the "deferred constraint counter".
72844 **
72845 **   DELETE      deferred    Decrement the "deferred constraint counter".
72846 **
72847 ** These operations are identified in the comment at the top of this file 
72848 ** (fkey.c) as "I.1" and "D.1".
72849 */
72850 static void fkLookupParent(
72851   Parse *pParse,        /* Parse context */
72852   int iDb,              /* Index of database housing pTab */
72853   Table *pTab,          /* Parent table of FK pFKey */
72854   Index *pIdx,          /* Unique index on parent key columns in pTab */
72855   FKey *pFKey,          /* Foreign key constraint */
72856   int *aiCol,           /* Map from parent key columns to child table columns */
72857   int regData,          /* Address of array containing child table row */
72858   int nIncr,            /* Increment constraint counter by this */
72859   int isIgnore          /* If true, pretend pTab contains all NULL values */
72860 ){
72861   int i;                                    /* Iterator variable */
72862   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
72863   int iCur = pParse->nTab - 1;              /* Cursor number to use */
72864   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
72865
72866   /* If nIncr is less than zero, then check at runtime if there are any
72867   ** outstanding constraints to resolve. If there are not, there is no need
72868   ** to check if deleting this row resolves any outstanding violations.
72869   **
72870   ** Check if any of the key columns in the child table row are NULL. If 
72871   ** any are, then the constraint is considered satisfied. No need to 
72872   ** search for a matching row in the parent table.  */
72873   if( nIncr<0 ){
72874     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
72875   }
72876   for(i=0; i<pFKey->nCol; i++){
72877     int iReg = aiCol[i] + regData + 1;
72878     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
72879   }
72880
72881   if( isIgnore==0 ){
72882     if( pIdx==0 ){
72883       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
72884       ** column of the parent table (table pTab).  */
72885       int iMustBeInt;               /* Address of MustBeInt instruction */
72886       int regTemp = sqlite3GetTempReg(pParse);
72887   
72888       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
72889       ** apply the affinity of the parent key). If this fails, then there
72890       ** is no matching parent key. Before using MustBeInt, make a copy of
72891       ** the value. Otherwise, the value inserted into the child key column
72892       ** will have INTEGER affinity applied to it, which may not be correct.  */
72893       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
72894       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
72895   
72896       /* If the parent table is the same as the child table, and we are about
72897       ** to increment the constraint-counter (i.e. this is an INSERT operation),
72898       ** then check if the row being inserted matches itself. If so, do not
72899       ** increment the constraint-counter.  */
72900       if( pTab==pFKey->pFrom && nIncr==1 ){
72901         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
72902       }
72903   
72904       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
72905       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
72906       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
72907       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
72908       sqlite3VdbeJumpHere(v, iMustBeInt);
72909       sqlite3ReleaseTempReg(pParse, regTemp);
72910     }else{
72911       int nCol = pFKey->nCol;
72912       int regTemp = sqlite3GetTempRange(pParse, nCol);
72913       int regRec = sqlite3GetTempReg(pParse);
72914       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
72915   
72916       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
72917       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
72918       for(i=0; i<nCol; i++){
72919         sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
72920       }
72921   
72922       /* If the parent table is the same as the child table, and we are about
72923       ** to increment the constraint-counter (i.e. this is an INSERT operation),
72924       ** then check if the row being inserted matches itself. If so, do not
72925       ** increment the constraint-counter.  */
72926       if( pTab==pFKey->pFrom && nIncr==1 ){
72927         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
72928         for(i=0; i<nCol; i++){
72929           int iChild = aiCol[i]+1+regData;
72930           int iParent = pIdx->aiColumn[i]+1+regData;
72931           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
72932         }
72933         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
72934       }
72935   
72936       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
72937       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
72938       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
72939   
72940       sqlite3ReleaseTempReg(pParse, regRec);
72941       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
72942     }
72943   }
72944
72945   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
72946     /* Special case: If this is an INSERT statement that will insert exactly
72947     ** one row into the table, raise a constraint immediately instead of
72948     ** incrementing a counter. This is necessary as the VM code is being
72949     ** generated for will not open a statement transaction.  */
72950     assert( nIncr==1 );
72951     sqlite3HaltConstraint(
72952         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
72953     );
72954   }else{
72955     if( nIncr>0 && pFKey->isDeferred==0 ){
72956       sqlite3ParseToplevel(pParse)->mayAbort = 1;
72957     }
72958     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
72959   }
72960
72961   sqlite3VdbeResolveLabel(v, iOk);
72962   sqlite3VdbeAddOp1(v, OP_Close, iCur);
72963 }
72964
72965 /*
72966 ** This function is called to generate code executed when a row is deleted
72967 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
72968 ** deferred, when a row is inserted into the same table. When generating
72969 ** code for an SQL UPDATE operation, this function may be called twice -
72970 ** once to "delete" the old row and once to "insert" the new row.
72971 **
72972 ** The code generated by this function scans through the rows in the child
72973 ** table that correspond to the parent table row being deleted or inserted.
72974 ** For each child row found, one of the following actions is taken:
72975 **
72976 **   Operation | FK type   | Action taken
72977 **   --------------------------------------------------------------------------
72978 **   DELETE      immediate   Increment the "immediate constraint counter".
72979 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
72980 **                           throw a "foreign key constraint failed" exception.
72981 **
72982 **   INSERT      immediate   Decrement the "immediate constraint counter".
72983 **
72984 **   DELETE      deferred    Increment the "deferred constraint counter".
72985 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
72986 **                           throw a "foreign key constraint failed" exception.
72987 **
72988 **   INSERT      deferred    Decrement the "deferred constraint counter".
72989 **
72990 ** These operations are identified in the comment at the top of this file 
72991 ** (fkey.c) as "I.2" and "D.2".
72992 */
72993 static void fkScanChildren(
72994   Parse *pParse,                  /* Parse context */
72995   SrcList *pSrc,                  /* SrcList containing the table to scan */
72996   Table *pTab,
72997   Index *pIdx,                    /* Foreign key index */
72998   FKey *pFKey,                    /* Foreign key relationship */
72999   int *aiCol,                     /* Map from pIdx cols to child table cols */
73000   int regData,                    /* Referenced table data starts here */
73001   int nIncr                       /* Amount to increment deferred counter by */
73002 ){
73003   sqlite3 *db = pParse->db;       /* Database handle */
73004   int i;                          /* Iterator variable */
73005   Expr *pWhere = 0;               /* WHERE clause to scan with */
73006   NameContext sNameContext;       /* Context used to resolve WHERE clause */
73007   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
73008   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
73009   Vdbe *v = sqlite3GetVdbe(pParse);
73010
73011   assert( !pIdx || pIdx->pTable==pTab );
73012
73013   if( nIncr<0 ){
73014     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
73015   }
73016
73017   /* Create an Expr object representing an SQL expression like:
73018   **
73019   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
73020   **
73021   ** The collation sequence used for the comparison should be that of
73022   ** the parent key columns. The affinity of the parent key column should
73023   ** be applied to each child key value before the comparison takes place.
73024   */
73025   for(i=0; i<pFKey->nCol; i++){
73026     Expr *pLeft;                  /* Value from parent table row */
73027     Expr *pRight;                 /* Column ref to child table */
73028     Expr *pEq;                    /* Expression (pLeft = pRight) */
73029     int iCol;                     /* Index of column in child table */ 
73030     const char *zCol;             /* Name of column in child table */
73031
73032     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
73033     if( pLeft ){
73034       /* Set the collation sequence and affinity of the LHS of each TK_EQ
73035       ** expression to the parent key column defaults.  */
73036       if( pIdx ){
73037         Column *pCol;
73038         iCol = pIdx->aiColumn[i];
73039         pCol = &pIdx->pTable->aCol[iCol];
73040         pLeft->iTable = regData+iCol+1;
73041         pLeft->affinity = pCol->affinity;
73042         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
73043       }else{
73044         pLeft->iTable = regData;
73045         pLeft->affinity = SQLITE_AFF_INTEGER;
73046       }
73047     }
73048     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
73049     assert( iCol>=0 );
73050     zCol = pFKey->pFrom->aCol[iCol].zName;
73051     pRight = sqlite3Expr(db, TK_ID, zCol);
73052     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
73053     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
73054   }
73055
73056   /* If the child table is the same as the parent table, and this scan
73057   ** is taking place as part of a DELETE operation (operation D.2), omit the
73058   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
73059   ** clause, where $rowid is the rowid of the row being deleted.  */
73060   if( pTab==pFKey->pFrom && nIncr>0 ){
73061     Expr *pEq;                    /* Expression (pLeft = pRight) */
73062     Expr *pLeft;                  /* Value from parent table row */
73063     Expr *pRight;                 /* Column ref to child table */
73064     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
73065     pRight = sqlite3Expr(db, TK_COLUMN, 0);
73066     if( pLeft && pRight ){
73067       pLeft->iTable = regData;
73068       pLeft->affinity = SQLITE_AFF_INTEGER;
73069       pRight->iTable = pSrc->a[0].iCursor;
73070       pRight->iColumn = -1;
73071     }
73072     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
73073     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
73074   }
73075
73076   /* Resolve the references in the WHERE clause. */
73077   memset(&sNameContext, 0, sizeof(NameContext));
73078   sNameContext.pSrcList = pSrc;
73079   sNameContext.pParse = pParse;
73080   sqlite3ResolveExprNames(&sNameContext, pWhere);
73081
73082   /* Create VDBE to loop through the entries in pSrc that match the WHERE
73083   ** clause. If the constraint is not deferred, throw an exception for
73084   ** each row found. Otherwise, for deferred constraints, increment the
73085   ** deferred constraint counter by nIncr for each row selected.  */
73086   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
73087   if( nIncr>0 && pFKey->isDeferred==0 ){
73088     sqlite3ParseToplevel(pParse)->mayAbort = 1;
73089   }
73090   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
73091   if( pWInfo ){
73092     sqlite3WhereEnd(pWInfo);
73093   }
73094
73095   /* Clean up the WHERE clause constructed above. */
73096   sqlite3ExprDelete(db, pWhere);
73097   if( iFkIfZero ){
73098     sqlite3VdbeJumpHere(v, iFkIfZero);
73099   }
73100 }
73101
73102 /*
73103 ** This function returns a pointer to the head of a linked list of FK
73104 ** constraints for which table pTab is the parent table. For example,
73105 ** given the following schema:
73106 **
73107 **   CREATE TABLE t1(a PRIMARY KEY);
73108 **   CREATE TABLE t2(b REFERENCES t1(a);
73109 **
73110 ** Calling this function with table "t1" as an argument returns a pointer
73111 ** to the FKey structure representing the foreign key constraint on table
73112 ** "t2". Calling this function with "t2" as the argument would return a
73113 ** NULL pointer (as there are no FK constraints for which t2 is the parent
73114 ** table).
73115 */
73116 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
73117   int nName = sqlite3Strlen30(pTab->zName);
73118   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
73119 }
73120
73121 /*
73122 ** The second argument is a Trigger structure allocated by the 
73123 ** fkActionTrigger() routine. This function deletes the Trigger structure
73124 ** and all of its sub-components.
73125 **
73126 ** The Trigger structure or any of its sub-components may be allocated from
73127 ** the lookaside buffer belonging to database handle dbMem.
73128 */
73129 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
73130   if( p ){
73131     TriggerStep *pStep = p->step_list;
73132     sqlite3ExprDelete(dbMem, pStep->pWhere);
73133     sqlite3ExprListDelete(dbMem, pStep->pExprList);
73134     sqlite3SelectDelete(dbMem, pStep->pSelect);
73135     sqlite3ExprDelete(dbMem, p->pWhen);
73136     sqlite3DbFree(dbMem, p);
73137   }
73138 }
73139
73140 /*
73141 ** This function is called to generate code that runs when table pTab is
73142 ** being dropped from the database. The SrcList passed as the second argument
73143 ** to this function contains a single entry guaranteed to resolve to
73144 ** table pTab.
73145 **
73146 ** Normally, no code is required. However, if either
73147 **
73148 **   (a) The table is the parent table of a FK constraint, or
73149 **   (b) The table is the child table of a deferred FK constraint and it is
73150 **       determined at runtime that there are outstanding deferred FK 
73151 **       constraint violations in the database,
73152 **
73153 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
73154 ** the table from the database. Triggers are disabled while running this
73155 ** DELETE, but foreign key actions are not.
73156 */
73157 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
73158   sqlite3 *db = pParse->db;
73159   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
73160     int iSkip = 0;
73161     Vdbe *v = sqlite3GetVdbe(pParse);
73162
73163     assert( v );                  /* VDBE has already been allocated */
73164     if( sqlite3FkReferences(pTab)==0 ){
73165       /* Search for a deferred foreign key constraint for which this table
73166       ** is the child table. If one cannot be found, return without 
73167       ** generating any VDBE code. If one can be found, then jump over
73168       ** the entire DELETE if there are no outstanding deferred constraints
73169       ** when this statement is run.  */
73170       FKey *p;
73171       for(p=pTab->pFKey; p; p=p->pNextFrom){
73172         if( p->isDeferred ) break;
73173       }
73174       if( !p ) return;
73175       iSkip = sqlite3VdbeMakeLabel(v);
73176       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
73177     }
73178
73179     pParse->disableTriggers = 1;
73180     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
73181     pParse->disableTriggers = 0;
73182
73183     /* If the DELETE has generated immediate foreign key constraint 
73184     ** violations, halt the VDBE and return an error at this point, before
73185     ** any modifications to the schema are made. This is because statement
73186     ** transactions are not able to rollback schema changes.  */
73187     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
73188     sqlite3HaltConstraint(
73189         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
73190     );
73191
73192     if( iSkip ){
73193       sqlite3VdbeResolveLabel(v, iSkip);
73194     }
73195   }
73196 }
73197
73198 /*
73199 ** This function is called when inserting, deleting or updating a row of
73200 ** table pTab to generate VDBE code to perform foreign key constraint 
73201 ** processing for the operation.
73202 **
73203 ** For a DELETE operation, parameter regOld is passed the index of the
73204 ** first register in an array of (pTab->nCol+1) registers containing the
73205 ** rowid of the row being deleted, followed by each of the column values
73206 ** of the row being deleted, from left to right. Parameter regNew is passed
73207 ** zero in this case.
73208 **
73209 ** For an INSERT operation, regOld is passed zero and regNew is passed the
73210 ** first register of an array of (pTab->nCol+1) registers containing the new
73211 ** row data.
73212 **
73213 ** For an UPDATE operation, this function is called twice. Once before
73214 ** the original record is deleted from the table using the calling convention
73215 ** described for DELETE. Then again after the original record is deleted
73216 ** but before the new record is inserted using the INSERT convention. 
73217 */
73218 SQLITE_PRIVATE void sqlite3FkCheck(
73219   Parse *pParse,                  /* Parse context */
73220   Table *pTab,                    /* Row is being deleted from this table */ 
73221   int regOld,                     /* Previous row data is stored here */
73222   int regNew                      /* New row data is stored here */
73223 ){
73224   sqlite3 *db = pParse->db;       /* Database handle */
73225   Vdbe *v;                        /* VM to write code to */
73226   FKey *pFKey;                    /* Used to iterate through FKs */
73227   int iDb;                        /* Index of database containing pTab */
73228   const char *zDb;                /* Name of database containing pTab */
73229   int isIgnoreErrors = pParse->disableTriggers;
73230
73231   /* Exactly one of regOld and regNew should be non-zero. */
73232   assert( (regOld==0)!=(regNew==0) );
73233
73234   /* If foreign-keys are disabled, this function is a no-op. */
73235   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
73236
73237   v = sqlite3GetVdbe(pParse);
73238   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
73239   zDb = db->aDb[iDb].zName;
73240
73241   /* Loop through all the foreign key constraints for which pTab is the
73242   ** child table (the table that the foreign key definition is part of).  */
73243   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
73244     Table *pTo;                   /* Parent table of foreign key pFKey */
73245     Index *pIdx = 0;              /* Index on key columns in pTo */
73246     int *aiFree = 0;
73247     int *aiCol;
73248     int iCol;
73249     int i;
73250     int isIgnore = 0;
73251
73252     /* Find the parent table of this foreign key. Also find a unique index 
73253     ** on the parent key columns in the parent table. If either of these 
73254     ** schema items cannot be located, set an error in pParse and return 
73255     ** early.  */
73256     if( pParse->disableTriggers ){
73257       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
73258     }else{
73259       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
73260     }
73261     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
73262       if( !isIgnoreErrors || db->mallocFailed ) return;
73263       continue;
73264     }
73265     assert( pFKey->nCol==1 || (aiFree && pIdx) );
73266
73267     if( aiFree ){
73268       aiCol = aiFree;
73269     }else{
73270       iCol = pFKey->aCol[0].iFrom;
73271       aiCol = &iCol;
73272     }
73273     for(i=0; i<pFKey->nCol; i++){
73274       if( aiCol[i]==pTab->iPKey ){
73275         aiCol[i] = -1;
73276       }
73277 #ifndef SQLITE_OMIT_AUTHORIZATION
73278       /* Request permission to read the parent key columns. If the 
73279       ** authorization callback returns SQLITE_IGNORE, behave as if any
73280       ** values read from the parent table are NULL. */
73281       if( db->xAuth ){
73282         int rcauth;
73283         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
73284         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
73285         isIgnore = (rcauth==SQLITE_IGNORE);
73286       }
73287 #endif
73288     }
73289
73290     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
73291     ** a cursor to use to search the unique index on the parent key columns 
73292     ** in the parent table.  */
73293     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
73294     pParse->nTab++;
73295
73296     if( regOld!=0 ){
73297       /* A row is being removed from the child table. Search for the parent.
73298       ** If the parent does not exist, removing the child row resolves an 
73299       ** outstanding foreign key constraint violation. */
73300       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
73301     }
73302     if( regNew!=0 ){
73303       /* A row is being added to the child table. If a parent row cannot
73304       ** be found, adding the child row has violated the FK constraint. */ 
73305       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
73306     }
73307
73308     sqlite3DbFree(db, aiFree);
73309   }
73310
73311   /* Loop through all the foreign key constraints that refer to this table */
73312   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
73313     Index *pIdx = 0;              /* Foreign key index for pFKey */
73314     SrcList *pSrc;
73315     int *aiCol = 0;
73316
73317     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
73318       assert( regOld==0 && regNew!=0 );
73319       /* Inserting a single row into a parent table cannot cause an immediate
73320       ** foreign key violation. So do nothing in this case.  */
73321       continue;
73322     }
73323
73324     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
73325       if( !isIgnoreErrors || db->mallocFailed ) return;
73326       continue;
73327     }
73328     assert( aiCol || pFKey->nCol==1 );
73329
73330     /* Create a SrcList structure containing a single table (the table 
73331     ** the foreign key that refers to this table is attached to). This
73332     ** is required for the sqlite3WhereXXX() interface.  */
73333     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
73334     if( pSrc ){
73335       struct SrcList_item *pItem = pSrc->a;
73336       pItem->pTab = pFKey->pFrom;
73337       pItem->zName = pFKey->pFrom->zName;
73338       pItem->pTab->nRef++;
73339       pItem->iCursor = pParse->nTab++;
73340   
73341       if( regNew!=0 ){
73342         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
73343       }
73344       if( regOld!=0 ){
73345         /* If there is a RESTRICT action configured for the current operation
73346         ** on the parent table of this FK, then throw an exception 
73347         ** immediately if the FK constraint is violated, even if this is a
73348         ** deferred trigger. That's what RESTRICT means. To defer checking
73349         ** the constraint, the FK should specify NO ACTION (represented
73350         ** using OE_None). NO ACTION is the default.  */
73351         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
73352       }
73353       pItem->zName = 0;
73354       sqlite3SrcListDelete(db, pSrc);
73355     }
73356     sqlite3DbFree(db, aiCol);
73357   }
73358 }
73359
73360 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
73361
73362 /*
73363 ** This function is called before generating code to update or delete a 
73364 ** row contained in table pTab.
73365 */
73366 SQLITE_PRIVATE u32 sqlite3FkOldmask(
73367   Parse *pParse,                  /* Parse context */
73368   Table *pTab                     /* Table being modified */
73369 ){
73370   u32 mask = 0;
73371   if( pParse->db->flags&SQLITE_ForeignKeys ){
73372     FKey *p;
73373     int i;
73374     for(p=pTab->pFKey; p; p=p->pNextFrom){
73375       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
73376     }
73377     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
73378       Index *pIdx = 0;
73379       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
73380       if( pIdx ){
73381         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
73382       }
73383     }
73384   }
73385   return mask;
73386 }
73387
73388 /*
73389 ** This function is called before generating code to update or delete a 
73390 ** row contained in table pTab. If the operation is a DELETE, then
73391 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
73392 ** to an array of size N, where N is the number of columns in table pTab.
73393 ** If the i'th column is not modified by the UPDATE, then the corresponding 
73394 ** entry in the aChange[] array is set to -1. If the column is modified,
73395 ** the value is 0 or greater. Parameter chngRowid is set to true if the
73396 ** UPDATE statement modifies the rowid fields of the table.
73397 **
73398 ** If any foreign key processing will be required, this function returns
73399 ** true. If there is no foreign key related processing, this function 
73400 ** returns false.
73401 */
73402 SQLITE_PRIVATE int sqlite3FkRequired(
73403   Parse *pParse,                  /* Parse context */
73404   Table *pTab,                    /* Table being modified */
73405   int *aChange,                   /* Non-NULL for UPDATE operations */
73406   int chngRowid                   /* True for UPDATE that affects rowid */
73407 ){
73408   if( pParse->db->flags&SQLITE_ForeignKeys ){
73409     if( !aChange ){
73410       /* A DELETE operation. Foreign key processing is required if the 
73411       ** table in question is either the child or parent table for any 
73412       ** foreign key constraint.  */
73413       return (sqlite3FkReferences(pTab) || pTab->pFKey);
73414     }else{
73415       /* This is an UPDATE. Foreign key processing is only required if the
73416       ** operation modifies one or more child or parent key columns. */
73417       int i;
73418       FKey *p;
73419
73420       /* Check if any child key columns are being modified. */
73421       for(p=pTab->pFKey; p; p=p->pNextFrom){
73422         for(i=0; i<p->nCol; i++){
73423           int iChildKey = p->aCol[i].iFrom;
73424           if( aChange[iChildKey]>=0 ) return 1;
73425           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
73426         }
73427       }
73428
73429       /* Check if any parent key columns are being modified. */
73430       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
73431         for(i=0; i<p->nCol; i++){
73432           char *zKey = p->aCol[i].zCol;
73433           int iKey;
73434           for(iKey=0; iKey<pTab->nCol; iKey++){
73435             Column *pCol = &pTab->aCol[iKey];
73436             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
73437               if( aChange[iKey]>=0 ) return 1;
73438               if( iKey==pTab->iPKey && chngRowid ) return 1;
73439             }
73440           }
73441         }
73442       }
73443     }
73444   }
73445   return 0;
73446 }
73447
73448 /*
73449 ** This function is called when an UPDATE or DELETE operation is being 
73450 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
73451 ** If the current operation is an UPDATE, then the pChanges parameter is
73452 ** passed a pointer to the list of columns being modified. If it is a
73453 ** DELETE, pChanges is passed a NULL pointer.
73454 **
73455 ** It returns a pointer to a Trigger structure containing a trigger
73456 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
73457 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
73458 ** returned (these actions require no special handling by the triggers
73459 ** sub-system, code for them is created by fkScanChildren()).
73460 **
73461 ** For example, if pFKey is the foreign key and pTab is table "p" in 
73462 ** the following schema:
73463 **
73464 **   CREATE TABLE p(pk PRIMARY KEY);
73465 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
73466 **
73467 ** then the returned trigger structure is equivalent to:
73468 **
73469 **   CREATE TRIGGER ... DELETE ON p BEGIN
73470 **     DELETE FROM c WHERE ck = old.pk;
73471 **   END;
73472 **
73473 ** The returned pointer is cached as part of the foreign key object. It
73474 ** is eventually freed along with the rest of the foreign key object by 
73475 ** sqlite3FkDelete().
73476 */
73477 static Trigger *fkActionTrigger(
73478   Parse *pParse,                  /* Parse context */
73479   Table *pTab,                    /* Table being updated or deleted from */
73480   FKey *pFKey,                    /* Foreign key to get action for */
73481   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
73482 ){
73483   sqlite3 *db = pParse->db;       /* Database handle */
73484   int action;                     /* One of OE_None, OE_Cascade etc. */
73485   Trigger *pTrigger;              /* Trigger definition to return */
73486   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
73487
73488   action = pFKey->aAction[iAction];
73489   pTrigger = pFKey->apTrigger[iAction];
73490
73491   if( action!=OE_None && !pTrigger ){
73492     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
73493     char const *zFrom;            /* Name of child table */
73494     int nFrom;                    /* Length in bytes of zFrom */
73495     Index *pIdx = 0;              /* Parent key index for this FK */
73496     int *aiCol = 0;               /* child table cols -> parent key cols */
73497     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
73498     Expr *pWhere = 0;             /* WHERE clause of trigger step */
73499     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
73500     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
73501     int i;                        /* Iterator variable */
73502     Expr *pWhen = 0;              /* WHEN clause for the trigger */
73503
73504     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
73505     assert( aiCol || pFKey->nCol==1 );
73506
73507     for(i=0; i<pFKey->nCol; i++){
73508       Token tOld = { "old", 3 };  /* Literal "old" token */
73509       Token tNew = { "new", 3 };  /* Literal "new" token */
73510       Token tFromCol;             /* Name of column in child table */
73511       Token tToCol;               /* Name of column in parent table */
73512       int iFromCol;               /* Idx of column in child table */
73513       Expr *pEq;                  /* tFromCol = OLD.tToCol */
73514
73515       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
73516       assert( iFromCol>=0 );
73517       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
73518       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
73519
73520       tToCol.n = sqlite3Strlen30(tToCol.z);
73521       tFromCol.n = sqlite3Strlen30(tFromCol.z);
73522
73523       /* Create the expression "OLD.zToCol = zFromCol". It is important
73524       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
73525       ** that the affinity and collation sequence associated with the
73526       ** parent table are used for the comparison. */
73527       pEq = sqlite3PExpr(pParse, TK_EQ,
73528           sqlite3PExpr(pParse, TK_DOT, 
73529             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
73530             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
73531           , 0),
73532           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
73533       , 0);
73534       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
73535
73536       /* For ON UPDATE, construct the next term of the WHEN clause.
73537       ** The final WHEN clause will be like this:
73538       **
73539       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
73540       */
73541       if( pChanges ){
73542         pEq = sqlite3PExpr(pParse, TK_IS,
73543             sqlite3PExpr(pParse, TK_DOT, 
73544               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
73545               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
73546               0),
73547             sqlite3PExpr(pParse, TK_DOT, 
73548               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
73549               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
73550               0),
73551             0);
73552         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
73553       }
73554   
73555       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
73556         Expr *pNew;
73557         if( action==OE_Cascade ){
73558           pNew = sqlite3PExpr(pParse, TK_DOT, 
73559             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
73560             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
73561           , 0);
73562         }else if( action==OE_SetDflt ){
73563           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
73564           if( pDflt ){
73565             pNew = sqlite3ExprDup(db, pDflt, 0);
73566           }else{
73567             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
73568           }
73569         }else{
73570           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
73571         }
73572         pList = sqlite3ExprListAppend(pParse, pList, pNew);
73573         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
73574       }
73575     }
73576     sqlite3DbFree(db, aiCol);
73577
73578     zFrom = pFKey->pFrom->zName;
73579     nFrom = sqlite3Strlen30(zFrom);
73580
73581     if( action==OE_Restrict ){
73582       Token tFrom;
73583       Expr *pRaise; 
73584
73585       tFrom.z = zFrom;
73586       tFrom.n = nFrom;
73587       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
73588       if( pRaise ){
73589         pRaise->affinity = OE_Abort;
73590       }
73591       pSelect = sqlite3SelectNew(pParse, 
73592           sqlite3ExprListAppend(pParse, 0, pRaise),
73593           sqlite3SrcListAppend(db, 0, &tFrom, 0),
73594           pWhere,
73595           0, 0, 0, 0, 0, 0
73596       );
73597       pWhere = 0;
73598     }
73599
73600     /* In the current implementation, pTab->dbMem==0 for all tables except
73601     ** for temporary tables used to describe subqueries.  And temporary
73602     ** tables do not have foreign key constraints.  Hence, pTab->dbMem
73603     ** should always be 0 there.
73604     */
73605     enableLookaside = db->lookaside.bEnabled;
73606     db->lookaside.bEnabled = 0;
73607
73608     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
73609         sizeof(Trigger) +         /* struct Trigger */
73610         sizeof(TriggerStep) +     /* Single step in trigger program */
73611         nFrom + 1                 /* Space for pStep->target.z */
73612     );
73613     if( pTrigger ){
73614       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
73615       pStep->target.z = (char *)&pStep[1];
73616       pStep->target.n = nFrom;
73617       memcpy((char *)pStep->target.z, zFrom, nFrom);
73618   
73619       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
73620       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
73621       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
73622       if( pWhen ){
73623         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
73624         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
73625       }
73626     }
73627
73628     /* Re-enable the lookaside buffer, if it was disabled earlier. */
73629     db->lookaside.bEnabled = enableLookaside;
73630
73631     sqlite3ExprDelete(db, pWhere);
73632     sqlite3ExprDelete(db, pWhen);
73633     sqlite3ExprListDelete(db, pList);
73634     sqlite3SelectDelete(db, pSelect);
73635     if( db->mallocFailed==1 ){
73636       fkTriggerDelete(db, pTrigger);
73637       return 0;
73638     }
73639
73640     switch( action ){
73641       case OE_Restrict:
73642         pStep->op = TK_SELECT; 
73643         break;
73644       case OE_Cascade: 
73645         if( !pChanges ){ 
73646           pStep->op = TK_DELETE; 
73647           break; 
73648         }
73649       default:
73650         pStep->op = TK_UPDATE;
73651     }
73652     pStep->pTrig = pTrigger;
73653     pTrigger->pSchema = pTab->pSchema;
73654     pTrigger->pTabSchema = pTab->pSchema;
73655     pFKey->apTrigger[iAction] = pTrigger;
73656     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
73657   }
73658
73659   return pTrigger;
73660 }
73661
73662 /*
73663 ** This function is called when deleting or updating a row to implement
73664 ** any required CASCADE, SET NULL or SET DEFAULT actions.
73665 */
73666 SQLITE_PRIVATE void sqlite3FkActions(
73667   Parse *pParse,                  /* Parse context */
73668   Table *pTab,                    /* Table being updated or deleted from */
73669   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
73670   int regOld                      /* Address of array containing old row */
73671 ){
73672   /* If foreign-key support is enabled, iterate through all FKs that 
73673   ** refer to table pTab. If there is an action associated with the FK 
73674   ** for this operation (either update or delete), invoke the associated 
73675   ** trigger sub-program.  */
73676   if( pParse->db->flags&SQLITE_ForeignKeys ){
73677     FKey *pFKey;                  /* Iterator variable */
73678     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
73679       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
73680       if( pAction ){
73681         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
73682       }
73683     }
73684   }
73685 }
73686
73687 #endif /* ifndef SQLITE_OMIT_TRIGGER */
73688
73689 /*
73690 ** Free all memory associated with foreign key definitions attached to
73691 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
73692 ** hash table.
73693 */
73694 SQLITE_PRIVATE void sqlite3FkDelete(Table *pTab){
73695   FKey *pFKey;                    /* Iterator variable */
73696   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
73697
73698   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
73699
73700     /* Remove the FK from the fkeyHash hash table. */
73701     if( pFKey->pPrevTo ){
73702       pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
73703     }else{
73704       void *data = (void *)pFKey->pNextTo;
73705       const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
73706       sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
73707     }
73708     if( pFKey->pNextTo ){
73709       pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
73710     }
73711
73712     /* Delete any triggers created to implement actions for this FK. */
73713 #ifndef SQLITE_OMIT_TRIGGER
73714     fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
73715     fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
73716 #endif
73717
73718     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
73719     ** classified as either immediate or deferred.
73720     */
73721     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
73722
73723     pNext = pFKey->pNextFrom;
73724     sqlite3DbFree(pTab->dbMem, pFKey);
73725   }
73726 }
73727 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
73728
73729 /************** End of fkey.c ************************************************/
73730 /************** Begin file insert.c ******************************************/
73731 /*
73732 ** 2001 September 15
73733 **
73734 ** The author disclaims copyright to this source code.  In place of
73735 ** a legal notice, here is a blessing:
73736 **
73737 **    May you do good and not evil.
73738 **    May you find forgiveness for yourself and forgive others.
73739 **    May you share freely, never taking more than you give.
73740 **
73741 *************************************************************************
73742 ** This file contains C code routines that are called by the parser
73743 ** to handle INSERT statements in SQLite.
73744 */
73745
73746 /*
73747 ** Generate code that will open a table for reading.
73748 */
73749 SQLITE_PRIVATE void sqlite3OpenTable(
73750   Parse *p,       /* Generate code into this VDBE */
73751   int iCur,       /* The cursor number of the table */
73752   int iDb,        /* The database index in sqlite3.aDb[] */
73753   Table *pTab,    /* The table to be opened */
73754   int opcode      /* OP_OpenRead or OP_OpenWrite */
73755 ){
73756   Vdbe *v;
73757   if( IsVirtual(pTab) ) return;
73758   v = sqlite3GetVdbe(p);
73759   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
73760   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
73761   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
73762   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
73763   VdbeComment((v, "%s", pTab->zName));
73764 }
73765
73766 /*
73767 ** Return a pointer to the column affinity string associated with index
73768 ** pIdx. A column affinity string has one character for each column in 
73769 ** the table, according to the affinity of the column:
73770 **
73771 **  Character      Column affinity
73772 **  ------------------------------
73773 **  'a'            TEXT
73774 **  'b'            NONE
73775 **  'c'            NUMERIC
73776 **  'd'            INTEGER
73777 **  'e'            REAL
73778 **
73779 ** An extra 'b' is appended to the end of the string to cover the
73780 ** rowid that appears as the last column in every index.
73781 **
73782 ** Memory for the buffer containing the column index affinity string
73783 ** is managed along with the rest of the Index structure. It will be
73784 ** released when sqlite3DeleteIndex() is called.
73785 */
73786 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
73787   if( !pIdx->zColAff ){
73788     /* The first time a column affinity string for a particular index is
73789     ** required, it is allocated and populated here. It is then stored as
73790     ** a member of the Index structure for subsequent use.
73791     **
73792     ** The column affinity string will eventually be deleted by
73793     ** sqliteDeleteIndex() when the Index structure itself is cleaned
73794     ** up.
73795     */
73796     int n;
73797     Table *pTab = pIdx->pTable;
73798     sqlite3 *db = sqlite3VdbeDb(v);
73799     pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
73800     if( !pIdx->zColAff ){
73801       db->mallocFailed = 1;
73802       return 0;
73803     }
73804     for(n=0; n<pIdx->nColumn; n++){
73805       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
73806     }
73807     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
73808     pIdx->zColAff[n] = 0;
73809   }
73810  
73811   return pIdx->zColAff;
73812 }
73813
73814 /*
73815 ** Set P4 of the most recently inserted opcode to a column affinity
73816 ** string for table pTab. A column affinity string has one character
73817 ** for each column indexed by the index, according to the affinity of the
73818 ** column:
73819 **
73820 **  Character      Column affinity
73821 **  ------------------------------
73822 **  'a'            TEXT
73823 **  'b'            NONE
73824 **  'c'            NUMERIC
73825 **  'd'            INTEGER
73826 **  'e'            REAL
73827 */
73828 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
73829   /* The first time a column affinity string for a particular table
73830   ** is required, it is allocated and populated here. It is then 
73831   ** stored as a member of the Table structure for subsequent use.
73832   **
73833   ** The column affinity string will eventually be deleted by
73834   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
73835   */
73836   if( !pTab->zColAff ){
73837     char *zColAff;
73838     int i;
73839     sqlite3 *db = sqlite3VdbeDb(v);
73840
73841     zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
73842     if( !zColAff ){
73843       db->mallocFailed = 1;
73844       return;
73845     }
73846
73847     for(i=0; i<pTab->nCol; i++){
73848       zColAff[i] = pTab->aCol[i].affinity;
73849     }
73850     zColAff[pTab->nCol] = '\0';
73851
73852     pTab->zColAff = zColAff;
73853   }
73854
73855   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
73856 }
73857
73858 /*
73859 ** Return non-zero if the table pTab in database iDb or any of its indices
73860 ** have been opened at any point in the VDBE program beginning at location
73861 ** iStartAddr throught the end of the program.  This is used to see if 
73862 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
73863 ** run without using temporary table for the results of the SELECT. 
73864 */
73865 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
73866   Vdbe *v = sqlite3GetVdbe(p);
73867   int i;
73868   int iEnd = sqlite3VdbeCurrentAddr(v);
73869 #ifndef SQLITE_OMIT_VIRTUALTABLE
73870   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
73871 #endif
73872
73873   for(i=iStartAddr; i<iEnd; i++){
73874     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
73875     assert( pOp!=0 );
73876     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
73877       Index *pIndex;
73878       int tnum = pOp->p2;
73879       if( tnum==pTab->tnum ){
73880         return 1;
73881       }
73882       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
73883         if( tnum==pIndex->tnum ){
73884           return 1;
73885         }
73886       }
73887     }
73888 #ifndef SQLITE_OMIT_VIRTUALTABLE
73889     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
73890       assert( pOp->p4.pVtab!=0 );
73891       assert( pOp->p4type==P4_VTAB );
73892       return 1;
73893     }
73894 #endif
73895   }
73896   return 0;
73897 }
73898
73899 #ifndef SQLITE_OMIT_AUTOINCREMENT
73900 /*
73901 ** Locate or create an AutoincInfo structure associated with table pTab
73902 ** which is in database iDb.  Return the register number for the register
73903 ** that holds the maximum rowid.
73904 **
73905 ** There is at most one AutoincInfo structure per table even if the
73906 ** same table is autoincremented multiple times due to inserts within
73907 ** triggers.  A new AutoincInfo structure is created if this is the
73908 ** first use of table pTab.  On 2nd and subsequent uses, the original
73909 ** AutoincInfo structure is used.
73910 **
73911 ** Three memory locations are allocated:
73912 **
73913 **   (1)  Register to hold the name of the pTab table.
73914 **   (2)  Register to hold the maximum ROWID of pTab.
73915 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
73916 **
73917 ** The 2nd register is the one that is returned.  That is all the
73918 ** insert routine needs to know about.
73919 */
73920 static int autoIncBegin(
73921   Parse *pParse,      /* Parsing context */
73922   int iDb,            /* Index of the database holding pTab */
73923   Table *pTab         /* The table we are writing to */
73924 ){
73925   int memId = 0;      /* Register holding maximum rowid */
73926   if( pTab->tabFlags & TF_Autoincrement ){
73927     Parse *pToplevel = sqlite3ParseToplevel(pParse);
73928     AutoincInfo *pInfo;
73929
73930     pInfo = pToplevel->pAinc;
73931     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
73932     if( pInfo==0 ){
73933       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
73934       if( pInfo==0 ) return 0;
73935       pInfo->pNext = pToplevel->pAinc;
73936       pToplevel->pAinc = pInfo;
73937       pInfo->pTab = pTab;
73938       pInfo->iDb = iDb;
73939       pToplevel->nMem++;                  /* Register to hold name of table */
73940       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
73941       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
73942     }
73943     memId = pInfo->regCtr;
73944   }
73945   return memId;
73946 }
73947
73948 /*
73949 ** This routine generates code that will initialize all of the
73950 ** register used by the autoincrement tracker.  
73951 */
73952 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
73953   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
73954   sqlite3 *db = pParse->db;  /* The database connection */
73955   Db *pDb;                   /* Database only autoinc table */
73956   int memId;                 /* Register holding max rowid */
73957   int addr;                  /* A VDBE address */
73958   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
73959
73960   /* This routine is never called during trigger-generation.  It is
73961   ** only called from the top-level */
73962   assert( pParse->pTriggerTab==0 );
73963   assert( pParse==sqlite3ParseToplevel(pParse) );
73964
73965   assert( v );   /* We failed long ago if this is not so */
73966   for(p = pParse->pAinc; p; p = p->pNext){
73967     pDb = &db->aDb[p->iDb];
73968     memId = p->regCtr;
73969     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
73970     addr = sqlite3VdbeCurrentAddr(v);
73971     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
73972     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
73973     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
73974     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
73975     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
73976     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
73977     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
73978     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
73979     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
73980     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
73981     sqlite3VdbeAddOp0(v, OP_Close);
73982   }
73983 }
73984
73985 /*
73986 ** Update the maximum rowid for an autoincrement calculation.
73987 **
73988 ** This routine should be called when the top of the stack holds a
73989 ** new rowid that is about to be inserted.  If that new rowid is
73990 ** larger than the maximum rowid in the memId memory cell, then the
73991 ** memory cell is updated.  The stack is unchanged.
73992 */
73993 static void autoIncStep(Parse *pParse, int memId, int regRowid){
73994   if( memId>0 ){
73995     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
73996   }
73997 }
73998
73999 /*
74000 ** This routine generates the code needed to write autoincrement
74001 ** maximum rowid values back into the sqlite_sequence register.
74002 ** Every statement that might do an INSERT into an autoincrement
74003 ** table (either directly or through triggers) needs to call this
74004 ** routine just before the "exit" code.
74005 */
74006 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
74007   AutoincInfo *p;
74008   Vdbe *v = pParse->pVdbe;
74009   sqlite3 *db = pParse->db;
74010
74011   assert( v );
74012   for(p = pParse->pAinc; p; p = p->pNext){
74013     Db *pDb = &db->aDb[p->iDb];
74014     int j1, j2, j3, j4, j5;
74015     int iRec;
74016     int memId = p->regCtr;
74017
74018     iRec = sqlite3GetTempReg(pParse);
74019     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
74020     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
74021     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
74022     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
74023     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
74024     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
74025     sqlite3VdbeJumpHere(v, j2);
74026     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
74027     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
74028     sqlite3VdbeJumpHere(v, j4);
74029     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
74030     sqlite3VdbeJumpHere(v, j1);
74031     sqlite3VdbeJumpHere(v, j5);
74032     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
74033     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
74034     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
74035     sqlite3VdbeAddOp0(v, OP_Close);
74036     sqlite3ReleaseTempReg(pParse, iRec);
74037   }
74038 }
74039 #else
74040 /*
74041 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
74042 ** above are all no-ops
74043 */
74044 # define autoIncBegin(A,B,C) (0)
74045 # define autoIncStep(A,B,C)
74046 #endif /* SQLITE_OMIT_AUTOINCREMENT */
74047
74048
74049 /* Forward declaration */
74050 static int xferOptimization(
74051   Parse *pParse,        /* Parser context */
74052   Table *pDest,         /* The table we are inserting into */
74053   Select *pSelect,      /* A SELECT statement to use as the data source */
74054   int onError,          /* How to handle constraint errors */
74055   int iDbDest           /* The database of pDest */
74056 );
74057
74058 /*
74059 ** This routine is call to handle SQL of the following forms:
74060 **
74061 **    insert into TABLE (IDLIST) values(EXPRLIST)
74062 **    insert into TABLE (IDLIST) select
74063 **
74064 ** The IDLIST following the table name is always optional.  If omitted,
74065 ** then a list of all columns for the table is substituted.  The IDLIST
74066 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
74067 **
74068 ** The pList parameter holds EXPRLIST in the first form of the INSERT
74069 ** statement above, and pSelect is NULL.  For the second form, pList is
74070 ** NULL and pSelect is a pointer to the select statement used to generate
74071 ** data for the insert.
74072 **
74073 ** The code generated follows one of four templates.  For a simple
74074 ** select with data coming from a VALUES clause, the code executes
74075 ** once straight down through.  Pseudo-code follows (we call this
74076 ** the "1st template"):
74077 **
74078 **         open write cursor to <table> and its indices
74079 **         puts VALUES clause expressions onto the stack
74080 **         write the resulting record into <table>
74081 **         cleanup
74082 **
74083 ** The three remaining templates assume the statement is of the form
74084 **
74085 **   INSERT INTO <table> SELECT ...
74086 **
74087 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
74088 ** in other words if the SELECT pulls all columns from a single table
74089 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
74090 ** if <table2> and <table1> are distinct tables but have identical
74091 ** schemas, including all the same indices, then a special optimization
74092 ** is invoked that copies raw records from <table2> over to <table1>.
74093 ** See the xferOptimization() function for the implementation of this
74094 ** template.  This is the 2nd template.
74095 **
74096 **         open a write cursor to <table>
74097 **         open read cursor on <table2>
74098 **         transfer all records in <table2> over to <table>
74099 **         close cursors
74100 **         foreach index on <table>
74101 **           open a write cursor on the <table> index
74102 **           open a read cursor on the corresponding <table2> index
74103 **           transfer all records from the read to the write cursors
74104 **           close cursors
74105 **         end foreach
74106 **
74107 ** The 3rd template is for when the second template does not apply
74108 ** and the SELECT clause does not read from <table> at any time.
74109 ** The generated code follows this template:
74110 **
74111 **         EOF <- 0
74112 **         X <- A
74113 **         goto B
74114 **      A: setup for the SELECT
74115 **         loop over the rows in the SELECT
74116 **           load values into registers R..R+n
74117 **           yield X
74118 **         end loop
74119 **         cleanup after the SELECT
74120 **         EOF <- 1
74121 **         yield X
74122 **         goto A
74123 **      B: open write cursor to <table> and its indices
74124 **      C: yield X
74125 **         if EOF goto D
74126 **         insert the select result into <table> from R..R+n
74127 **         goto C
74128 **      D: cleanup
74129 **
74130 ** The 4th template is used if the insert statement takes its
74131 ** values from a SELECT but the data is being inserted into a table
74132 ** that is also read as part of the SELECT.  In the third form,
74133 ** we have to use a intermediate table to store the results of
74134 ** the select.  The template is like this:
74135 **
74136 **         EOF <- 0
74137 **         X <- A
74138 **         goto B
74139 **      A: setup for the SELECT
74140 **         loop over the tables in the SELECT
74141 **           load value into register R..R+n
74142 **           yield X
74143 **         end loop
74144 **         cleanup after the SELECT
74145 **         EOF <- 1
74146 **         yield X
74147 **         halt-error
74148 **      B: open temp table
74149 **      L: yield X
74150 **         if EOF goto M
74151 **         insert row from R..R+n into temp table
74152 **         goto L
74153 **      M: open write cursor to <table> and its indices
74154 **         rewind temp table
74155 **      C: loop over rows of intermediate table
74156 **           transfer values form intermediate table into <table>
74157 **         end loop
74158 **      D: cleanup
74159 */
74160 SQLITE_PRIVATE void sqlite3Insert(
74161   Parse *pParse,        /* Parser context */
74162   SrcList *pTabList,    /* Name of table into which we are inserting */
74163   ExprList *pList,      /* List of values to be inserted */
74164   Select *pSelect,      /* A SELECT statement to use as the data source */
74165   IdList *pColumn,      /* Column names corresponding to IDLIST. */
74166   int onError           /* How to handle constraint errors */
74167 ){
74168   sqlite3 *db;          /* The main database structure */
74169   Table *pTab;          /* The table to insert into.  aka TABLE */
74170   char *zTab;           /* Name of the table into which we are inserting */
74171   const char *zDb;      /* Name of the database holding this table */
74172   int i, j, idx;        /* Loop counters */
74173   Vdbe *v;              /* Generate code into this virtual machine */
74174   Index *pIdx;          /* For looping over indices of the table */
74175   int nColumn;          /* Number of columns in the data */
74176   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
74177   int baseCur = 0;      /* VDBE Cursor number for pTab */
74178   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
74179   int endOfLoop;        /* Label for the end of the insertion loop */
74180   int useTempTable = 0; /* Store SELECT results in intermediate table */
74181   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
74182   int addrInsTop = 0;   /* Jump to label "D" */
74183   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
74184   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
74185   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
74186   int iDb;              /* Index of database holding TABLE */
74187   Db *pDb;              /* The database containing table being inserted into */
74188   int appendFlag = 0;   /* True if the insert is likely to be an append */
74189
74190   /* Register allocations */
74191   int regFromSelect = 0;/* Base register for data coming from SELECT */
74192   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
74193   int regRowCount = 0;  /* Memory cell used for the row counter */
74194   int regIns;           /* Block of regs holding rowid+data being inserted */
74195   int regRowid;         /* registers holding insert rowid */
74196   int regData;          /* register holding first column to insert */
74197   int regRecord;        /* Holds the assemblied row record */
74198   int regEof = 0;       /* Register recording end of SELECT data */
74199   int *aRegIdx = 0;     /* One register allocated to each index */
74200
74201 #ifndef SQLITE_OMIT_TRIGGER
74202   int isView;                 /* True if attempting to insert into a view */
74203   Trigger *pTrigger;          /* List of triggers on pTab, if required */
74204   int tmask;                  /* Mask of trigger times */
74205 #endif
74206
74207   db = pParse->db;
74208   memset(&dest, 0, sizeof(dest));
74209   if( pParse->nErr || db->mallocFailed ){
74210     goto insert_cleanup;
74211   }
74212
74213   /* Locate the table into which we will be inserting new information.
74214   */
74215   assert( pTabList->nSrc==1 );
74216   zTab = pTabList->a[0].zName;
74217   if( NEVER(zTab==0) ) goto insert_cleanup;
74218   pTab = sqlite3SrcListLookup(pParse, pTabList);
74219   if( pTab==0 ){
74220     goto insert_cleanup;
74221   }
74222   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74223   assert( iDb<db->nDb );
74224   pDb = &db->aDb[iDb];
74225   zDb = pDb->zName;
74226   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
74227     goto insert_cleanup;
74228   }
74229
74230   /* Figure out if we have any triggers and if the table being
74231   ** inserted into is a view
74232   */
74233 #ifndef SQLITE_OMIT_TRIGGER
74234   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
74235   isView = pTab->pSelect!=0;
74236 #else
74237 # define pTrigger 0
74238 # define tmask 0
74239 # define isView 0
74240 #endif
74241 #ifdef SQLITE_OMIT_VIEW
74242 # undef isView
74243 # define isView 0
74244 #endif
74245   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
74246
74247   /* If pTab is really a view, make sure it has been initialized.
74248   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
74249   ** module table).
74250   */
74251   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
74252     goto insert_cleanup;
74253   }
74254
74255   /* Ensure that:
74256   *  (a) the table is not read-only, 
74257   *  (b) that if it is a view then ON INSERT triggers exist
74258   */
74259   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
74260     goto insert_cleanup;
74261   }
74262
74263   /* Allocate a VDBE
74264   */
74265   v = sqlite3GetVdbe(pParse);
74266   if( v==0 ) goto insert_cleanup;
74267   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
74268   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
74269
74270 #ifndef SQLITE_OMIT_XFER_OPT
74271   /* If the statement is of the form
74272   **
74273   **       INSERT INTO <table1> SELECT * FROM <table2>;
74274   **
74275   ** Then special optimizations can be applied that make the transfer
74276   ** very fast and which reduce fragmentation of indices.
74277   **
74278   ** This is the 2nd template.
74279   */
74280   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
74281     assert( !pTrigger );
74282     assert( pList==0 );
74283     goto insert_end;
74284   }
74285 #endif /* SQLITE_OMIT_XFER_OPT */
74286
74287   /* If this is an AUTOINCREMENT table, look up the sequence number in the
74288   ** sqlite_sequence table and store it in memory cell regAutoinc.
74289   */
74290   regAutoinc = autoIncBegin(pParse, iDb, pTab);
74291
74292   /* Figure out how many columns of data are supplied.  If the data
74293   ** is coming from a SELECT statement, then generate a co-routine that
74294   ** produces a single row of the SELECT on each invocation.  The
74295   ** co-routine is the common header to the 3rd and 4th templates.
74296   */
74297   if( pSelect ){
74298     /* Data is coming from a SELECT.  Generate code to implement that SELECT
74299     ** as a co-routine.  The code is common to both the 3rd and 4th
74300     ** templates:
74301     **
74302     **         EOF <- 0
74303     **         X <- A
74304     **         goto B
74305     **      A: setup for the SELECT
74306     **         loop over the tables in the SELECT
74307     **           load value into register R..R+n
74308     **           yield X
74309     **         end loop
74310     **         cleanup after the SELECT
74311     **         EOF <- 1
74312     **         yield X
74313     **         halt-error
74314     **
74315     ** On each invocation of the co-routine, it puts a single row of the
74316     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
74317     ** (These output registers are allocated by sqlite3Select().)  When
74318     ** the SELECT completes, it sets the EOF flag stored in regEof.
74319     */
74320     int rc, j1;
74321
74322     regEof = ++pParse->nMem;
74323     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
74324     VdbeComment((v, "SELECT eof flag"));
74325     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
74326     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
74327     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
74328     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
74329     VdbeComment((v, "Jump over SELECT coroutine"));
74330
74331     /* Resolve the expressions in the SELECT statement and execute it. */
74332     rc = sqlite3Select(pParse, pSelect, &dest);
74333     assert( pParse->nErr==0 || rc );
74334     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
74335       goto insert_cleanup;
74336     }
74337     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
74338     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
74339     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
74340     VdbeComment((v, "End of SELECT coroutine"));
74341     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
74342
74343     regFromSelect = dest.iMem;
74344     assert( pSelect->pEList );
74345     nColumn = pSelect->pEList->nExpr;
74346     assert( dest.nMem==nColumn );
74347
74348     /* Set useTempTable to TRUE if the result of the SELECT statement
74349     ** should be written into a temporary table (template 4).  Set to
74350     ** FALSE if each* row of the SELECT can be written directly into
74351     ** the destination table (template 3).
74352     **
74353     ** A temp table must be used if the table being updated is also one
74354     ** of the tables being read by the SELECT statement.  Also use a 
74355     ** temp table in the case of row triggers.
74356     */
74357     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
74358       useTempTable = 1;
74359     }
74360
74361     if( useTempTable ){
74362       /* Invoke the coroutine to extract information from the SELECT
74363       ** and add it to a transient table srcTab.  The code generated
74364       ** here is from the 4th template:
74365       **
74366       **      B: open temp table
74367       **      L: yield X
74368       **         if EOF goto M
74369       **         insert row from R..R+n into temp table
74370       **         goto L
74371       **      M: ...
74372       */
74373       int regRec;          /* Register to hold packed record */
74374       int regTempRowid;    /* Register to hold temp table ROWID */
74375       int addrTop;         /* Label "L" */
74376       int addrIf;          /* Address of jump to M */
74377
74378       srcTab = pParse->nTab++;
74379       regRec = sqlite3GetTempReg(pParse);
74380       regTempRowid = sqlite3GetTempReg(pParse);
74381       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
74382       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
74383       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
74384       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
74385       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
74386       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
74387       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
74388       sqlite3VdbeJumpHere(v, addrIf);
74389       sqlite3ReleaseTempReg(pParse, regRec);
74390       sqlite3ReleaseTempReg(pParse, regTempRowid);
74391     }
74392   }else{
74393     /* This is the case if the data for the INSERT is coming from a VALUES
74394     ** clause
74395     */
74396     NameContext sNC;
74397     memset(&sNC, 0, sizeof(sNC));
74398     sNC.pParse = pParse;
74399     srcTab = -1;
74400     assert( useTempTable==0 );
74401     nColumn = pList ? pList->nExpr : 0;
74402     for(i=0; i<nColumn; i++){
74403       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
74404         goto insert_cleanup;
74405       }
74406     }
74407   }
74408
74409   /* Make sure the number of columns in the source data matches the number
74410   ** of columns to be inserted into the table.
74411   */
74412   if( IsVirtual(pTab) ){
74413     for(i=0; i<pTab->nCol; i++){
74414       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
74415     }
74416   }
74417   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
74418     sqlite3ErrorMsg(pParse, 
74419        "table %S has %d columns but %d values were supplied",
74420        pTabList, 0, pTab->nCol-nHidden, nColumn);
74421     goto insert_cleanup;
74422   }
74423   if( pColumn!=0 && nColumn!=pColumn->nId ){
74424     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
74425     goto insert_cleanup;
74426   }
74427
74428   /* If the INSERT statement included an IDLIST term, then make sure
74429   ** all elements of the IDLIST really are columns of the table and 
74430   ** remember the column indices.
74431   **
74432   ** If the table has an INTEGER PRIMARY KEY column and that column
74433   ** is named in the IDLIST, then record in the keyColumn variable
74434   ** the index into IDLIST of the primary key column.  keyColumn is
74435   ** the index of the primary key as it appears in IDLIST, not as
74436   ** is appears in the original table.  (The index of the primary
74437   ** key in the original table is pTab->iPKey.)
74438   */
74439   if( pColumn ){
74440     for(i=0; i<pColumn->nId; i++){
74441       pColumn->a[i].idx = -1;
74442     }
74443     for(i=0; i<pColumn->nId; i++){
74444       for(j=0; j<pTab->nCol; j++){
74445         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
74446           pColumn->a[i].idx = j;
74447           if( j==pTab->iPKey ){
74448             keyColumn = i;
74449           }
74450           break;
74451         }
74452       }
74453       if( j>=pTab->nCol ){
74454         if( sqlite3IsRowid(pColumn->a[i].zName) ){
74455           keyColumn = i;
74456         }else{
74457           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
74458               pTabList, 0, pColumn->a[i].zName);
74459           pParse->nErr++;
74460           goto insert_cleanup;
74461         }
74462       }
74463     }
74464   }
74465
74466   /* If there is no IDLIST term but the table has an integer primary
74467   ** key, the set the keyColumn variable to the primary key column index
74468   ** in the original table definition.
74469   */
74470   if( pColumn==0 && nColumn>0 ){
74471     keyColumn = pTab->iPKey;
74472   }
74473     
74474   /* Initialize the count of rows to be inserted
74475   */
74476   if( db->flags & SQLITE_CountRows ){
74477     regRowCount = ++pParse->nMem;
74478     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
74479   }
74480
74481   /* If this is not a view, open the table and and all indices */
74482   if( !isView ){
74483     int nIdx;
74484
74485     baseCur = pParse->nTab;
74486     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
74487     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
74488     if( aRegIdx==0 ){
74489       goto insert_cleanup;
74490     }
74491     for(i=0; i<nIdx; i++){
74492       aRegIdx[i] = ++pParse->nMem;
74493     }
74494   }
74495
74496   /* This is the top of the main insertion loop */
74497   if( useTempTable ){
74498     /* This block codes the top of loop only.  The complete loop is the
74499     ** following pseudocode (template 4):
74500     **
74501     **         rewind temp table
74502     **      C: loop over rows of intermediate table
74503     **           transfer values form intermediate table into <table>
74504     **         end loop
74505     **      D: ...
74506     */
74507     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
74508     addrCont = sqlite3VdbeCurrentAddr(v);
74509   }else if( pSelect ){
74510     /* This block codes the top of loop only.  The complete loop is the
74511     ** following pseudocode (template 3):
74512     **
74513     **      C: yield X
74514     **         if EOF goto D
74515     **         insert the select result into <table> from R..R+n
74516     **         goto C
74517     **      D: ...
74518     */
74519     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
74520     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
74521   }
74522
74523   /* Allocate registers for holding the rowid of the new row,
74524   ** the content of the new row, and the assemblied row record.
74525   */
74526   regRecord = ++pParse->nMem;
74527   regRowid = regIns = pParse->nMem+1;
74528   pParse->nMem += pTab->nCol + 1;
74529   if( IsVirtual(pTab) ){
74530     regRowid++;
74531     pParse->nMem++;
74532   }
74533   regData = regRowid+1;
74534
74535   /* Run the BEFORE and INSTEAD OF triggers, if there are any
74536   */
74537   endOfLoop = sqlite3VdbeMakeLabel(v);
74538   if( tmask & TRIGGER_BEFORE ){
74539     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
74540
74541     /* build the NEW.* reference row.  Note that if there is an INTEGER
74542     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
74543     ** translated into a unique ID for the row.  But on a BEFORE trigger,
74544     ** we do not know what the unique ID will be (because the insert has
74545     ** not happened yet) so we substitute a rowid of -1
74546     */
74547     if( keyColumn<0 ){
74548       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
74549     }else{
74550       int j1;
74551       if( useTempTable ){
74552         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
74553       }else{
74554         assert( pSelect==0 );  /* Otherwise useTempTable is true */
74555         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
74556       }
74557       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
74558       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
74559       sqlite3VdbeJumpHere(v, j1);
74560       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
74561     }
74562
74563     /* Cannot have triggers on a virtual table. If it were possible,
74564     ** this block would have to account for hidden column.
74565     */
74566     assert( !IsVirtual(pTab) );
74567
74568     /* Create the new column data
74569     */
74570     for(i=0; i<pTab->nCol; i++){
74571       if( pColumn==0 ){
74572         j = i;
74573       }else{
74574         for(j=0; j<pColumn->nId; j++){
74575           if( pColumn->a[j].idx==i ) break;
74576         }
74577       }
74578       if( pColumn && j>=pColumn->nId ){
74579         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
74580       }else if( useTempTable ){
74581         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
74582       }else{
74583         assert( pSelect==0 ); /* Otherwise useTempTable is true */
74584         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
74585       }
74586     }
74587
74588     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
74589     ** do not attempt any conversions before assembling the record.
74590     ** If this is a real table, attempt conversions as required by the
74591     ** table column affinities.
74592     */
74593     if( !isView ){
74594       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
74595       sqlite3TableAffinityStr(v, pTab);
74596     }
74597
74598     /* Fire BEFORE or INSTEAD OF triggers */
74599     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
74600         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
74601
74602     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
74603   }
74604
74605   /* Push the record number for the new entry onto the stack.  The
74606   ** record number is a randomly generate integer created by NewRowid
74607   ** except when the table has an INTEGER PRIMARY KEY column, in which
74608   ** case the record number is the same as that column. 
74609   */
74610   if( !isView ){
74611     if( IsVirtual(pTab) ){
74612       /* The row that the VUpdate opcode will delete: none */
74613       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
74614     }
74615     if( keyColumn>=0 ){
74616       if( useTempTable ){
74617         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
74618       }else if( pSelect ){
74619         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
74620       }else{
74621         VdbeOp *pOp;
74622         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
74623         pOp = sqlite3VdbeGetOp(v, -1);
74624         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
74625           appendFlag = 1;
74626           pOp->opcode = OP_NewRowid;
74627           pOp->p1 = baseCur;
74628           pOp->p2 = regRowid;
74629           pOp->p3 = regAutoinc;
74630         }
74631       }
74632       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
74633       ** to generate a unique primary key value.
74634       */
74635       if( !appendFlag ){
74636         int j1;
74637         if( !IsVirtual(pTab) ){
74638           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
74639           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
74640           sqlite3VdbeJumpHere(v, j1);
74641         }else{
74642           j1 = sqlite3VdbeCurrentAddr(v);
74643           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
74644         }
74645         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
74646       }
74647     }else if( IsVirtual(pTab) ){
74648       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
74649     }else{
74650       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
74651       appendFlag = 1;
74652     }
74653     autoIncStep(pParse, regAutoinc, regRowid);
74654
74655     /* Push onto the stack, data for all columns of the new entry, beginning
74656     ** with the first column.
74657     */
74658     nHidden = 0;
74659     for(i=0; i<pTab->nCol; i++){
74660       int iRegStore = regRowid+1+i;
74661       if( i==pTab->iPKey ){
74662         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
74663         ** Whenever this column is read, the record number will be substituted
74664         ** in its place.  So will fill this column with a NULL to avoid
74665         ** taking up data space with information that will never be used. */
74666         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
74667         continue;
74668       }
74669       if( pColumn==0 ){
74670         if( IsHiddenColumn(&pTab->aCol[i]) ){
74671           assert( IsVirtual(pTab) );
74672           j = -1;
74673           nHidden++;
74674         }else{
74675           j = i - nHidden;
74676         }
74677       }else{
74678         for(j=0; j<pColumn->nId; j++){
74679           if( pColumn->a[j].idx==i ) break;
74680         }
74681       }
74682       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
74683         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
74684       }else if( useTempTable ){
74685         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
74686       }else if( pSelect ){
74687         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
74688       }else{
74689         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
74690       }
74691     }
74692
74693     /* Generate code to check constraints and generate index keys and
74694     ** do the insertion.
74695     */
74696 #ifndef SQLITE_OMIT_VIRTUALTABLE
74697     if( IsVirtual(pTab) ){
74698       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
74699       sqlite3VtabMakeWritable(pParse, pTab);
74700       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
74701       sqlite3MayAbort(pParse);
74702     }else
74703 #endif
74704     {
74705       int isReplace;    /* Set to true if constraints may cause a replace */
74706       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
74707           keyColumn>=0, 0, onError, endOfLoop, &isReplace
74708       );
74709       sqlite3FkCheck(pParse, pTab, 0, regIns);
74710       sqlite3CompleteInsertion(
74711           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
74712       );
74713     }
74714   }
74715
74716   /* Update the count of rows that are inserted
74717   */
74718   if( (db->flags & SQLITE_CountRows)!=0 ){
74719     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
74720   }
74721
74722   if( pTrigger ){
74723     /* Code AFTER triggers */
74724     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
74725         pTab, regData-2-pTab->nCol, onError, endOfLoop);
74726   }
74727
74728   /* The bottom of the main insertion loop, if the data source
74729   ** is a SELECT statement.
74730   */
74731   sqlite3VdbeResolveLabel(v, endOfLoop);
74732   if( useTempTable ){
74733     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
74734     sqlite3VdbeJumpHere(v, addrInsTop);
74735     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
74736   }else if( pSelect ){
74737     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
74738     sqlite3VdbeJumpHere(v, addrInsTop);
74739   }
74740
74741   if( !IsVirtual(pTab) && !isView ){
74742     /* Close all tables opened */
74743     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
74744     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
74745       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
74746     }
74747   }
74748
74749 insert_end:
74750   /* Update the sqlite_sequence table by storing the content of the
74751   ** maximum rowid counter values recorded while inserting into
74752   ** autoincrement tables.
74753   */
74754   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
74755     sqlite3AutoincrementEnd(pParse);
74756   }
74757
74758   /*
74759   ** Return the number of rows inserted. If this routine is 
74760   ** generating code because of a call to sqlite3NestedParse(), do not
74761   ** invoke the callback function.
74762   */
74763   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
74764     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
74765     sqlite3VdbeSetNumCols(v, 1);
74766     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
74767   }
74768
74769 insert_cleanup:
74770   sqlite3SrcListDelete(db, pTabList);
74771   sqlite3ExprListDelete(db, pList);
74772   sqlite3SelectDelete(db, pSelect);
74773   sqlite3IdListDelete(db, pColumn);
74774   sqlite3DbFree(db, aRegIdx);
74775 }
74776
74777 /* Make sure "isView" and other macros defined above are undefined. Otherwise
74778 ** thely may interfere with compilation of other functions in this file
74779 ** (or in another file, if this file becomes part of the amalgamation).  */
74780 #ifdef isView
74781  #undef isView
74782 #endif
74783 #ifdef pTrigger
74784  #undef pTrigger
74785 #endif
74786 #ifdef tmask
74787  #undef tmask
74788 #endif
74789
74790
74791 /*
74792 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
74793 **
74794 ** The input is a range of consecutive registers as follows:
74795 **
74796 **    1.  The rowid of the row after the update.
74797 **
74798 **    2.  The data in the first column of the entry after the update.
74799 **
74800 **    i.  Data from middle columns...
74801 **
74802 **    N.  The data in the last column of the entry after the update.
74803 **
74804 ** The regRowid parameter is the index of the register containing (1).
74805 **
74806 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
74807 ** the address of a register containing the rowid before the update takes
74808 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
74809 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
74810 ** indicates that the rowid was explicitly specified as part of the
74811 ** INSERT statement. If rowidChng is false, it means that  the rowid is
74812 ** computed automatically in an insert or that the rowid value is not 
74813 ** modified by an update.
74814 **
74815 ** The code generated by this routine store new index entries into
74816 ** registers identified by aRegIdx[].  No index entry is created for
74817 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
74818 ** the same as the order of indices on the linked list of indices
74819 ** attached to the table.
74820 **
74821 ** This routine also generates code to check constraints.  NOT NULL,
74822 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
74823 ** then the appropriate action is performed.  There are five possible
74824 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
74825 **
74826 **  Constraint type  Action       What Happens
74827 **  ---------------  ----------   ----------------------------------------
74828 **  any              ROLLBACK     The current transaction is rolled back and
74829 **                                sqlite3_exec() returns immediately with a
74830 **                                return code of SQLITE_CONSTRAINT.
74831 **
74832 **  any              ABORT        Back out changes from the current command
74833 **                                only (do not do a complete rollback) then
74834 **                                cause sqlite3_exec() to return immediately
74835 **                                with SQLITE_CONSTRAINT.
74836 **
74837 **  any              FAIL         Sqlite_exec() returns immediately with a
74838 **                                return code of SQLITE_CONSTRAINT.  The
74839 **                                transaction is not rolled back and any
74840 **                                prior changes are retained.
74841 **
74842 **  any              IGNORE       The record number and data is popped from
74843 **                                the stack and there is an immediate jump
74844 **                                to label ignoreDest.
74845 **
74846 **  NOT NULL         REPLACE      The NULL value is replace by the default
74847 **                                value for that column.  If the default value
74848 **                                is NULL, the action is the same as ABORT.
74849 **
74850 **  UNIQUE           REPLACE      The other row that conflicts with the row
74851 **                                being inserted is removed.
74852 **
74853 **  CHECK            REPLACE      Illegal.  The results in an exception.
74854 **
74855 ** Which action to take is determined by the overrideError parameter.
74856 ** Or if overrideError==OE_Default, then the pParse->onError parameter
74857 ** is used.  Or if pParse->onError==OE_Default then the onError value
74858 ** for the constraint is used.
74859 **
74860 ** The calling routine must open a read/write cursor for pTab with
74861 ** cursor number "baseCur".  All indices of pTab must also have open
74862 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
74863 ** Except, if there is no possibility of a REPLACE action then
74864 ** cursors do not need to be open for indices where aRegIdx[i]==0.
74865 */
74866 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
74867   Parse *pParse,      /* The parser context */
74868   Table *pTab,        /* the table into which we are inserting */
74869   int baseCur,        /* Index of a read/write cursor pointing at pTab */
74870   int regRowid,       /* Index of the range of input registers */
74871   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
74872   int rowidChng,      /* True if the rowid might collide with existing entry */
74873   int isUpdate,       /* True for UPDATE, False for INSERT */
74874   int overrideError,  /* Override onError to this if not OE_Default */
74875   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
74876   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
74877 ){
74878   int i;              /* loop counter */
74879   Vdbe *v;            /* VDBE under constrution */
74880   int nCol;           /* Number of columns */
74881   int onError;        /* Conflict resolution strategy */
74882   int j1;             /* Addresss of jump instruction */
74883   int j2 = 0, j3;     /* Addresses of jump instructions */
74884   int regData;        /* Register containing first data column */
74885   int iCur;           /* Table cursor number */
74886   Index *pIdx;         /* Pointer to one of the indices */
74887   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
74888   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
74889
74890   v = sqlite3GetVdbe(pParse);
74891   assert( v!=0 );
74892   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
74893   nCol = pTab->nCol;
74894   regData = regRowid + 1;
74895
74896   /* Test all NOT NULL constraints.
74897   */
74898   for(i=0; i<nCol; i++){
74899     if( i==pTab->iPKey ){
74900       continue;
74901     }
74902     onError = pTab->aCol[i].notNull;
74903     if( onError==OE_None ) continue;
74904     if( overrideError!=OE_Default ){
74905       onError = overrideError;
74906     }else if( onError==OE_Default ){
74907       onError = OE_Abort;
74908     }
74909     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
74910       onError = OE_Abort;
74911     }
74912     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
74913         || onError==OE_Ignore || onError==OE_Replace );
74914     switch( onError ){
74915       case OE_Abort:
74916         sqlite3MayAbort(pParse);
74917       case OE_Rollback:
74918       case OE_Fail: {
74919         char *zMsg;
74920         j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
74921                                   SQLITE_CONSTRAINT, onError, regData+i);
74922         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
74923                               pTab->zName, pTab->aCol[i].zName);
74924         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
74925         break;
74926       }
74927       case OE_Ignore: {
74928         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
74929         break;
74930       }
74931       default: {
74932         assert( onError==OE_Replace );
74933         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
74934         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
74935         sqlite3VdbeJumpHere(v, j1);
74936         break;
74937       }
74938     }
74939   }
74940
74941   /* Test all CHECK constraints
74942   */
74943 #ifndef SQLITE_OMIT_CHECK
74944   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
74945     int allOk = sqlite3VdbeMakeLabel(v);
74946     pParse->ckBase = regData;
74947     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
74948     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
74949     if( onError==OE_Ignore ){
74950       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
74951     }else{
74952       sqlite3HaltConstraint(pParse, onError, 0, 0);
74953     }
74954     sqlite3VdbeResolveLabel(v, allOk);
74955   }
74956 #endif /* !defined(SQLITE_OMIT_CHECK) */
74957
74958   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
74959   ** of the new record does not previously exist.  Except, if this
74960   ** is an UPDATE and the primary key is not changing, that is OK.
74961   */
74962   if( rowidChng ){
74963     onError = pTab->keyConf;
74964     if( overrideError!=OE_Default ){
74965       onError = overrideError;
74966     }else if( onError==OE_Default ){
74967       onError = OE_Abort;
74968     }
74969     
74970     if( isUpdate ){
74971       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
74972     }
74973     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
74974     switch( onError ){
74975       default: {
74976         onError = OE_Abort;
74977         /* Fall thru into the next case */
74978       }
74979       case OE_Rollback:
74980       case OE_Abort:
74981       case OE_Fail: {
74982         sqlite3HaltConstraint(
74983           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
74984         break;
74985       }
74986       case OE_Replace: {
74987         /* If there are DELETE triggers on this table and the
74988         ** recursive-triggers flag is set, call GenerateRowDelete() to
74989         ** remove the conflicting row from the the table. This will fire
74990         ** the triggers and remove both the table and index b-tree entries.
74991         **
74992         ** Otherwise, if there are no triggers or the recursive-triggers
74993         ** flag is not set, call GenerateRowIndexDelete(). This removes
74994         ** the index b-tree entries only. The table b-tree entry will be 
74995         ** replaced by the new entry when it is inserted.  */
74996         Trigger *pTrigger = 0;
74997         if( pParse->db->flags&SQLITE_RecTriggers ){
74998           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
74999         }
75000         sqlite3MultiWrite(pParse);
75001         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
75002           sqlite3GenerateRowDelete(
75003               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
75004           );
75005         }else{
75006           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
75007         }
75008         seenReplace = 1;
75009         break;
75010       }
75011       case OE_Ignore: {
75012         assert( seenReplace==0 );
75013         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
75014         break;
75015       }
75016     }
75017     sqlite3VdbeJumpHere(v, j3);
75018     if( isUpdate ){
75019       sqlite3VdbeJumpHere(v, j2);
75020     }
75021   }
75022
75023   /* Test all UNIQUE constraints by creating entries for each UNIQUE
75024   ** index and making sure that duplicate entries do not already exist.
75025   ** Add the new records to the indices as we go.
75026   */
75027   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
75028     int regIdx;
75029     int regR;
75030
75031     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
75032
75033     /* Create a key for accessing the index entry */
75034     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
75035     for(i=0; i<pIdx->nColumn; i++){
75036       int idx = pIdx->aiColumn[i];
75037       if( idx==pTab->iPKey ){
75038         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
75039       }else{
75040         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
75041       }
75042     }
75043     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
75044     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
75045     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
75046     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
75047
75048     /* Find out what action to take in case there is an indexing conflict */
75049     onError = pIdx->onError;
75050     if( onError==OE_None ){ 
75051       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
75052       continue;  /* pIdx is not a UNIQUE index */
75053     }
75054     if( overrideError!=OE_Default ){
75055       onError = overrideError;
75056     }else if( onError==OE_Default ){
75057       onError = OE_Abort;
75058     }
75059     if( seenReplace ){
75060       if( onError==OE_Ignore ) onError = OE_Replace;
75061       else if( onError==OE_Fail ) onError = OE_Abort;
75062     }
75063     
75064     /* Check to see if the new index entry will be unique */
75065     regR = sqlite3GetTempReg(pParse);
75066     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
75067     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
75068                            regR, SQLITE_INT_TO_PTR(regIdx),
75069                            P4_INT32);
75070     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
75071
75072     /* Generate code that executes if the new index entry is not unique */
75073     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
75074         || onError==OE_Ignore || onError==OE_Replace );
75075     switch( onError ){
75076       case OE_Rollback:
75077       case OE_Abort:
75078       case OE_Fail: {
75079         int j;
75080         StrAccum errMsg;
75081         const char *zSep;
75082         char *zErr;
75083
75084         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
75085         errMsg.db = pParse->db;
75086         zSep = pIdx->nColumn>1 ? "columns " : "column ";
75087         for(j=0; j<pIdx->nColumn; j++){
75088           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
75089           sqlite3StrAccumAppend(&errMsg, zSep, -1);
75090           zSep = ", ";
75091           sqlite3StrAccumAppend(&errMsg, zCol, -1);
75092         }
75093         sqlite3StrAccumAppend(&errMsg,
75094             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
75095         zErr = sqlite3StrAccumFinish(&errMsg);
75096         sqlite3HaltConstraint(pParse, onError, zErr, 0);
75097         sqlite3DbFree(errMsg.db, zErr);
75098         break;
75099       }
75100       case OE_Ignore: {
75101         assert( seenReplace==0 );
75102         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
75103         break;
75104       }
75105       default: {
75106         Trigger *pTrigger = 0;
75107         assert( onError==OE_Replace );
75108         sqlite3MultiWrite(pParse);
75109         if( pParse->db->flags&SQLITE_RecTriggers ){
75110           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
75111         }
75112         sqlite3GenerateRowDelete(
75113             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
75114         );
75115         seenReplace = 1;
75116         break;
75117       }
75118     }
75119     sqlite3VdbeJumpHere(v, j3);
75120     sqlite3ReleaseTempReg(pParse, regR);
75121   }
75122   
75123   if( pbMayReplace ){
75124     *pbMayReplace = seenReplace;
75125   }
75126 }
75127
75128 /*
75129 ** This routine generates code to finish the INSERT or UPDATE operation
75130 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
75131 ** A consecutive range of registers starting at regRowid contains the
75132 ** rowid and the content to be inserted.
75133 **
75134 ** The arguments to this routine should be the same as the first six
75135 ** arguments to sqlite3GenerateConstraintChecks.
75136 */
75137 SQLITE_PRIVATE void sqlite3CompleteInsertion(
75138   Parse *pParse,      /* The parser context */
75139   Table *pTab,        /* the table into which we are inserting */
75140   int baseCur,        /* Index of a read/write cursor pointing at pTab */
75141   int regRowid,       /* Range of content */
75142   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
75143   int isUpdate,       /* True for UPDATE, False for INSERT */
75144   int appendBias,     /* True if this is likely to be an append */
75145   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
75146 ){
75147   int i;
75148   Vdbe *v;
75149   int nIdx;
75150   Index *pIdx;
75151   u8 pik_flags;
75152   int regData;
75153   int regRec;
75154
75155   v = sqlite3GetVdbe(pParse);
75156   assert( v!=0 );
75157   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
75158   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
75159   for(i=nIdx-1; i>=0; i--){
75160     if( aRegIdx[i]==0 ) continue;
75161     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
75162     if( useSeekResult ){
75163       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
75164     }
75165   }
75166   regData = regRowid + 1;
75167   regRec = sqlite3GetTempReg(pParse);
75168   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
75169   sqlite3TableAffinityStr(v, pTab);
75170   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
75171   if( pParse->nested ){
75172     pik_flags = 0;
75173   }else{
75174     pik_flags = OPFLAG_NCHANGE;
75175     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
75176   }
75177   if( appendBias ){
75178     pik_flags |= OPFLAG_APPEND;
75179   }
75180   if( useSeekResult ){
75181     pik_flags |= OPFLAG_USESEEKRESULT;
75182   }
75183   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
75184   if( !pParse->nested ){
75185     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
75186   }
75187   sqlite3VdbeChangeP5(v, pik_flags);
75188 }
75189
75190 /*
75191 ** Generate code that will open cursors for a table and for all
75192 ** indices of that table.  The "baseCur" parameter is the cursor number used
75193 ** for the table.  Indices are opened on subsequent cursors.
75194 **
75195 ** Return the number of indices on the table.
75196 */
75197 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
75198   Parse *pParse,   /* Parsing context */
75199   Table *pTab,     /* Table to be opened */
75200   int baseCur,     /* Cursor number assigned to the table */
75201   int op           /* OP_OpenRead or OP_OpenWrite */
75202 ){
75203   int i;
75204   int iDb;
75205   Index *pIdx;
75206   Vdbe *v;
75207
75208   if( IsVirtual(pTab) ) return 0;
75209   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75210   v = sqlite3GetVdbe(pParse);
75211   assert( v!=0 );
75212   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
75213   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
75214     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
75215     assert( pIdx->pSchema==pTab->pSchema );
75216     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
75217                       (char*)pKey, P4_KEYINFO_HANDOFF);
75218     VdbeComment((v, "%s", pIdx->zName));
75219   }
75220   if( pParse->nTab<baseCur+i ){
75221     pParse->nTab = baseCur+i;
75222   }
75223   return i-1;
75224 }
75225
75226
75227 #ifdef SQLITE_TEST
75228 /*
75229 ** The following global variable is incremented whenever the
75230 ** transfer optimization is used.  This is used for testing
75231 ** purposes only - to make sure the transfer optimization really
75232 ** is happening when it is suppose to.
75233 */
75234 SQLITE_API int sqlite3_xferopt_count;
75235 #endif /* SQLITE_TEST */
75236
75237
75238 #ifndef SQLITE_OMIT_XFER_OPT
75239 /*
75240 ** Check to collation names to see if they are compatible.
75241 */
75242 static int xferCompatibleCollation(const char *z1, const char *z2){
75243   if( z1==0 ){
75244     return z2==0;
75245   }
75246   if( z2==0 ){
75247     return 0;
75248   }
75249   return sqlite3StrICmp(z1, z2)==0;
75250 }
75251
75252
75253 /*
75254 ** Check to see if index pSrc is compatible as a source of data
75255 ** for index pDest in an insert transfer optimization.  The rules
75256 ** for a compatible index:
75257 **
75258 **    *   The index is over the same set of columns
75259 **    *   The same DESC and ASC markings occurs on all columns
75260 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
75261 **    *   The same collating sequence on each column
75262 */
75263 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
75264   int i;
75265   assert( pDest && pSrc );
75266   assert( pDest->pTable!=pSrc->pTable );
75267   if( pDest->nColumn!=pSrc->nColumn ){
75268     return 0;   /* Different number of columns */
75269   }
75270   if( pDest->onError!=pSrc->onError ){
75271     return 0;   /* Different conflict resolution strategies */
75272   }
75273   for(i=0; i<pSrc->nColumn; i++){
75274     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
75275       return 0;   /* Different columns indexed */
75276     }
75277     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
75278       return 0;   /* Different sort orders */
75279     }
75280     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
75281       return 0;   /* Different collating sequences */
75282     }
75283   }
75284
75285   /* If no test above fails then the indices must be compatible */
75286   return 1;
75287 }
75288
75289 /*
75290 ** Attempt the transfer optimization on INSERTs of the form
75291 **
75292 **     INSERT INTO tab1 SELECT * FROM tab2;
75293 **
75294 ** This optimization is only attempted if
75295 **
75296 **    (1)  tab1 and tab2 have identical schemas including all the
75297 **         same indices and constraints
75298 **
75299 **    (2)  tab1 and tab2 are different tables
75300 **
75301 **    (3)  There must be no triggers on tab1
75302 **
75303 **    (4)  The result set of the SELECT statement is "*"
75304 **
75305 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
75306 **         or LIMIT clause.
75307 **
75308 **    (6)  The SELECT statement is a simple (not a compound) select that
75309 **         contains only tab2 in its FROM clause
75310 **
75311 ** This method for implementing the INSERT transfers raw records from
75312 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
75313 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
75314 ** the resulting tab1 has much less fragmentation.
75315 **
75316 ** This routine returns TRUE if the optimization is attempted.  If any
75317 ** of the conditions above fail so that the optimization should not
75318 ** be attempted, then this routine returns FALSE.
75319 */
75320 static int xferOptimization(
75321   Parse *pParse,        /* Parser context */
75322   Table *pDest,         /* The table we are inserting into */
75323   Select *pSelect,      /* A SELECT statement to use as the data source */
75324   int onError,          /* How to handle constraint errors */
75325   int iDbDest           /* The database of pDest */
75326 ){
75327   ExprList *pEList;                /* The result set of the SELECT */
75328   Table *pSrc;                     /* The table in the FROM clause of SELECT */
75329   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
75330   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
75331   int i;                           /* Loop counter */
75332   int iDbSrc;                      /* The database of pSrc */
75333   int iSrc, iDest;                 /* Cursors from source and destination */
75334   int addr1, addr2;                /* Loop addresses */
75335   int emptyDestTest;               /* Address of test for empty pDest */
75336   int emptySrcTest;                /* Address of test for empty pSrc */
75337   Vdbe *v;                         /* The VDBE we are building */
75338   KeyInfo *pKey;                   /* Key information for an index */
75339   int regAutoinc;                  /* Memory register used by AUTOINC */
75340   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
75341   int regData, regRowid;           /* Registers holding data and rowid */
75342
75343   if( pSelect==0 ){
75344     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
75345   }
75346   if( sqlite3TriggerList(pParse, pDest) ){
75347     return 0;   /* tab1 must not have triggers */
75348   }
75349 #ifndef SQLITE_OMIT_VIRTUALTABLE
75350   if( pDest->tabFlags & TF_Virtual ){
75351     return 0;   /* tab1 must not be a virtual table */
75352   }
75353 #endif
75354   if( onError==OE_Default ){
75355     onError = OE_Abort;
75356   }
75357   if( onError!=OE_Abort && onError!=OE_Rollback ){
75358     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
75359   }
75360   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
75361   if( pSelect->pSrc->nSrc!=1 ){
75362     return 0;   /* FROM clause must have exactly one term */
75363   }
75364   if( pSelect->pSrc->a[0].pSelect ){
75365     return 0;   /* FROM clause cannot contain a subquery */
75366   }
75367   if( pSelect->pWhere ){
75368     return 0;   /* SELECT may not have a WHERE clause */
75369   }
75370   if( pSelect->pOrderBy ){
75371     return 0;   /* SELECT may not have an ORDER BY clause */
75372   }
75373   /* Do not need to test for a HAVING clause.  If HAVING is present but
75374   ** there is no ORDER BY, we will get an error. */
75375   if( pSelect->pGroupBy ){
75376     return 0;   /* SELECT may not have a GROUP BY clause */
75377   }
75378   if( pSelect->pLimit ){
75379     return 0;   /* SELECT may not have a LIMIT clause */
75380   }
75381   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
75382   if( pSelect->pPrior ){
75383     return 0;   /* SELECT may not be a compound query */
75384   }
75385   if( pSelect->selFlags & SF_Distinct ){
75386     return 0;   /* SELECT may not be DISTINCT */
75387   }
75388   pEList = pSelect->pEList;
75389   assert( pEList!=0 );
75390   if( pEList->nExpr!=1 ){
75391     return 0;   /* The result set must have exactly one column */
75392   }
75393   assert( pEList->a[0].pExpr );
75394   if( pEList->a[0].pExpr->op!=TK_ALL ){
75395     return 0;   /* The result set must be the special operator "*" */
75396   }
75397
75398   /* At this point we have established that the statement is of the
75399   ** correct syntactic form to participate in this optimization.  Now
75400   ** we have to check the semantics.
75401   */
75402   pItem = pSelect->pSrc->a;
75403   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
75404   if( pSrc==0 ){
75405     return 0;   /* FROM clause does not contain a real table */
75406   }
75407   if( pSrc==pDest ){
75408     return 0;   /* tab1 and tab2 may not be the same table */
75409   }
75410 #ifndef SQLITE_OMIT_VIRTUALTABLE
75411   if( pSrc->tabFlags & TF_Virtual ){
75412     return 0;   /* tab2 must not be a virtual table */
75413   }
75414 #endif
75415   if( pSrc->pSelect ){
75416     return 0;   /* tab2 may not be a view */
75417   }
75418   if( pDest->nCol!=pSrc->nCol ){
75419     return 0;   /* Number of columns must be the same in tab1 and tab2 */
75420   }
75421   if( pDest->iPKey!=pSrc->iPKey ){
75422     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
75423   }
75424   for(i=0; i<pDest->nCol; i++){
75425     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
75426       return 0;    /* Affinity must be the same on all columns */
75427     }
75428     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
75429       return 0;    /* Collating sequence must be the same on all columns */
75430     }
75431     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
75432       return 0;    /* tab2 must be NOT NULL if tab1 is */
75433     }
75434   }
75435   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
75436     if( pDestIdx->onError!=OE_None ){
75437       destHasUniqueIdx = 1;
75438     }
75439     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
75440       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
75441     }
75442     if( pSrcIdx==0 ){
75443       return 0;    /* pDestIdx has no corresponding index in pSrc */
75444     }
75445   }
75446 #ifndef SQLITE_OMIT_CHECK
75447   if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
75448     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
75449   }
75450 #endif
75451
75452   /* If we get this far, it means either:
75453   **
75454   **    *   We can always do the transfer if the table contains an
75455   **        an integer primary key
75456   **
75457   **    *   We can conditionally do the transfer if the destination
75458   **        table is empty.
75459   */
75460 #ifdef SQLITE_TEST
75461   sqlite3_xferopt_count++;
75462 #endif
75463   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
75464   v = sqlite3GetVdbe(pParse);
75465   sqlite3CodeVerifySchema(pParse, iDbSrc);
75466   iSrc = pParse->nTab++;
75467   iDest = pParse->nTab++;
75468   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
75469   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
75470   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
75471     /* If tables do not have an INTEGER PRIMARY KEY and there
75472     ** are indices to be copied and the destination is not empty,
75473     ** we have to disallow the transfer optimization because the
75474     ** the rowids might change which will mess up indexing.
75475     **
75476     ** Or if the destination has a UNIQUE index and is not empty,
75477     ** we also disallow the transfer optimization because we cannot
75478     ** insure that all entries in the union of DEST and SRC will be
75479     ** unique.
75480     */
75481     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
75482     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
75483     sqlite3VdbeJumpHere(v, addr1);
75484   }else{
75485     emptyDestTest = 0;
75486   }
75487   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
75488   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
75489   regData = sqlite3GetTempReg(pParse);
75490   regRowid = sqlite3GetTempReg(pParse);
75491   if( pDest->iPKey>=0 ){
75492     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
75493     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
75494     sqlite3HaltConstraint(
75495         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
75496     sqlite3VdbeJumpHere(v, addr2);
75497     autoIncStep(pParse, regAutoinc, regRowid);
75498   }else if( pDest->pIndex==0 ){
75499     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
75500   }else{
75501     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
75502     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
75503   }
75504   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
75505   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
75506   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
75507   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
75508   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
75509   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
75510     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
75511       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
75512     }
75513     assert( pSrcIdx );
75514     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
75515     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
75516     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
75517     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
75518                       (char*)pKey, P4_KEYINFO_HANDOFF);
75519     VdbeComment((v, "%s", pSrcIdx->zName));
75520     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
75521     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
75522                       (char*)pKey, P4_KEYINFO_HANDOFF);
75523     VdbeComment((v, "%s", pDestIdx->zName));
75524     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
75525     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
75526     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
75527     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
75528     sqlite3VdbeJumpHere(v, addr1);
75529   }
75530   sqlite3VdbeJumpHere(v, emptySrcTest);
75531   sqlite3ReleaseTempReg(pParse, regRowid);
75532   sqlite3ReleaseTempReg(pParse, regData);
75533   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
75534   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
75535   if( emptyDestTest ){
75536     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
75537     sqlite3VdbeJumpHere(v, emptyDestTest);
75538     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
75539     return 0;
75540   }else{
75541     return 1;
75542   }
75543 }
75544 #endif /* SQLITE_OMIT_XFER_OPT */
75545
75546 /************** End of insert.c **********************************************/
75547 /************** Begin file legacy.c ******************************************/
75548 /*
75549 ** 2001 September 15
75550 **
75551 ** The author disclaims copyright to this source code.  In place of
75552 ** a legal notice, here is a blessing:
75553 **
75554 **    May you do good and not evil.
75555 **    May you find forgiveness for yourself and forgive others.
75556 **    May you share freely, never taking more than you give.
75557 **
75558 *************************************************************************
75559 ** Main file for the SQLite library.  The routines in this file
75560 ** implement the programmer interface to the library.  Routines in
75561 ** other files are for internal use by SQLite and should not be
75562 ** accessed by users of the library.
75563 */
75564
75565
75566 /*
75567 ** Execute SQL code.  Return one of the SQLITE_ success/failure
75568 ** codes.  Also write an error message into memory obtained from
75569 ** malloc() and make *pzErrMsg point to that message.
75570 **
75571 ** If the SQL is a query, then for each row in the query result
75572 ** the xCallback() function is called.  pArg becomes the first
75573 ** argument to xCallback().  If xCallback=NULL then no callback
75574 ** is invoked, even for queries.
75575 */
75576 SQLITE_API int sqlite3_exec(
75577   sqlite3 *db,                /* The database on which the SQL executes */
75578   const char *zSql,           /* The SQL to be executed */
75579   sqlite3_callback xCallback, /* Invoke this callback routine */
75580   void *pArg,                 /* First argument to xCallback() */
75581   char **pzErrMsg             /* Write error messages here */
75582 ){
75583   int rc = SQLITE_OK;         /* Return code */
75584   const char *zLeftover;      /* Tail of unprocessed SQL */
75585   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
75586   char **azCols = 0;          /* Names of result columns */
75587   int nRetry = 0;             /* Number of retry attempts */
75588   int callbackIsInit;         /* True if callback data is initialized */
75589
75590   if( zSql==0 ) zSql = "";
75591
75592   sqlite3_mutex_enter(db->mutex);
75593   sqlite3Error(db, SQLITE_OK, 0);
75594   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
75595     int nCol;
75596     char **azVals = 0;
75597
75598     pStmt = 0;
75599     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
75600     assert( rc==SQLITE_OK || pStmt==0 );
75601     if( rc!=SQLITE_OK ){
75602       continue;
75603     }
75604     if( !pStmt ){
75605       /* this happens for a comment or white-space */
75606       zSql = zLeftover;
75607       continue;
75608     }
75609
75610     callbackIsInit = 0;
75611     nCol = sqlite3_column_count(pStmt);
75612
75613     while( 1 ){
75614       int i;
75615       rc = sqlite3_step(pStmt);
75616
75617       /* Invoke the callback function if required */
75618       if( xCallback && (SQLITE_ROW==rc || 
75619           (SQLITE_DONE==rc && !callbackIsInit
75620                            && db->flags&SQLITE_NullCallback)) ){
75621         if( !callbackIsInit ){
75622           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
75623           if( azCols==0 ){
75624             goto exec_out;
75625           }
75626           for(i=0; i<nCol; i++){
75627             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
75628             /* sqlite3VdbeSetColName() installs column names as UTF8
75629             ** strings so there is no way for sqlite3_column_name() to fail. */
75630             assert( azCols[i]!=0 );
75631           }
75632           callbackIsInit = 1;
75633         }
75634         if( rc==SQLITE_ROW ){
75635           azVals = &azCols[nCol];
75636           for(i=0; i<nCol; i++){
75637             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
75638             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
75639               db->mallocFailed = 1;
75640               goto exec_out;
75641             }
75642           }
75643         }
75644         if( xCallback(pArg, nCol, azVals, azCols) ){
75645           rc = SQLITE_ABORT;
75646           sqlite3VdbeFinalize((Vdbe *)pStmt);
75647           pStmt = 0;
75648           sqlite3Error(db, SQLITE_ABORT, 0);
75649           goto exec_out;
75650         }
75651       }
75652
75653       if( rc!=SQLITE_ROW ){
75654         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
75655         pStmt = 0;
75656         if( rc!=SQLITE_SCHEMA ){
75657           nRetry = 0;
75658           zSql = zLeftover;
75659           while( sqlite3Isspace(zSql[0]) ) zSql++;
75660         }
75661         break;
75662       }
75663     }
75664
75665     sqlite3DbFree(db, azCols);
75666     azCols = 0;
75667   }
75668
75669 exec_out:
75670   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
75671   sqlite3DbFree(db, azCols);
75672
75673   rc = sqlite3ApiExit(db, rc);
75674   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
75675     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
75676     *pzErrMsg = sqlite3Malloc(nErrMsg);
75677     if( *pzErrMsg ){
75678       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
75679     }else{
75680       rc = SQLITE_NOMEM;
75681       sqlite3Error(db, SQLITE_NOMEM, 0);
75682     }
75683   }else if( pzErrMsg ){
75684     *pzErrMsg = 0;
75685   }
75686
75687   assert( (rc&db->errMask)==rc );
75688   sqlite3_mutex_leave(db->mutex);
75689   return rc;
75690 }
75691
75692 /************** End of legacy.c **********************************************/
75693 /************** Begin file loadext.c *****************************************/
75694 /*
75695 ** 2006 June 7
75696 **
75697 ** The author disclaims copyright to this source code.  In place of
75698 ** a legal notice, here is a blessing:
75699 **
75700 **    May you do good and not evil.
75701 **    May you find forgiveness for yourself and forgive others.
75702 **    May you share freely, never taking more than you give.
75703 **
75704 *************************************************************************
75705 ** This file contains code used to dynamically load extensions into
75706 ** the SQLite library.
75707 */
75708
75709 #ifndef SQLITE_CORE
75710   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
75711 #endif
75712 /************** Include sqlite3ext.h in the middle of loadext.c **************/
75713 /************** Begin file sqlite3ext.h **************************************/
75714 /*
75715 ** 2006 June 7
75716 **
75717 ** The author disclaims copyright to this source code.  In place of
75718 ** a legal notice, here is a blessing:
75719 **
75720 **    May you do good and not evil.
75721 **    May you find forgiveness for yourself and forgive others.
75722 **    May you share freely, never taking more than you give.
75723 **
75724 *************************************************************************
75725 ** This header file defines the SQLite interface for use by
75726 ** shared libraries that want to be imported as extensions into
75727 ** an SQLite instance.  Shared libraries that intend to be loaded
75728 ** as extensions by SQLite should #include this file instead of 
75729 ** sqlite3.h.
75730 */
75731 #ifndef _SQLITE3EXT_H_
75732 #define _SQLITE3EXT_H_
75733
75734 typedef struct sqlite3_api_routines sqlite3_api_routines;
75735
75736 /*
75737 ** The following structure holds pointers to all of the SQLite API
75738 ** routines.
75739 **
75740 ** WARNING:  In order to maintain backwards compatibility, add new
75741 ** interfaces to the end of this structure only.  If you insert new
75742 ** interfaces in the middle of this structure, then older different
75743 ** versions of SQLite will not be able to load each others' shared
75744 ** libraries!
75745 */
75746 struct sqlite3_api_routines {
75747   void * (*aggregate_context)(sqlite3_context*,int nBytes);
75748   int  (*aggregate_count)(sqlite3_context*);
75749   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
75750   int  (*bind_double)(sqlite3_stmt*,int,double);
75751   int  (*bind_int)(sqlite3_stmt*,int,int);
75752   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
75753   int  (*bind_null)(sqlite3_stmt*,int);
75754   int  (*bind_parameter_count)(sqlite3_stmt*);
75755   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
75756   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
75757   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
75758   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
75759   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
75760   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
75761   int  (*busy_timeout)(sqlite3*,int ms);
75762   int  (*changes)(sqlite3*);
75763   int  (*close)(sqlite3*);
75764   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
75765   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
75766   const void * (*column_blob)(sqlite3_stmt*,int iCol);
75767   int  (*column_bytes)(sqlite3_stmt*,int iCol);
75768   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
75769   int  (*column_count)(sqlite3_stmt*pStmt);
75770   const char * (*column_database_name)(sqlite3_stmt*,int);
75771   const void * (*column_database_name16)(sqlite3_stmt*,int);
75772   const char * (*column_decltype)(sqlite3_stmt*,int i);
75773   const void * (*column_decltype16)(sqlite3_stmt*,int);
75774   double  (*column_double)(sqlite3_stmt*,int iCol);
75775   int  (*column_int)(sqlite3_stmt*,int iCol);
75776   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
75777   const char * (*column_name)(sqlite3_stmt*,int);
75778   const void * (*column_name16)(sqlite3_stmt*,int);
75779   const char * (*column_origin_name)(sqlite3_stmt*,int);
75780   const void * (*column_origin_name16)(sqlite3_stmt*,int);
75781   const char * (*column_table_name)(sqlite3_stmt*,int);
75782   const void * (*column_table_name16)(sqlite3_stmt*,int);
75783   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
75784   const void * (*column_text16)(sqlite3_stmt*,int iCol);
75785   int  (*column_type)(sqlite3_stmt*,int iCol);
75786   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
75787   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
75788   int  (*complete)(const char*sql);
75789   int  (*complete16)(const void*sql);
75790   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
75791   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
75792   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*));
75793   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*));
75794   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
75795   int  (*data_count)(sqlite3_stmt*pStmt);
75796   sqlite3 * (*db_handle)(sqlite3_stmt*);
75797   int (*declare_vtab)(sqlite3*,const char*);
75798   int  (*enable_shared_cache)(int);
75799   int  (*errcode)(sqlite3*db);
75800   const char * (*errmsg)(sqlite3*);
75801   const void * (*errmsg16)(sqlite3*);
75802   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
75803   int  (*expired)(sqlite3_stmt*);
75804   int  (*finalize)(sqlite3_stmt*pStmt);
75805   void  (*free)(void*);
75806   void  (*free_table)(char**result);
75807   int  (*get_autocommit)(sqlite3*);
75808   void * (*get_auxdata)(sqlite3_context*,int);
75809   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
75810   int  (*global_recover)(void);
75811   void  (*interruptx)(sqlite3*);
75812   sqlite_int64  (*last_insert_rowid)(sqlite3*);
75813   const char * (*libversion)(void);
75814   int  (*libversion_number)(void);
75815   void *(*malloc)(int);
75816   char * (*mprintf)(const char*,...);
75817   int  (*open)(const char*,sqlite3**);
75818   int  (*open16)(const void*,sqlite3**);
75819   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
75820   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
75821   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
75822   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
75823   void *(*realloc)(void*,int);
75824   int  (*reset)(sqlite3_stmt*pStmt);
75825   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
75826   void  (*result_double)(sqlite3_context*,double);
75827   void  (*result_error)(sqlite3_context*,const char*,int);
75828   void  (*result_error16)(sqlite3_context*,const void*,int);
75829   void  (*result_int)(sqlite3_context*,int);
75830   void  (*result_int64)(sqlite3_context*,sqlite_int64);
75831   void  (*result_null)(sqlite3_context*);
75832   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
75833   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
75834   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
75835   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
75836   void  (*result_value)(sqlite3_context*,sqlite3_value*);
75837   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
75838   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
75839   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
75840   char * (*snprintf)(int,char*,const char*,...);
75841   int  (*step)(sqlite3_stmt*);
75842   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
75843   void  (*thread_cleanup)(void);
75844   int  (*total_changes)(sqlite3*);
75845   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
75846   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
75847   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
75848   void * (*user_data)(sqlite3_context*);
75849   const void * (*value_blob)(sqlite3_value*);
75850   int  (*value_bytes)(sqlite3_value*);
75851   int  (*value_bytes16)(sqlite3_value*);
75852   double  (*value_double)(sqlite3_value*);
75853   int  (*value_int)(sqlite3_value*);
75854   sqlite_int64  (*value_int64)(sqlite3_value*);
75855   int  (*value_numeric_type)(sqlite3_value*);
75856   const unsigned char * (*value_text)(sqlite3_value*);
75857   const void * (*value_text16)(sqlite3_value*);
75858   const void * (*value_text16be)(sqlite3_value*);
75859   const void * (*value_text16le)(sqlite3_value*);
75860   int  (*value_type)(sqlite3_value*);
75861   char *(*vmprintf)(const char*,va_list);
75862   /* Added ??? */
75863   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
75864   /* Added by 3.3.13 */
75865   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
75866   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
75867   int (*clear_bindings)(sqlite3_stmt*);
75868   /* Added by 3.4.1 */
75869   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
75870   /* Added by 3.5.0 */
75871   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
75872   int (*blob_bytes)(sqlite3_blob*);
75873   int (*blob_close)(sqlite3_blob*);
75874   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
75875   int (*blob_read)(sqlite3_blob*,void*,int,int);
75876   int (*blob_write)(sqlite3_blob*,const void*,int,int);
75877   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
75878   int (*file_control)(sqlite3*,const char*,int,void*);
75879   sqlite3_int64 (*memory_highwater)(int);
75880   sqlite3_int64 (*memory_used)(void);
75881   sqlite3_mutex *(*mutex_alloc)(int);
75882   void (*mutex_enter)(sqlite3_mutex*);
75883   void (*mutex_free)(sqlite3_mutex*);
75884   void (*mutex_leave)(sqlite3_mutex*);
75885   int (*mutex_try)(sqlite3_mutex*);
75886   int (*open_v2)(const char*,sqlite3**,int,const char*);
75887   int (*release_memory)(int);
75888   void (*result_error_nomem)(sqlite3_context*);
75889   void (*result_error_toobig)(sqlite3_context*);
75890   int (*sleep)(int);
75891   void (*soft_heap_limit)(int);
75892   sqlite3_vfs *(*vfs_find)(const char*);
75893   int (*vfs_register)(sqlite3_vfs*,int);
75894   int (*vfs_unregister)(sqlite3_vfs*);
75895   int (*xthreadsafe)(void);
75896   void (*result_zeroblob)(sqlite3_context*,int);
75897   void (*result_error_code)(sqlite3_context*,int);
75898   int (*test_control)(int, ...);
75899   void (*randomness)(int,void*);
75900   sqlite3 *(*context_db_handle)(sqlite3_context*);
75901   int (*extended_result_codes)(sqlite3*,int);
75902   int (*limit)(sqlite3*,int,int);
75903   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
75904   const char *(*sql)(sqlite3_stmt*);
75905   int (*status)(int,int*,int*,int);
75906 };
75907
75908 /*
75909 ** The following macros redefine the API routines so that they are
75910 ** redirected throught the global sqlite3_api structure.
75911 **
75912 ** This header file is also used by the loadext.c source file
75913 ** (part of the main SQLite library - not an extension) so that
75914 ** it can get access to the sqlite3_api_routines structure
75915 ** definition.  But the main library does not want to redefine
75916 ** the API.  So the redefinition macros are only valid if the
75917 ** SQLITE_CORE macros is undefined.
75918 */
75919 #ifndef SQLITE_CORE
75920 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
75921 #ifndef SQLITE_OMIT_DEPRECATED
75922 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
75923 #endif
75924 #define sqlite3_bind_blob              sqlite3_api->bind_blob
75925 #define sqlite3_bind_double            sqlite3_api->bind_double
75926 #define sqlite3_bind_int               sqlite3_api->bind_int
75927 #define sqlite3_bind_int64             sqlite3_api->bind_int64
75928 #define sqlite3_bind_null              sqlite3_api->bind_null
75929 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
75930 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
75931 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
75932 #define sqlite3_bind_text              sqlite3_api->bind_text
75933 #define sqlite3_bind_text16            sqlite3_api->bind_text16
75934 #define sqlite3_bind_value             sqlite3_api->bind_value
75935 #define sqlite3_busy_handler           sqlite3_api->busy_handler
75936 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
75937 #define sqlite3_changes                sqlite3_api->changes
75938 #define sqlite3_close                  sqlite3_api->close
75939 #define sqlite3_collation_needed       sqlite3_api->collation_needed
75940 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
75941 #define sqlite3_column_blob            sqlite3_api->column_blob
75942 #define sqlite3_column_bytes           sqlite3_api->column_bytes
75943 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
75944 #define sqlite3_column_count           sqlite3_api->column_count
75945 #define sqlite3_column_database_name   sqlite3_api->column_database_name
75946 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
75947 #define sqlite3_column_decltype        sqlite3_api->column_decltype
75948 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
75949 #define sqlite3_column_double          sqlite3_api->column_double
75950 #define sqlite3_column_int             sqlite3_api->column_int
75951 #define sqlite3_column_int64           sqlite3_api->column_int64
75952 #define sqlite3_column_name            sqlite3_api->column_name
75953 #define sqlite3_column_name16          sqlite3_api->column_name16
75954 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
75955 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
75956 #define sqlite3_column_table_name      sqlite3_api->column_table_name
75957 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
75958 #define sqlite3_column_text            sqlite3_api->column_text
75959 #define sqlite3_column_text16          sqlite3_api->column_text16
75960 #define sqlite3_column_type            sqlite3_api->column_type
75961 #define sqlite3_column_value           sqlite3_api->column_value
75962 #define sqlite3_commit_hook            sqlite3_api->commit_hook
75963 #define sqlite3_complete               sqlite3_api->complete
75964 #define sqlite3_complete16             sqlite3_api->complete16
75965 #define sqlite3_create_collation       sqlite3_api->create_collation
75966 #define sqlite3_create_collation16     sqlite3_api->create_collation16
75967 #define sqlite3_create_function        sqlite3_api->create_function
75968 #define sqlite3_create_function16      sqlite3_api->create_function16
75969 #define sqlite3_create_module          sqlite3_api->create_module
75970 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
75971 #define sqlite3_data_count             sqlite3_api->data_count
75972 #define sqlite3_db_handle              sqlite3_api->db_handle
75973 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
75974 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
75975 #define sqlite3_errcode                sqlite3_api->errcode
75976 #define sqlite3_errmsg                 sqlite3_api->errmsg
75977 #define sqlite3_errmsg16               sqlite3_api->errmsg16
75978 #define sqlite3_exec                   sqlite3_api->exec
75979 #ifndef SQLITE_OMIT_DEPRECATED
75980 #define sqlite3_expired                sqlite3_api->expired
75981 #endif
75982 #define sqlite3_finalize               sqlite3_api->finalize
75983 #define sqlite3_free                   sqlite3_api->free
75984 #define sqlite3_free_table             sqlite3_api->free_table
75985 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
75986 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
75987 #define sqlite3_get_table              sqlite3_api->get_table
75988 #ifndef SQLITE_OMIT_DEPRECATED
75989 #define sqlite3_global_recover         sqlite3_api->global_recover
75990 #endif
75991 #define sqlite3_interrupt              sqlite3_api->interruptx
75992 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
75993 #define sqlite3_libversion             sqlite3_api->libversion
75994 #define sqlite3_libversion_number      sqlite3_api->libversion_number
75995 #define sqlite3_malloc                 sqlite3_api->malloc
75996 #define sqlite3_mprintf                sqlite3_api->mprintf
75997 #define sqlite3_open                   sqlite3_api->open
75998 #define sqlite3_open16                 sqlite3_api->open16
75999 #define sqlite3_prepare                sqlite3_api->prepare
76000 #define sqlite3_prepare16              sqlite3_api->prepare16
76001 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
76002 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
76003 #define sqlite3_profile                sqlite3_api->profile
76004 #define sqlite3_progress_handler       sqlite3_api->progress_handler
76005 #define sqlite3_realloc                sqlite3_api->realloc
76006 #define sqlite3_reset                  sqlite3_api->reset
76007 #define sqlite3_result_blob            sqlite3_api->result_blob
76008 #define sqlite3_result_double          sqlite3_api->result_double
76009 #define sqlite3_result_error           sqlite3_api->result_error
76010 #define sqlite3_result_error16         sqlite3_api->result_error16
76011 #define sqlite3_result_int             sqlite3_api->result_int
76012 #define sqlite3_result_int64           sqlite3_api->result_int64
76013 #define sqlite3_result_null            sqlite3_api->result_null
76014 #define sqlite3_result_text            sqlite3_api->result_text
76015 #define sqlite3_result_text16          sqlite3_api->result_text16
76016 #define sqlite3_result_text16be        sqlite3_api->result_text16be
76017 #define sqlite3_result_text16le        sqlite3_api->result_text16le
76018 #define sqlite3_result_value           sqlite3_api->result_value
76019 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
76020 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
76021 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
76022 #define sqlite3_snprintf               sqlite3_api->snprintf
76023 #define sqlite3_step                   sqlite3_api->step
76024 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
76025 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
76026 #define sqlite3_total_changes          sqlite3_api->total_changes
76027 #define sqlite3_trace                  sqlite3_api->trace
76028 #ifndef SQLITE_OMIT_DEPRECATED
76029 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
76030 #endif
76031 #define sqlite3_update_hook            sqlite3_api->update_hook
76032 #define sqlite3_user_data              sqlite3_api->user_data
76033 #define sqlite3_value_blob             sqlite3_api->value_blob
76034 #define sqlite3_value_bytes            sqlite3_api->value_bytes
76035 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
76036 #define sqlite3_value_double           sqlite3_api->value_double
76037 #define sqlite3_value_int              sqlite3_api->value_int
76038 #define sqlite3_value_int64            sqlite3_api->value_int64
76039 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
76040 #define sqlite3_value_text             sqlite3_api->value_text
76041 #define sqlite3_value_text16           sqlite3_api->value_text16
76042 #define sqlite3_value_text16be         sqlite3_api->value_text16be
76043 #define sqlite3_value_text16le         sqlite3_api->value_text16le
76044 #define sqlite3_value_type             sqlite3_api->value_type
76045 #define sqlite3_vmprintf               sqlite3_api->vmprintf
76046 #define sqlite3_overload_function      sqlite3_api->overload_function
76047 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
76048 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
76049 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
76050 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
76051 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
76052 #define sqlite3_blob_close             sqlite3_api->blob_close
76053 #define sqlite3_blob_open              sqlite3_api->blob_open
76054 #define sqlite3_blob_read              sqlite3_api->blob_read
76055 #define sqlite3_blob_write             sqlite3_api->blob_write
76056 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
76057 #define sqlite3_file_control           sqlite3_api->file_control
76058 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
76059 #define sqlite3_memory_used            sqlite3_api->memory_used
76060 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
76061 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
76062 #define sqlite3_mutex_free             sqlite3_api->mutex_free
76063 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
76064 #define sqlite3_mutex_try              sqlite3_api->mutex_try
76065 #define sqlite3_open_v2                sqlite3_api->open_v2
76066 #define sqlite3_release_memory         sqlite3_api->release_memory
76067 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
76068 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
76069 #define sqlite3_sleep                  sqlite3_api->sleep
76070 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
76071 #define sqlite3_vfs_find               sqlite3_api->vfs_find
76072 #define sqlite3_vfs_register           sqlite3_api->vfs_register
76073 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
76074 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
76075 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
76076 #define sqlite3_result_error_code      sqlite3_api->result_error_code
76077 #define sqlite3_test_control           sqlite3_api->test_control
76078 #define sqlite3_randomness             sqlite3_api->randomness
76079 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
76080 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
76081 #define sqlite3_limit                  sqlite3_api->limit
76082 #define sqlite3_next_stmt              sqlite3_api->next_stmt
76083 #define sqlite3_sql                    sqlite3_api->sql
76084 #define sqlite3_status                 sqlite3_api->status
76085 #endif /* SQLITE_CORE */
76086
76087 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
76088 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
76089
76090 #endif /* _SQLITE3EXT_H_ */
76091
76092 /************** End of sqlite3ext.h ******************************************/
76093 /************** Continuing where we left off in loadext.c ********************/
76094
76095 #ifndef SQLITE_OMIT_LOAD_EXTENSION
76096
76097 /*
76098 ** Some API routines are omitted when various features are
76099 ** excluded from a build of SQLite.  Substitute a NULL pointer
76100 ** for any missing APIs.
76101 */
76102 #ifndef SQLITE_ENABLE_COLUMN_METADATA
76103 # define sqlite3_column_database_name   0
76104 # define sqlite3_column_database_name16 0
76105 # define sqlite3_column_table_name      0
76106 # define sqlite3_column_table_name16    0
76107 # define sqlite3_column_origin_name     0
76108 # define sqlite3_column_origin_name16   0
76109 # define sqlite3_table_column_metadata  0
76110 #endif
76111
76112 #ifdef SQLITE_OMIT_AUTHORIZATION
76113 # define sqlite3_set_authorizer         0
76114 #endif
76115
76116 #ifdef SQLITE_OMIT_UTF16
76117 # define sqlite3_bind_text16            0
76118 # define sqlite3_collation_needed16     0
76119 # define sqlite3_column_decltype16      0
76120 # define sqlite3_column_name16          0
76121 # define sqlite3_column_text16          0
76122 # define sqlite3_complete16             0
76123 # define sqlite3_create_collation16     0
76124 # define sqlite3_create_function16      0
76125 # define sqlite3_errmsg16               0
76126 # define sqlite3_open16                 0
76127 # define sqlite3_prepare16              0
76128 # define sqlite3_prepare16_v2           0
76129 # define sqlite3_result_error16         0
76130 # define sqlite3_result_text16          0
76131 # define sqlite3_result_text16be        0
76132 # define sqlite3_result_text16le        0
76133 # define sqlite3_value_text16           0
76134 # define sqlite3_value_text16be         0
76135 # define sqlite3_value_text16le         0
76136 # define sqlite3_column_database_name16 0
76137 # define sqlite3_column_table_name16    0
76138 # define sqlite3_column_origin_name16   0
76139 #endif
76140
76141 #ifdef SQLITE_OMIT_COMPLETE
76142 # define sqlite3_complete 0
76143 # define sqlite3_complete16 0
76144 #endif
76145
76146 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
76147 # define sqlite3_progress_handler 0
76148 #endif
76149
76150 #ifdef SQLITE_OMIT_VIRTUALTABLE
76151 # define sqlite3_create_module 0
76152 # define sqlite3_create_module_v2 0
76153 # define sqlite3_declare_vtab 0
76154 #endif
76155
76156 #ifdef SQLITE_OMIT_SHARED_CACHE
76157 # define sqlite3_enable_shared_cache 0
76158 #endif
76159
76160 #ifdef SQLITE_OMIT_TRACE
76161 # define sqlite3_profile       0
76162 # define sqlite3_trace         0
76163 #endif
76164
76165 #ifdef SQLITE_OMIT_GET_TABLE
76166 # define sqlite3_free_table    0
76167 # define sqlite3_get_table     0
76168 #endif
76169
76170 #ifdef SQLITE_OMIT_INCRBLOB
76171 #define sqlite3_bind_zeroblob  0
76172 #define sqlite3_blob_bytes     0
76173 #define sqlite3_blob_close     0
76174 #define sqlite3_blob_open      0
76175 #define sqlite3_blob_read      0
76176 #define sqlite3_blob_write     0
76177 #endif
76178
76179 /*
76180 ** The following structure contains pointers to all SQLite API routines.
76181 ** A pointer to this structure is passed into extensions when they are
76182 ** loaded so that the extension can make calls back into the SQLite
76183 ** library.
76184 **
76185 ** When adding new APIs, add them to the bottom of this structure
76186 ** in order to preserve backwards compatibility.
76187 **
76188 ** Extensions that use newer APIs should first call the
76189 ** sqlite3_libversion_number() to make sure that the API they
76190 ** intend to use is supported by the library.  Extensions should
76191 ** also check to make sure that the pointer to the function is
76192 ** not NULL before calling it.
76193 */
76194 static const sqlite3_api_routines sqlite3Apis = {
76195   sqlite3_aggregate_context,
76196 #ifndef SQLITE_OMIT_DEPRECATED
76197   sqlite3_aggregate_count,
76198 #else
76199   0,
76200 #endif
76201   sqlite3_bind_blob,
76202   sqlite3_bind_double,
76203   sqlite3_bind_int,
76204   sqlite3_bind_int64,
76205   sqlite3_bind_null,
76206   sqlite3_bind_parameter_count,
76207   sqlite3_bind_parameter_index,
76208   sqlite3_bind_parameter_name,
76209   sqlite3_bind_text,
76210   sqlite3_bind_text16,
76211   sqlite3_bind_value,
76212   sqlite3_busy_handler,
76213   sqlite3_busy_timeout,
76214   sqlite3_changes,
76215   sqlite3_close,
76216   sqlite3_collation_needed,
76217   sqlite3_collation_needed16,
76218   sqlite3_column_blob,
76219   sqlite3_column_bytes,
76220   sqlite3_column_bytes16,
76221   sqlite3_column_count,
76222   sqlite3_column_database_name,
76223   sqlite3_column_database_name16,
76224   sqlite3_column_decltype,
76225   sqlite3_column_decltype16,
76226   sqlite3_column_double,
76227   sqlite3_column_int,
76228   sqlite3_column_int64,
76229   sqlite3_column_name,
76230   sqlite3_column_name16,
76231   sqlite3_column_origin_name,
76232   sqlite3_column_origin_name16,
76233   sqlite3_column_table_name,
76234   sqlite3_column_table_name16,
76235   sqlite3_column_text,
76236   sqlite3_column_text16,
76237   sqlite3_column_type,
76238   sqlite3_column_value,
76239   sqlite3_commit_hook,
76240   sqlite3_complete,
76241   sqlite3_complete16,
76242   sqlite3_create_collation,
76243   sqlite3_create_collation16,
76244   sqlite3_create_function,
76245   sqlite3_create_function16,
76246   sqlite3_create_module,
76247   sqlite3_data_count,
76248   sqlite3_db_handle,
76249   sqlite3_declare_vtab,
76250   sqlite3_enable_shared_cache,
76251   sqlite3_errcode,
76252   sqlite3_errmsg,
76253   sqlite3_errmsg16,
76254   sqlite3_exec,
76255 #ifndef SQLITE_OMIT_DEPRECATED
76256   sqlite3_expired,
76257 #else
76258   0,
76259 #endif
76260   sqlite3_finalize,
76261   sqlite3_free,
76262   sqlite3_free_table,
76263   sqlite3_get_autocommit,
76264   sqlite3_get_auxdata,
76265   sqlite3_get_table,
76266   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
76267   sqlite3_interrupt,
76268   sqlite3_last_insert_rowid,
76269   sqlite3_libversion,
76270   sqlite3_libversion_number,
76271   sqlite3_malloc,
76272   sqlite3_mprintf,
76273   sqlite3_open,
76274   sqlite3_open16,
76275   sqlite3_prepare,
76276   sqlite3_prepare16,
76277   sqlite3_profile,
76278   sqlite3_progress_handler,
76279   sqlite3_realloc,
76280   sqlite3_reset,
76281   sqlite3_result_blob,
76282   sqlite3_result_double,
76283   sqlite3_result_error,
76284   sqlite3_result_error16,
76285   sqlite3_result_int,
76286   sqlite3_result_int64,
76287   sqlite3_result_null,
76288   sqlite3_result_text,
76289   sqlite3_result_text16,
76290   sqlite3_result_text16be,
76291   sqlite3_result_text16le,
76292   sqlite3_result_value,
76293   sqlite3_rollback_hook,
76294   sqlite3_set_authorizer,
76295   sqlite3_set_auxdata,
76296   sqlite3_snprintf,
76297   sqlite3_step,
76298   sqlite3_table_column_metadata,
76299 #ifndef SQLITE_OMIT_DEPRECATED
76300   sqlite3_thread_cleanup,
76301 #else
76302   0,
76303 #endif
76304   sqlite3_total_changes,
76305   sqlite3_trace,
76306 #ifndef SQLITE_OMIT_DEPRECATED
76307   sqlite3_transfer_bindings,
76308 #else
76309   0,
76310 #endif
76311   sqlite3_update_hook,
76312   sqlite3_user_data,
76313   sqlite3_value_blob,
76314   sqlite3_value_bytes,
76315   sqlite3_value_bytes16,
76316   sqlite3_value_double,
76317   sqlite3_value_int,
76318   sqlite3_value_int64,
76319   sqlite3_value_numeric_type,
76320   sqlite3_value_text,
76321   sqlite3_value_text16,
76322   sqlite3_value_text16be,
76323   sqlite3_value_text16le,
76324   sqlite3_value_type,
76325   sqlite3_vmprintf,
76326   /*
76327   ** The original API set ends here.  All extensions can call any
76328   ** of the APIs above provided that the pointer is not NULL.  But
76329   ** before calling APIs that follow, extension should check the
76330   ** sqlite3_libversion_number() to make sure they are dealing with
76331   ** a library that is new enough to support that API.
76332   *************************************************************************
76333   */
76334   sqlite3_overload_function,
76335
76336   /*
76337   ** Added after 3.3.13
76338   */
76339   sqlite3_prepare_v2,
76340   sqlite3_prepare16_v2,
76341   sqlite3_clear_bindings,
76342
76343   /*
76344   ** Added for 3.4.1
76345   */
76346   sqlite3_create_module_v2,
76347
76348   /*
76349   ** Added for 3.5.0
76350   */
76351   sqlite3_bind_zeroblob,
76352   sqlite3_blob_bytes,
76353   sqlite3_blob_close,
76354   sqlite3_blob_open,
76355   sqlite3_blob_read,
76356   sqlite3_blob_write,
76357   sqlite3_create_collation_v2,
76358   sqlite3_file_control,
76359   sqlite3_memory_highwater,
76360   sqlite3_memory_used,
76361 #ifdef SQLITE_MUTEX_OMIT
76362   0, 
76363   0, 
76364   0,
76365   0,
76366   0,
76367 #else
76368   sqlite3_mutex_alloc,
76369   sqlite3_mutex_enter,
76370   sqlite3_mutex_free,
76371   sqlite3_mutex_leave,
76372   sqlite3_mutex_try,
76373 #endif
76374   sqlite3_open_v2,
76375   sqlite3_release_memory,
76376   sqlite3_result_error_nomem,
76377   sqlite3_result_error_toobig,
76378   sqlite3_sleep,
76379   sqlite3_soft_heap_limit,
76380   sqlite3_vfs_find,
76381   sqlite3_vfs_register,
76382   sqlite3_vfs_unregister,
76383
76384   /*
76385   ** Added for 3.5.8
76386   */
76387   sqlite3_threadsafe,
76388   sqlite3_result_zeroblob,
76389   sqlite3_result_error_code,
76390   sqlite3_test_control,
76391   sqlite3_randomness,
76392   sqlite3_context_db_handle,
76393
76394   /*
76395   ** Added for 3.6.0
76396   */
76397   sqlite3_extended_result_codes,
76398   sqlite3_limit,
76399   sqlite3_next_stmt,
76400   sqlite3_sql,
76401   sqlite3_status,
76402 };
76403
76404 /*
76405 ** Attempt to load an SQLite extension library contained in the file
76406 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
76407 ** default entry point name (sqlite3_extension_init) is used.  Use
76408 ** of the default name is recommended.
76409 **
76410 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
76411 **
76412 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
76413 ** error message text.  The calling function should free this memory
76414 ** by calling sqlite3DbFree(db, ).
76415 */
76416 static int sqlite3LoadExtension(
76417   sqlite3 *db,          /* Load the extension into this database connection */
76418   const char *zFile,    /* Name of the shared library containing extension */
76419   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
76420   char **pzErrMsg       /* Put error message here if not 0 */
76421 ){
76422   sqlite3_vfs *pVfs = db->pVfs;
76423   void *handle;
76424   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
76425   char *zErrmsg = 0;
76426   void **aHandle;
76427   const int nMsg = 300;
76428
76429   if( pzErrMsg ) *pzErrMsg = 0;
76430
76431   /* Ticket #1863.  To avoid a creating security problems for older
76432   ** applications that relink against newer versions of SQLite, the
76433   ** ability to run load_extension is turned off by default.  One
76434   ** must call sqlite3_enable_load_extension() to turn on extension
76435   ** loading.  Otherwise you get the following error.
76436   */
76437   if( (db->flags & SQLITE_LoadExtension)==0 ){
76438     if( pzErrMsg ){
76439       *pzErrMsg = sqlite3_mprintf("not authorized");
76440     }
76441     return SQLITE_ERROR;
76442   }
76443
76444   if( zProc==0 ){
76445     zProc = "sqlite3_extension_init";
76446   }
76447
76448   handle = sqlite3OsDlOpen(pVfs, zFile);
76449   if( handle==0 ){
76450     if( pzErrMsg ){
76451       zErrmsg = sqlite3StackAllocZero(db, nMsg);
76452       if( zErrmsg ){
76453         sqlite3_snprintf(nMsg, zErrmsg, 
76454             "unable to open shared library [%s]", zFile);
76455         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
76456         *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
76457         sqlite3StackFree(db, zErrmsg);
76458       }
76459     }
76460     return SQLITE_ERROR;
76461   }
76462   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
76463                    sqlite3OsDlSym(pVfs, handle, zProc);
76464   if( xInit==0 ){
76465     if( pzErrMsg ){
76466       zErrmsg = sqlite3StackAllocZero(db, nMsg);
76467       if( zErrmsg ){
76468         sqlite3_snprintf(nMsg, zErrmsg,
76469             "no entry point [%s] in shared library [%s]", zProc,zFile);
76470         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
76471         *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
76472         sqlite3StackFree(db, zErrmsg);
76473       }
76474       sqlite3OsDlClose(pVfs, handle);
76475     }
76476     return SQLITE_ERROR;
76477   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
76478     if( pzErrMsg ){
76479       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
76480     }
76481     sqlite3_free(zErrmsg);
76482     sqlite3OsDlClose(pVfs, handle);
76483     return SQLITE_ERROR;
76484   }
76485
76486   /* Append the new shared library handle to the db->aExtension array. */
76487   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
76488   if( aHandle==0 ){
76489     return SQLITE_NOMEM;
76490   }
76491   if( db->nExtension>0 ){
76492     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
76493   }
76494   sqlite3DbFree(db, db->aExtension);
76495   db->aExtension = aHandle;
76496
76497   db->aExtension[db->nExtension++] = handle;
76498   return SQLITE_OK;
76499 }
76500 SQLITE_API int sqlite3_load_extension(
76501   sqlite3 *db,          /* Load the extension into this database connection */
76502   const char *zFile,    /* Name of the shared library containing extension */
76503   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
76504   char **pzErrMsg       /* Put error message here if not 0 */
76505 ){
76506   int rc;
76507   sqlite3_mutex_enter(db->mutex);
76508   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
76509   rc = sqlite3ApiExit(db, rc);
76510   sqlite3_mutex_leave(db->mutex);
76511   return rc;
76512 }
76513
76514 /*
76515 ** Call this routine when the database connection is closing in order
76516 ** to clean up loaded extensions
76517 */
76518 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
76519   int i;
76520   assert( sqlite3_mutex_held(db->mutex) );
76521   for(i=0; i<db->nExtension; i++){
76522     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
76523   }
76524   sqlite3DbFree(db, db->aExtension);
76525 }
76526
76527 /*
76528 ** Enable or disable extension loading.  Extension loading is disabled by
76529 ** default so as not to open security holes in older applications.
76530 */
76531 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
76532   sqlite3_mutex_enter(db->mutex);
76533   if( onoff ){
76534     db->flags |= SQLITE_LoadExtension;
76535   }else{
76536     db->flags &= ~SQLITE_LoadExtension;
76537   }
76538   sqlite3_mutex_leave(db->mutex);
76539   return SQLITE_OK;
76540 }
76541
76542 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
76543
76544 /*
76545 ** The auto-extension code added regardless of whether or not extension
76546 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
76547 ** code if regular extension loading is not available.  This is that
76548 ** dummy pointer.
76549 */
76550 #ifdef SQLITE_OMIT_LOAD_EXTENSION
76551 static const sqlite3_api_routines sqlite3Apis = { 0 };
76552 #endif
76553
76554
76555 /*
76556 ** The following object holds the list of automatically loaded
76557 ** extensions.
76558 **
76559 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
76560 ** mutex must be held while accessing this list.
76561 */
76562 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
76563 static SQLITE_WSD struct sqlite3AutoExtList {
76564   int nExt;              /* Number of entries in aExt[] */          
76565   void (**aExt)(void);   /* Pointers to the extension init functions */
76566 } sqlite3Autoext = { 0, 0 };
76567
76568 /* The "wsdAutoext" macro will resolve to the autoextension
76569 ** state vector.  If writable static data is unsupported on the target,
76570 ** we have to locate the state vector at run-time.  In the more common
76571 ** case where writable static data is supported, wsdStat can refer directly
76572 ** to the "sqlite3Autoext" state vector declared above.
76573 */
76574 #ifdef SQLITE_OMIT_WSD
76575 # define wsdAutoextInit \
76576   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
76577 # define wsdAutoext x[0]
76578 #else
76579 # define wsdAutoextInit
76580 # define wsdAutoext sqlite3Autoext
76581 #endif
76582
76583
76584 /*
76585 ** Register a statically linked extension that is automatically
76586 ** loaded by every new database connection.
76587 */
76588 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
76589   int rc = SQLITE_OK;
76590 #ifndef SQLITE_OMIT_AUTOINIT
76591   rc = sqlite3_initialize();
76592   if( rc ){
76593     return rc;
76594   }else
76595 #endif
76596   {
76597     int i;
76598 #if SQLITE_THREADSAFE
76599     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
76600 #endif
76601     wsdAutoextInit;
76602     sqlite3_mutex_enter(mutex);
76603     for(i=0; i<wsdAutoext.nExt; i++){
76604       if( wsdAutoext.aExt[i]==xInit ) break;
76605     }
76606     if( i==wsdAutoext.nExt ){
76607       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
76608       void (**aNew)(void);
76609       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
76610       if( aNew==0 ){
76611         rc = SQLITE_NOMEM;
76612       }else{
76613         wsdAutoext.aExt = aNew;
76614         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
76615         wsdAutoext.nExt++;
76616       }
76617     }
76618     sqlite3_mutex_leave(mutex);
76619     assert( (rc&0xff)==rc );
76620     return rc;
76621   }
76622 }
76623
76624 /*
76625 ** Reset the automatic extension loading mechanism.
76626 */
76627 SQLITE_API void sqlite3_reset_auto_extension(void){
76628 #ifndef SQLITE_OMIT_AUTOINIT
76629   if( sqlite3_initialize()==SQLITE_OK )
76630 #endif
76631   {
76632 #if SQLITE_THREADSAFE
76633     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
76634 #endif
76635     wsdAutoextInit;
76636     sqlite3_mutex_enter(mutex);
76637     sqlite3_free(wsdAutoext.aExt);
76638     wsdAutoext.aExt = 0;
76639     wsdAutoext.nExt = 0;
76640     sqlite3_mutex_leave(mutex);
76641   }
76642 }
76643
76644 /*
76645 ** Load all automatic extensions.
76646 **
76647 ** If anything goes wrong, set an error in the database connection.
76648 */
76649 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
76650   int i;
76651   int go = 1;
76652   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
76653
76654   wsdAutoextInit;
76655   if( wsdAutoext.nExt==0 ){
76656     /* Common case: early out without every having to acquire a mutex */
76657     return;
76658   }
76659   for(i=0; go; i++){
76660     char *zErrmsg;
76661 #if SQLITE_THREADSAFE
76662     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
76663 #endif
76664     sqlite3_mutex_enter(mutex);
76665     if( i>=wsdAutoext.nExt ){
76666       xInit = 0;
76667       go = 0;
76668     }else{
76669       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
76670               wsdAutoext.aExt[i];
76671     }
76672     sqlite3_mutex_leave(mutex);
76673     zErrmsg = 0;
76674     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
76675       sqlite3Error(db, SQLITE_ERROR,
76676             "automatic extension loading failed: %s", zErrmsg);
76677       go = 0;
76678     }
76679     sqlite3_free(zErrmsg);
76680   }
76681 }
76682
76683 /************** End of loadext.c *********************************************/
76684 /************** Begin file pragma.c ******************************************/
76685 /*
76686 ** 2003 April 6
76687 **
76688 ** The author disclaims copyright to this source code.  In place of
76689 ** a legal notice, here is a blessing:
76690 **
76691 **    May you do good and not evil.
76692 **    May you find forgiveness for yourself and forgive others.
76693 **    May you share freely, never taking more than you give.
76694 **
76695 *************************************************************************
76696 ** This file contains code used to implement the PRAGMA command.
76697 */
76698
76699 /* Ignore this whole file if pragmas are disabled
76700 */
76701 #if !defined(SQLITE_OMIT_PRAGMA)
76702
76703 /*
76704 ** Interpret the given string as a safety level.  Return 0 for OFF,
76705 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
76706 ** unrecognized string argument.
76707 **
76708 ** Note that the values returned are one less that the values that
76709 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
76710 ** to support legacy SQL code.  The safety level used to be boolean
76711 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
76712 */
76713 static u8 getSafetyLevel(const char *z){
76714                              /* 123456789 123456789 */
76715   static const char zText[] = "onoffalseyestruefull";
76716   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
76717   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
76718   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
76719   int i, n;
76720   if( sqlite3Isdigit(*z) ){
76721     return (u8)atoi(z);
76722   }
76723   n = sqlite3Strlen30(z);
76724   for(i=0; i<ArraySize(iLength); i++){
76725     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
76726       return iValue[i];
76727     }
76728   }
76729   return 1;
76730 }
76731
76732 /*
76733 ** Interpret the given string as a boolean value.
76734 */
76735 static u8 getBoolean(const char *z){
76736   return getSafetyLevel(z)&1;
76737 }
76738
76739 /*
76740 ** Interpret the given string as a locking mode value.
76741 */
76742 static int getLockingMode(const char *z){
76743   if( z ){
76744     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
76745     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
76746   }
76747   return PAGER_LOCKINGMODE_QUERY;
76748 }
76749
76750 #ifndef SQLITE_OMIT_AUTOVACUUM
76751 /*
76752 ** Interpret the given string as an auto-vacuum mode value.
76753 **
76754 ** The following strings, "none", "full" and "incremental" are 
76755 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
76756 */
76757 static int getAutoVacuum(const char *z){
76758   int i;
76759   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
76760   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
76761   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
76762   i = atoi(z);
76763   return (u8)((i>=0&&i<=2)?i:0);
76764 }
76765 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
76766
76767 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
76768 /*
76769 ** Interpret the given string as a temp db location. Return 1 for file
76770 ** backed temporary databases, 2 for the Red-Black tree in memory database
76771 ** and 0 to use the compile-time default.
76772 */
76773 static int getTempStore(const char *z){
76774   if( z[0]>='0' && z[0]<='2' ){
76775     return z[0] - '0';
76776   }else if( sqlite3StrICmp(z, "file")==0 ){
76777     return 1;
76778   }else if( sqlite3StrICmp(z, "memory")==0 ){
76779     return 2;
76780   }else{
76781     return 0;
76782   }
76783 }
76784 #endif /* SQLITE_PAGER_PRAGMAS */
76785
76786 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
76787 /*
76788 ** Invalidate temp storage, either when the temp storage is changed
76789 ** from default, or when 'file' and the temp_store_directory has changed
76790 */
76791 static int invalidateTempStorage(Parse *pParse){
76792   sqlite3 *db = pParse->db;
76793   if( db->aDb[1].pBt!=0 ){
76794     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
76795       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
76796         "from within a transaction");
76797       return SQLITE_ERROR;
76798     }
76799     sqlite3BtreeClose(db->aDb[1].pBt);
76800     db->aDb[1].pBt = 0;
76801     sqlite3ResetInternalSchema(db, 0);
76802   }
76803   return SQLITE_OK;
76804 }
76805 #endif /* SQLITE_PAGER_PRAGMAS */
76806
76807 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
76808 /*
76809 ** If the TEMP database is open, close it and mark the database schema
76810 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
76811 ** or DEFAULT_TEMP_STORE pragmas.
76812 */
76813 static int changeTempStorage(Parse *pParse, const char *zStorageType){
76814   int ts = getTempStore(zStorageType);
76815   sqlite3 *db = pParse->db;
76816   if( db->temp_store==ts ) return SQLITE_OK;
76817   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
76818     return SQLITE_ERROR;
76819   }
76820   db->temp_store = (u8)ts;
76821   return SQLITE_OK;
76822 }
76823 #endif /* SQLITE_PAGER_PRAGMAS */
76824
76825 /*
76826 ** Generate code to return a single integer value.
76827 */
76828 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
76829   Vdbe *v = sqlite3GetVdbe(pParse);
76830   int mem = ++pParse->nMem;
76831   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
76832   if( pI64 ){
76833     memcpy(pI64, &value, sizeof(value));
76834   }
76835   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
76836   sqlite3VdbeSetNumCols(v, 1);
76837   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
76838   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
76839 }
76840
76841 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
76842 /*
76843 ** Check to see if zRight and zLeft refer to a pragma that queries
76844 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
76845 ** Also, implement the pragma.
76846 */
76847 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
76848   static const struct sPragmaType {
76849     const char *zName;  /* Name of the pragma */
76850     int mask;           /* Mask for the db->flags value */
76851   } aPragma[] = {
76852     { "full_column_names",        SQLITE_FullColNames  },
76853     { "short_column_names",       SQLITE_ShortColNames },
76854     { "count_changes",            SQLITE_CountRows     },
76855     { "empty_result_callbacks",   SQLITE_NullCallback  },
76856     { "legacy_file_format",       SQLITE_LegacyFileFmt },
76857     { "fullfsync",                SQLITE_FullFSync     },
76858     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
76859 #ifdef SQLITE_DEBUG
76860     { "sql_trace",                SQLITE_SqlTrace      },
76861     { "vdbe_listing",             SQLITE_VdbeListing   },
76862     { "vdbe_trace",               SQLITE_VdbeTrace     },
76863 #endif
76864 #ifndef SQLITE_OMIT_CHECK
76865     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
76866 #endif
76867     /* The following is VERY experimental */
76868     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
76869     { "omit_readlock",            SQLITE_NoReadlock    },
76870
76871     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
76872     ** flag if there are any active statements. */
76873     { "read_uncommitted",         SQLITE_ReadUncommitted },
76874     { "recursive_triggers",       SQLITE_RecTriggers },
76875
76876     /* This flag may only be set if both foreign-key and trigger support
76877     ** are present in the build.  */
76878 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
76879     { "foreign_keys",             SQLITE_ForeignKeys },
76880 #endif
76881   };
76882   int i;
76883   const struct sPragmaType *p;
76884   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
76885     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
76886       sqlite3 *db = pParse->db;
76887       Vdbe *v;
76888       v = sqlite3GetVdbe(pParse);
76889       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
76890       if( ALWAYS(v) ){
76891         if( zRight==0 ){
76892           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
76893         }else{
76894           int mask = p->mask;          /* Mask of bits to set or clear. */
76895           if( db->autoCommit==0 ){
76896             /* Foreign key support may not be enabled or disabled while not
76897             ** in auto-commit mode.  */
76898             mask &= ~(SQLITE_ForeignKeys);
76899           }
76900
76901           if( getBoolean(zRight) ){
76902             db->flags |= mask;
76903           }else{
76904             db->flags &= ~mask;
76905           }
76906
76907           /* Many of the flag-pragmas modify the code generated by the SQL 
76908           ** compiler (eg. count_changes). So add an opcode to expire all
76909           ** compiled SQL statements after modifying a pragma value.
76910           */
76911           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
76912         }
76913       }
76914
76915       return 1;
76916     }
76917   }
76918   return 0;
76919 }
76920 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
76921
76922 /*
76923 ** Return a human-readable name for a constraint resolution action.
76924 */
76925 #ifndef SQLITE_OMIT_FOREIGN_KEY
76926 static const char *actionName(u8 action){
76927   const char *zName;
76928   switch( action ){
76929     case OE_SetNull:  zName = "SET NULL";        break;
76930     case OE_SetDflt:  zName = "SET DEFAULT";     break;
76931     case OE_Cascade:  zName = "CASCADE";         break;
76932     case OE_Restrict: zName = "RESTRICT";        break;
76933     default:          zName = "NO ACTION";  
76934                       assert( action==OE_None ); break;
76935   }
76936   return zName;
76937 }
76938 #endif
76939
76940 /*
76941 ** Process a pragma statement.  
76942 **
76943 ** Pragmas are of this form:
76944 **
76945 **      PRAGMA [database.]id [= value]
76946 **
76947 ** The identifier might also be a string.  The value is a string, and
76948 ** identifier, or a number.  If minusFlag is true, then the value is
76949 ** a number that was preceded by a minus sign.
76950 **
76951 ** If the left side is "database.id" then pId1 is the database name
76952 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
76953 ** id and pId2 is any empty string.
76954 */
76955 SQLITE_PRIVATE void sqlite3Pragma(
76956   Parse *pParse, 
76957   Token *pId1,        /* First part of [database.]id field */
76958   Token *pId2,        /* Second part of [database.]id field, or NULL */
76959   Token *pValue,      /* Token for <value>, or NULL */
76960   int minusFlag       /* True if a '-' sign preceded <value> */
76961 ){
76962   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
76963   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
76964   const char *zDb = 0;   /* The database name */
76965   Token *pId;            /* Pointer to <id> token */
76966   int iDb;               /* Database index for <database> */
76967   sqlite3 *db = pParse->db;
76968   Db *pDb;
76969   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
76970   if( v==0 ) return;
76971   pParse->nMem = 2;
76972
76973   /* Interpret the [database.] part of the pragma statement. iDb is the
76974   ** index of the database this pragma is being applied to in db.aDb[]. */
76975   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
76976   if( iDb<0 ) return;
76977   pDb = &db->aDb[iDb];
76978
76979   /* If the temp database has been explicitly named as part of the 
76980   ** pragma, make sure it is open. 
76981   */
76982   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
76983     return;
76984   }
76985
76986   zLeft = sqlite3NameFromToken(db, pId);
76987   if( !zLeft ) return;
76988   if( minusFlag ){
76989     zRight = sqlite3MPrintf(db, "-%T", pValue);
76990   }else{
76991     zRight = sqlite3NameFromToken(db, pValue);
76992   }
76993
76994   assert( pId2 );
76995   zDb = pId2->n>0 ? pDb->zName : 0;
76996   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
76997     goto pragma_out;
76998   }
76999  
77000 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
77001   /*
77002   **  PRAGMA [database.]default_cache_size
77003   **  PRAGMA [database.]default_cache_size=N
77004   **
77005   ** The first form reports the current persistent setting for the
77006   ** page cache size.  The value returned is the maximum number of
77007   ** pages in the page cache.  The second form sets both the current
77008   ** page cache size value and the persistent page cache size value
77009   ** stored in the database file.
77010   **
77011   ** The default cache size is stored in meta-value 2 of page 1 of the
77012   ** database file.  The cache size is actually the absolute value of
77013   ** this memory location.  The sign of meta-value 2 determines the
77014   ** synchronous setting.  A negative value means synchronous is off
77015   ** and a positive value means synchronous is on.
77016   */
77017   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
77018     static const VdbeOpList getCacheSize[] = {
77019       { OP_Transaction, 0, 0,        0},                         /* 0 */
77020       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
77021       { OP_IfPos,       1, 7,        0},
77022       { OP_Integer,     0, 2,        0},
77023       { OP_Subtract,    1, 2,        1},
77024       { OP_IfPos,       1, 7,        0},
77025       { OP_Integer,     0, 1,        0},                         /* 6 */
77026       { OP_ResultRow,   1, 1,        0},
77027     };
77028     int addr;
77029     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77030     sqlite3VdbeUsesBtree(v, iDb);
77031     if( !zRight ){
77032       sqlite3VdbeSetNumCols(v, 1);
77033       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
77034       pParse->nMem += 2;
77035       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
77036       sqlite3VdbeChangeP1(v, addr, iDb);
77037       sqlite3VdbeChangeP1(v, addr+1, iDb);
77038       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
77039     }else{
77040       int size = atoi(zRight);
77041       if( size<0 ) size = -size;
77042       sqlite3BeginWriteOperation(pParse, 0, iDb);
77043       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
77044       sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, BTREE_DEFAULT_CACHE_SIZE);
77045       addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
77046       sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
77047       sqlite3VdbeJumpHere(v, addr);
77048       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
77049       pDb->pSchema->cache_size = size;
77050       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
77051     }
77052   }else
77053
77054   /*
77055   **  PRAGMA [database.]page_size
77056   **  PRAGMA [database.]page_size=N
77057   **
77058   ** The first form reports the current setting for the
77059   ** database page size in bytes.  The second form sets the
77060   ** database page size value.  The value can only be set if
77061   ** the database has not yet been created.
77062   */
77063   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
77064     Btree *pBt = pDb->pBt;
77065     assert( pBt!=0 );
77066     if( !zRight ){
77067       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
77068       returnSingleInt(pParse, "page_size", size);
77069     }else{
77070       /* Malloc may fail when setting the page-size, as there is an internal
77071       ** buffer that the pager module resizes using sqlite3_realloc().
77072       */
77073       db->nextPagesize = atoi(zRight);
77074       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
77075         db->mallocFailed = 1;
77076       }
77077     }
77078   }else
77079
77080   /*
77081   **  PRAGMA [database.]max_page_count
77082   **  PRAGMA [database.]max_page_count=N
77083   **
77084   ** The first form reports the current setting for the
77085   ** maximum number of pages in the database file.  The 
77086   ** second form attempts to change this setting.  Both
77087   ** forms return the current setting.
77088   */
77089   if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
77090     Btree *pBt = pDb->pBt;
77091     int newMax = 0;
77092     assert( pBt!=0 );
77093     if( zRight ){
77094       newMax = atoi(zRight);
77095     }
77096     if( ALWAYS(pBt) ){
77097       newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
77098     }
77099     returnSingleInt(pParse, "max_page_count", newMax);
77100   }else
77101
77102   /*
77103   **  PRAGMA [database.]page_count
77104   **
77105   ** Return the number of pages in the specified database.
77106   */
77107   if( sqlite3StrICmp(zLeft,"page_count")==0 ){
77108     int iReg;
77109     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77110     sqlite3CodeVerifySchema(pParse, iDb);
77111     iReg = ++pParse->nMem;
77112     sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
77113     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
77114     sqlite3VdbeSetNumCols(v, 1);
77115     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
77116   }else
77117
77118   /*
77119   **  PRAGMA [database.]locking_mode
77120   **  PRAGMA [database.]locking_mode = (normal|exclusive)
77121   */
77122   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
77123     const char *zRet = "normal";
77124     int eMode = getLockingMode(zRight);
77125
77126     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
77127       /* Simple "PRAGMA locking_mode;" statement. This is a query for
77128       ** the current default locking mode (which may be different to
77129       ** the locking-mode of the main database).
77130       */
77131       eMode = db->dfltLockMode;
77132     }else{
77133       Pager *pPager;
77134       if( pId2->n==0 ){
77135         /* This indicates that no database name was specified as part
77136         ** of the PRAGMA command. In this case the locking-mode must be
77137         ** set on all attached databases, as well as the main db file.
77138         **
77139         ** Also, the sqlite3.dfltLockMode variable is set so that
77140         ** any subsequently attached databases also use the specified
77141         ** locking mode.
77142         */
77143         int ii;
77144         assert(pDb==&db->aDb[0]);
77145         for(ii=2; ii<db->nDb; ii++){
77146           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
77147           sqlite3PagerLockingMode(pPager, eMode);
77148         }
77149         db->dfltLockMode = (u8)eMode;
77150       }
77151       pPager = sqlite3BtreePager(pDb->pBt);
77152       eMode = sqlite3PagerLockingMode(pPager, eMode);
77153     }
77154
77155     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
77156     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
77157       zRet = "exclusive";
77158     }
77159     sqlite3VdbeSetNumCols(v, 1);
77160     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
77161     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
77162     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77163   }else
77164
77165   /*
77166   **  PRAGMA [database.]journal_mode
77167   **  PRAGMA [database.]journal_mode = (delete|persist|off|truncate|memory)
77168   */
77169   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
77170     int eMode;
77171     static char * const azModeName[] = {
77172       "delete", "persist", "off", "truncate", "memory"
77173     };
77174
77175     if( zRight==0 ){
77176       eMode = PAGER_JOURNALMODE_QUERY;
77177     }else{
77178       int n = sqlite3Strlen30(zRight);
77179       eMode = sizeof(azModeName)/sizeof(azModeName[0]) - 1;
77180       while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
77181         eMode--;
77182       }
77183     }
77184     if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
77185       /* Simple "PRAGMA journal_mode;" statement. This is a query for
77186       ** the current default journal mode (which may be different to
77187       ** the journal-mode of the main database).
77188       */
77189       eMode = db->dfltJournalMode;
77190     }else{
77191       Pager *pPager;
77192       if( pId2->n==0 ){
77193         /* This indicates that no database name was specified as part
77194         ** of the PRAGMA command. In this case the journal-mode must be
77195         ** set on all attached databases, as well as the main db file.
77196         **
77197         ** Also, the sqlite3.dfltJournalMode variable is set so that
77198         ** any subsequently attached databases also use the specified
77199         ** journal mode.
77200         */
77201         int ii;
77202         assert(pDb==&db->aDb[0]);
77203         for(ii=1; ii<db->nDb; ii++){
77204           if( db->aDb[ii].pBt ){
77205             pPager = sqlite3BtreePager(db->aDb[ii].pBt);
77206             sqlite3PagerJournalMode(pPager, eMode);
77207           }
77208         }
77209         db->dfltJournalMode = (u8)eMode;
77210       }
77211       pPager = sqlite3BtreePager(pDb->pBt);
77212       eMode = sqlite3PagerJournalMode(pPager, eMode);
77213     }
77214     assert( eMode==PAGER_JOURNALMODE_DELETE
77215               || eMode==PAGER_JOURNALMODE_TRUNCATE
77216               || eMode==PAGER_JOURNALMODE_PERSIST
77217               || eMode==PAGER_JOURNALMODE_OFF
77218               || eMode==PAGER_JOURNALMODE_MEMORY );
77219     sqlite3VdbeSetNumCols(v, 1);
77220     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
77221     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, 
77222            azModeName[eMode], P4_STATIC);
77223     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77224   }else
77225
77226   /*
77227   **  PRAGMA [database.]journal_size_limit
77228   **  PRAGMA [database.]journal_size_limit=N
77229   **
77230   ** Get or set the size limit on rollback journal files.
77231   */
77232   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
77233     Pager *pPager = sqlite3BtreePager(pDb->pBt);
77234     i64 iLimit = -2;
77235     if( zRight ){
77236       sqlite3Atoi64(zRight, &iLimit);
77237       if( iLimit<-1 ) iLimit = -1;
77238     }
77239     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
77240     returnSingleInt(pParse, "journal_size_limit", iLimit);
77241   }else
77242
77243 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
77244
77245   /*
77246   **  PRAGMA [database.]auto_vacuum
77247   **  PRAGMA [database.]auto_vacuum=N
77248   **
77249   ** Get or set the value of the database 'auto-vacuum' parameter.
77250   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
77251   */
77252 #ifndef SQLITE_OMIT_AUTOVACUUM
77253   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
77254     Btree *pBt = pDb->pBt;
77255     assert( pBt!=0 );
77256     if( sqlite3ReadSchema(pParse) ){
77257       goto pragma_out;
77258     }
77259     if( !zRight ){
77260       int auto_vacuum;
77261       if( ALWAYS(pBt) ){
77262          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
77263       }else{
77264          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
77265       }
77266       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
77267     }else{
77268       int eAuto = getAutoVacuum(zRight);
77269       assert( eAuto>=0 && eAuto<=2 );
77270       db->nextAutovac = (u8)eAuto;
77271       if( ALWAYS(eAuto>=0) ){
77272         /* Call SetAutoVacuum() to set initialize the internal auto and
77273         ** incr-vacuum flags. This is required in case this connection
77274         ** creates the database file. It is important that it is created
77275         ** as an auto-vacuum capable db.
77276         */
77277         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
77278         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
77279           /* When setting the auto_vacuum mode to either "full" or 
77280           ** "incremental", write the value of meta[6] in the database
77281           ** file. Before writing to meta[6], check that meta[3] indicates
77282           ** that this really is an auto-vacuum capable database.
77283           */
77284           static const VdbeOpList setMeta6[] = {
77285             { OP_Transaction,    0,         1,                 0},    /* 0 */
77286             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
77287             { OP_If,             1,         0,                 0},    /* 2 */
77288             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
77289             { OP_Integer,        0,         1,                 0},    /* 4 */
77290             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
77291           };
77292           int iAddr;
77293           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
77294           sqlite3VdbeChangeP1(v, iAddr, iDb);
77295           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
77296           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
77297           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
77298           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
77299           sqlite3VdbeUsesBtree(v, iDb);
77300         }
77301       }
77302     }
77303   }else
77304 #endif
77305
77306   /*
77307   **  PRAGMA [database.]incremental_vacuum(N)
77308   **
77309   ** Do N steps of incremental vacuuming on a database.
77310   */
77311 #ifndef SQLITE_OMIT_AUTOVACUUM
77312   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
77313     int iLimit, addr;
77314     if( sqlite3ReadSchema(pParse) ){
77315       goto pragma_out;
77316     }
77317     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
77318       iLimit = 0x7fffffff;
77319     }
77320     sqlite3BeginWriteOperation(pParse, 0, iDb);
77321     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
77322     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
77323     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
77324     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
77325     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
77326     sqlite3VdbeJumpHere(v, addr);
77327   }else
77328 #endif
77329
77330 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
77331   /*
77332   **  PRAGMA [database.]cache_size
77333   **  PRAGMA [database.]cache_size=N
77334   **
77335   ** The first form reports the current local setting for the
77336   ** page cache size.  The local setting can be different from
77337   ** the persistent cache size value that is stored in the database
77338   ** file itself.  The value returned is the maximum number of
77339   ** pages in the page cache.  The second form sets the local
77340   ** page cache size value.  It does not change the persistent
77341   ** cache size stored on the disk so the cache size will revert
77342   ** to its default value when the database is closed and reopened.
77343   ** N should be a positive integer.
77344   */
77345   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
77346     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77347     if( !zRight ){
77348       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
77349     }else{
77350       int size = atoi(zRight);
77351       if( size<0 ) size = -size;
77352       pDb->pSchema->cache_size = size;
77353       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
77354     }
77355   }else
77356
77357   /*
77358   **   PRAGMA temp_store
77359   **   PRAGMA temp_store = "default"|"memory"|"file"
77360   **
77361   ** Return or set the local value of the temp_store flag.  Changing
77362   ** the local value does not make changes to the disk file and the default
77363   ** value will be restored the next time the database is opened.
77364   **
77365   ** Note that it is possible for the library compile-time options to
77366   ** override this setting
77367   */
77368   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
77369     if( !zRight ){
77370       returnSingleInt(pParse, "temp_store", db->temp_store);
77371     }else{
77372       changeTempStorage(pParse, zRight);
77373     }
77374   }else
77375
77376   /*
77377   **   PRAGMA temp_store_directory
77378   **   PRAGMA temp_store_directory = ""|"directory_name"
77379   **
77380   ** Return or set the local value of the temp_store_directory flag.  Changing
77381   ** the value sets a specific directory to be used for temporary files.
77382   ** Setting to a null string reverts to the default temporary directory search.
77383   ** If temporary directory is changed, then invalidateTempStorage.
77384   **
77385   */
77386   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
77387     if( !zRight ){
77388       if( sqlite3_temp_directory ){
77389         sqlite3VdbeSetNumCols(v, 1);
77390         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
77391             "temp_store_directory", SQLITE_STATIC);
77392         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
77393         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77394       }
77395     }else{
77396 #ifndef SQLITE_OMIT_WSD
77397       if( zRight[0] ){
77398         int rc;
77399         int res;
77400         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
77401         if( rc!=SQLITE_OK || res==0 ){
77402           sqlite3ErrorMsg(pParse, "not a writable directory");
77403           goto pragma_out;
77404         }
77405       }
77406       if( SQLITE_TEMP_STORE==0
77407        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
77408        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
77409       ){
77410         invalidateTempStorage(pParse);
77411       }
77412       sqlite3_free(sqlite3_temp_directory);
77413       if( zRight[0] ){
77414         sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
77415       }else{
77416         sqlite3_temp_directory = 0;
77417       }
77418 #endif /* SQLITE_OMIT_WSD */
77419     }
77420   }else
77421
77422 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
77423 #  if defined(__APPLE__)
77424 #    define SQLITE_ENABLE_LOCKING_STYLE 1
77425 #  else
77426 #    define SQLITE_ENABLE_LOCKING_STYLE 0
77427 #  endif
77428 #endif
77429 #if SQLITE_ENABLE_LOCKING_STYLE
77430   /*
77431    **   PRAGMA [database.]lock_proxy_file
77432    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
77433    **
77434    ** Return or set the value of the lock_proxy_file flag.  Changing
77435    ** the value sets a specific file to be used for database access locks.
77436    **
77437    */
77438   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
77439     if( !zRight ){
77440       Pager *pPager = sqlite3BtreePager(pDb->pBt);
77441       char *proxy_file_path = NULL;
77442       sqlite3_file *pFile = sqlite3PagerFile(pPager);
77443       sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE, 
77444                            &proxy_file_path);
77445       
77446       if( proxy_file_path ){
77447         sqlite3VdbeSetNumCols(v, 1);
77448         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
77449                               "lock_proxy_file", SQLITE_STATIC);
77450         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
77451         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77452       }
77453     }else{
77454       Pager *pPager = sqlite3BtreePager(pDb->pBt);
77455       sqlite3_file *pFile = sqlite3PagerFile(pPager);
77456       int res;
77457       if( zRight[0] ){
77458         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
77459                                      zRight);
77460       } else {
77461         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
77462                                      NULL);
77463       }
77464       if( res!=SQLITE_OK ){
77465         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
77466         goto pragma_out;
77467       }
77468     }
77469   }else
77470 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
77471     
77472   /*
77473   **   PRAGMA [database.]synchronous
77474   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
77475   **
77476   ** Return or set the local value of the synchronous flag.  Changing
77477   ** the local value does not make changes to the disk file and the
77478   ** default value will be restored the next time the database is
77479   ** opened.
77480   */
77481   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
77482     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77483     if( !zRight ){
77484       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
77485     }else{
77486       if( !db->autoCommit ){
77487         sqlite3ErrorMsg(pParse, 
77488             "Safety level may not be changed inside a transaction");
77489       }else{
77490         pDb->safety_level = getSafetyLevel(zRight)+1;
77491       }
77492     }
77493   }else
77494 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
77495
77496 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
77497   if( flagPragma(pParse, zLeft, zRight) ){
77498     /* The flagPragma() subroutine also generates any necessary code
77499     ** there is nothing more to do here */
77500   }else
77501 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
77502
77503 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
77504   /*
77505   **   PRAGMA table_info(<table>)
77506   **
77507   ** Return a single row for each column of the named table. The columns of
77508   ** the returned data set are:
77509   **
77510   ** cid:        Column id (numbered from left to right, starting at 0)
77511   ** name:       Column name
77512   ** type:       Column declaration type.
77513   ** notnull:    True if 'NOT NULL' is part of column declaration
77514   ** dflt_value: The default value for the column, if any.
77515   */
77516   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
77517     Table *pTab;
77518     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77519     pTab = sqlite3FindTable(db, zRight, zDb);
77520     if( pTab ){
77521       int i;
77522       int nHidden = 0;
77523       Column *pCol;
77524       sqlite3VdbeSetNumCols(v, 6);
77525       pParse->nMem = 6;
77526       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
77527       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77528       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
77529       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
77530       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
77531       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
77532       sqlite3ViewGetColumnNames(pParse, pTab);
77533       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
77534         if( IsHiddenColumn(pCol) ){
77535           nHidden++;
77536           continue;
77537         }
77538         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
77539         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
77540         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
77541            pCol->zType ? pCol->zType : "", 0);
77542         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
77543         if( pCol->zDflt ){
77544           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
77545         }else{
77546           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
77547         }
77548         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
77549         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
77550       }
77551     }
77552   }else
77553
77554   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
77555     Index *pIdx;
77556     Table *pTab;
77557     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77558     pIdx = sqlite3FindIndex(db, zRight, zDb);
77559     if( pIdx ){
77560       int i;
77561       pTab = pIdx->pTable;
77562       sqlite3VdbeSetNumCols(v, 3);
77563       pParse->nMem = 3;
77564       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
77565       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
77566       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
77567       for(i=0; i<pIdx->nColumn; i++){
77568         int cnum = pIdx->aiColumn[i];
77569         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77570         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
77571         assert( pTab->nCol>cnum );
77572         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
77573         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
77574       }
77575     }
77576   }else
77577
77578   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
77579     Index *pIdx;
77580     Table *pTab;
77581     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77582     pTab = sqlite3FindTable(db, zRight, zDb);
77583     if( pTab ){
77584       v = sqlite3GetVdbe(pParse);
77585       pIdx = pTab->pIndex;
77586       if( pIdx ){
77587         int i = 0; 
77588         sqlite3VdbeSetNumCols(v, 3);
77589         pParse->nMem = 3;
77590         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
77591         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77592         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
77593         while(pIdx){
77594           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77595           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
77596           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
77597           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
77598           ++i;
77599           pIdx = pIdx->pNext;
77600         }
77601       }
77602     }
77603   }else
77604
77605   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
77606     int i;
77607     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77608     sqlite3VdbeSetNumCols(v, 3);
77609     pParse->nMem = 3;
77610     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
77611     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77612     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
77613     for(i=0; i<db->nDb; i++){
77614       if( db->aDb[i].pBt==0 ) continue;
77615       assert( db->aDb[i].zName!=0 );
77616       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77617       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
77618       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
77619            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
77620       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
77621     }
77622   }else
77623
77624   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
77625     int i = 0;
77626     HashElem *p;
77627     sqlite3VdbeSetNumCols(v, 2);
77628     pParse->nMem = 2;
77629     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
77630     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77631     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
77632       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
77633       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
77634       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
77635       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
77636     }
77637   }else
77638 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
77639
77640 #ifndef SQLITE_OMIT_FOREIGN_KEY
77641   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
77642     FKey *pFK;
77643     Table *pTab;
77644     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77645     pTab = sqlite3FindTable(db, zRight, zDb);
77646     if( pTab ){
77647       v = sqlite3GetVdbe(pParse);
77648       pFK = pTab->pFKey;
77649       if( pFK ){
77650         int i = 0; 
77651         sqlite3VdbeSetNumCols(v, 8);
77652         pParse->nMem = 8;
77653         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
77654         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
77655         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
77656         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
77657         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
77658         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
77659         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
77660         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
77661         while(pFK){
77662           int j;
77663           for(j=0; j<pFK->nCol; j++){
77664             char *zCol = pFK->aCol[j].zCol;
77665             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
77666             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
77667             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77668             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
77669             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
77670             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
77671                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
77672             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
77673             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
77674             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
77675             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
77676             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
77677           }
77678           ++i;
77679           pFK = pFK->pNextFrom;
77680         }
77681       }
77682     }
77683   }else
77684 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
77685
77686 #ifndef NDEBUG
77687   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
77688     if( zRight ){
77689       if( getBoolean(zRight) ){
77690         sqlite3ParserTrace(stderr, "parser: ");
77691       }else{
77692         sqlite3ParserTrace(0, 0);
77693       }
77694     }
77695   }else
77696 #endif
77697
77698   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
77699   ** used will be case sensitive or not depending on the RHS.
77700   */
77701   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
77702     if( zRight ){
77703       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
77704     }
77705   }else
77706
77707 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
77708 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
77709 #endif
77710
77711 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
77712   /* Pragma "quick_check" is an experimental reduced version of 
77713   ** integrity_check designed to detect most database corruption
77714   ** without most of the overhead of a full integrity-check.
77715   */
77716   if( sqlite3StrICmp(zLeft, "integrity_check")==0
77717    || sqlite3StrICmp(zLeft, "quick_check")==0 
77718   ){
77719     int i, j, addr, mxErr;
77720
77721     /* Code that appears at the end of the integrity check.  If no error
77722     ** messages have been generated, output OK.  Otherwise output the
77723     ** error message
77724     */
77725     static const VdbeOpList endCode[] = {
77726       { OP_AddImm,      1, 0,        0},    /* 0 */
77727       { OP_IfNeg,       1, 0,        0},    /* 1 */
77728       { OP_String8,     0, 3,        0},    /* 2 */
77729       { OP_ResultRow,   3, 1,        0},
77730     };
77731
77732     int isQuick = (zLeft[0]=='q');
77733
77734     /* Initialize the VDBE program */
77735     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77736     pParse->nMem = 6;
77737     sqlite3VdbeSetNumCols(v, 1);
77738     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
77739
77740     /* Set the maximum error count */
77741     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
77742     if( zRight ){
77743       mxErr = atoi(zRight);
77744       if( mxErr<=0 ){
77745         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
77746       }
77747     }
77748     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
77749
77750     /* Do an integrity check on each database file */
77751     for(i=0; i<db->nDb; i++){
77752       HashElem *x;
77753       Hash *pTbls;
77754       int cnt = 0;
77755
77756       if( OMIT_TEMPDB && i==1 ) continue;
77757
77758       sqlite3CodeVerifySchema(pParse, i);
77759       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
77760       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
77761       sqlite3VdbeJumpHere(v, addr);
77762
77763       /* Do an integrity check of the B-Tree
77764       **
77765       ** Begin by filling registers 2, 3, ... with the root pages numbers
77766       ** for all tables and indices in the database.
77767       */
77768       pTbls = &db->aDb[i].pSchema->tblHash;
77769       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
77770         Table *pTab = sqliteHashData(x);
77771         Index *pIdx;
77772         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
77773         cnt++;
77774         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
77775           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
77776           cnt++;
77777         }
77778       }
77779
77780       /* Make sure sufficient number of registers have been allocated */
77781       if( pParse->nMem < cnt+4 ){
77782         pParse->nMem = cnt+4;
77783       }
77784
77785       /* Do the b-tree integrity checks */
77786       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
77787       sqlite3VdbeChangeP5(v, (u8)i);
77788       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
77789       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
77790          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
77791          P4_DYNAMIC);
77792       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
77793       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
77794       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
77795       sqlite3VdbeJumpHere(v, addr);
77796
77797       /* Make sure all the indices are constructed correctly.
77798       */
77799       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
77800         Table *pTab = sqliteHashData(x);
77801         Index *pIdx;
77802         int loopTop;
77803
77804         if( pTab->pIndex==0 ) continue;
77805         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
77806         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
77807         sqlite3VdbeJumpHere(v, addr);
77808         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
77809         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
77810         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
77811         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
77812         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
77813           int jmp2;
77814           int r1;
77815           static const VdbeOpList idxErr[] = {
77816             { OP_AddImm,      1, -1,  0},
77817             { OP_String8,     0,  3,  0},    /* 1 */
77818             { OP_Rowid,       1,  4,  0},
77819             { OP_String8,     0,  5,  0},    /* 3 */
77820             { OP_String8,     0,  6,  0},    /* 4 */
77821             { OP_Concat,      4,  3,  3},
77822             { OP_Concat,      5,  3,  3},
77823             { OP_Concat,      6,  3,  3},
77824             { OP_ResultRow,   3,  1,  0},
77825             { OP_IfPos,       1,  0,  0},    /* 9 */
77826             { OP_Halt,        0,  0,  0},
77827           };
77828           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
77829           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
77830           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
77831           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
77832           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
77833           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
77834           sqlite3VdbeJumpHere(v, addr+9);
77835           sqlite3VdbeJumpHere(v, jmp2);
77836         }
77837         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
77838         sqlite3VdbeJumpHere(v, loopTop);
77839         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
77840           static const VdbeOpList cntIdx[] = {
77841              { OP_Integer,      0,  3,  0},
77842              { OP_Rewind,       0,  0,  0},  /* 1 */
77843              { OP_AddImm,       3,  1,  0},
77844              { OP_Next,         0,  0,  0},  /* 3 */
77845              { OP_Eq,           2,  0,  3},  /* 4 */
77846              { OP_AddImm,       1, -1,  0},
77847              { OP_String8,      0,  2,  0},  /* 6 */
77848              { OP_String8,      0,  3,  0},  /* 7 */
77849              { OP_Concat,       3,  2,  2},
77850              { OP_ResultRow,    2,  1,  0},
77851           };
77852           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
77853           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
77854           sqlite3VdbeJumpHere(v, addr);
77855           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
77856           sqlite3VdbeChangeP1(v, addr+1, j+2);
77857           sqlite3VdbeChangeP2(v, addr+1, addr+4);
77858           sqlite3VdbeChangeP1(v, addr+3, j+2);
77859           sqlite3VdbeChangeP2(v, addr+3, addr+2);
77860           sqlite3VdbeJumpHere(v, addr+4);
77861           sqlite3VdbeChangeP4(v, addr+6, 
77862                      "wrong # of entries in index ", P4_STATIC);
77863           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
77864         }
77865       } 
77866     }
77867     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
77868     sqlite3VdbeChangeP2(v, addr, -mxErr);
77869     sqlite3VdbeJumpHere(v, addr+1);
77870     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
77871   }else
77872 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
77873
77874 #ifndef SQLITE_OMIT_UTF16
77875   /*
77876   **   PRAGMA encoding
77877   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
77878   **
77879   ** In its first form, this pragma returns the encoding of the main
77880   ** database. If the database is not initialized, it is initialized now.
77881   **
77882   ** The second form of this pragma is a no-op if the main database file
77883   ** has not already been initialized. In this case it sets the default
77884   ** encoding that will be used for the main database file if a new file
77885   ** is created. If an existing main database file is opened, then the
77886   ** default text encoding for the existing database is used.
77887   ** 
77888   ** In all cases new databases created using the ATTACH command are
77889   ** created to use the same default text encoding as the main database. If
77890   ** the main database has not been initialized and/or created when ATTACH
77891   ** is executed, this is done before the ATTACH operation.
77892   **
77893   ** In the second form this pragma sets the text encoding to be used in
77894   ** new database files created using this database handle. It is only
77895   ** useful if invoked immediately after the main database i
77896   */
77897   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
77898     static const struct EncName {
77899       char *zName;
77900       u8 enc;
77901     } encnames[] = {
77902       { "UTF8",     SQLITE_UTF8        },
77903       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
77904       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
77905       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
77906       { "UTF16le",  SQLITE_UTF16LE     },
77907       { "UTF16be",  SQLITE_UTF16BE     },
77908       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
77909       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
77910       { 0, 0 }
77911     };
77912     const struct EncName *pEnc;
77913     if( !zRight ){    /* "PRAGMA encoding" */
77914       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77915       sqlite3VdbeSetNumCols(v, 1);
77916       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
77917       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
77918       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
77919       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
77920       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
77921       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
77922       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77923     }else{                        /* "PRAGMA encoding = XXX" */
77924       /* Only change the value of sqlite.enc if the database handle is not
77925       ** initialized. If the main database exists, the new sqlite.enc value
77926       ** will be overwritten when the schema is next loaded. If it does not
77927       ** already exists, it will be created to use the new encoding value.
77928       */
77929       if( 
77930         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
77931         DbHasProperty(db, 0, DB_Empty) 
77932       ){
77933         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
77934           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
77935             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
77936             break;
77937           }
77938         }
77939         if( !pEnc->zName ){
77940           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
77941         }
77942       }
77943     }
77944   }else
77945 #endif /* SQLITE_OMIT_UTF16 */
77946
77947 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
77948   /*
77949   **   PRAGMA [database.]schema_version
77950   **   PRAGMA [database.]schema_version = <integer>
77951   **
77952   **   PRAGMA [database.]user_version
77953   **   PRAGMA [database.]user_version = <integer>
77954   **
77955   ** The pragma's schema_version and user_version are used to set or get
77956   ** the value of the schema-version and user-version, respectively. Both
77957   ** the schema-version and the user-version are 32-bit signed integers
77958   ** stored in the database header.
77959   **
77960   ** The schema-cookie is usually only manipulated internally by SQLite. It
77961   ** is incremented by SQLite whenever the database schema is modified (by
77962   ** creating or dropping a table or index). The schema version is used by
77963   ** SQLite each time a query is executed to ensure that the internal cache
77964   ** of the schema used when compiling the SQL query matches the schema of
77965   ** the database against which the compiled query is actually executed.
77966   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
77967   ** the schema-version is potentially dangerous and may lead to program
77968   ** crashes or database corruption. Use with caution!
77969   **
77970   ** The user-version is not used internally by SQLite. It may be used by
77971   ** applications for any purpose.
77972   */
77973   if( sqlite3StrICmp(zLeft, "schema_version")==0 
77974    || sqlite3StrICmp(zLeft, "user_version")==0 
77975    || sqlite3StrICmp(zLeft, "freelist_count")==0 
77976   ){
77977     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
77978     sqlite3VdbeUsesBtree(v, iDb);
77979     switch( zLeft[0] ){
77980       case 'f': case 'F':
77981         iCookie = BTREE_FREE_PAGE_COUNT;
77982         break;
77983       case 's': case 'S':
77984         iCookie = BTREE_SCHEMA_VERSION;
77985         break;
77986       default:
77987         iCookie = BTREE_USER_VERSION;
77988         break;
77989     }
77990
77991     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
77992       /* Write the specified cookie value */
77993       static const VdbeOpList setCookie[] = {
77994         { OP_Transaction,    0,  1,  0},    /* 0 */
77995         { OP_Integer,        0,  1,  0},    /* 1 */
77996         { OP_SetCookie,      0,  0,  1},    /* 2 */
77997       };
77998       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
77999       sqlite3VdbeChangeP1(v, addr, iDb);
78000       sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
78001       sqlite3VdbeChangeP1(v, addr+2, iDb);
78002       sqlite3VdbeChangeP2(v, addr+2, iCookie);
78003     }else{
78004       /* Read the specified cookie value */
78005       static const VdbeOpList readCookie[] = {
78006         { OP_Transaction,     0,  0,  0},    /* 0 */
78007         { OP_ReadCookie,      0,  1,  0},    /* 1 */
78008         { OP_ResultRow,       1,  1,  0}
78009       };
78010       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
78011       sqlite3VdbeChangeP1(v, addr, iDb);
78012       sqlite3VdbeChangeP1(v, addr+1, iDb);
78013       sqlite3VdbeChangeP3(v, addr+1, iCookie);
78014       sqlite3VdbeSetNumCols(v, 1);
78015       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
78016     }
78017   }else
78018 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
78019
78020 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
78021   /*
78022   ** Report the current state of file logs for all databases
78023   */
78024   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
78025     static const char *const azLockName[] = {
78026       "unlocked", "shared", "reserved", "pending", "exclusive"
78027     };
78028     int i;
78029     sqlite3VdbeSetNumCols(v, 2);
78030     pParse->nMem = 2;
78031     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
78032     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
78033     for(i=0; i<db->nDb; i++){
78034       Btree *pBt;
78035       Pager *pPager;
78036       const char *zState = "unknown";
78037       int j;
78038       if( db->aDb[i].zName==0 ) continue;
78039       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
78040       pBt = db->aDb[i].pBt;
78041       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
78042         zState = "closed";
78043       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
78044                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
78045          zState = azLockName[j];
78046       }
78047       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
78048       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
78049     }
78050
78051   }else
78052 #endif
78053
78054 #if SQLITE_HAS_CODEC
78055   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
78056     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
78057   }else
78058   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
78059     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
78060   }else
78061   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
78062                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
78063     int i, h1, h2;
78064     char zKey[40];
78065     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
78066       h1 += 9*(1&(h1>>6));
78067       h2 += 9*(1&(h2>>6));
78068       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
78069     }
78070     if( (zLeft[3] & 0xf)==0xb ){
78071       sqlite3_key(db, zKey, i/2);
78072     }else{
78073       sqlite3_rekey(db, zKey, i/2);
78074     }
78075   }else
78076 #endif
78077 #if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
78078   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
78079 #if SQLITE_HAS_CODEC
78080     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
78081       extern void sqlite3_activate_see(const char*);
78082       sqlite3_activate_see(&zRight[4]);
78083     }
78084 #endif
78085 #ifdef SQLITE_ENABLE_CEROD
78086     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
78087       extern void sqlite3_activate_cerod(const char*);
78088       sqlite3_activate_cerod(&zRight[6]);
78089     }
78090 #endif
78091   }else
78092 #endif
78093
78094  
78095   {/* Empty ELSE clause */}
78096
78097   /* Code an OP_Expire at the end of each PRAGMA program to cause
78098   ** the VDBE implementing the pragma to expire. Most (all?) pragmas
78099   ** are only valid for a single execution.
78100   */
78101   sqlite3VdbeAddOp2(v, OP_Expire, 1, 0);
78102
78103   /*
78104   ** Reset the safety level, in case the fullfsync flag or synchronous
78105   ** setting changed.
78106   */
78107 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
78108   if( db->autoCommit ){
78109     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
78110                (db->flags&SQLITE_FullFSync)!=0);
78111   }
78112 #endif
78113 pragma_out:
78114   sqlite3DbFree(db, zLeft);
78115   sqlite3DbFree(db, zRight);
78116 }
78117
78118 #endif /* SQLITE_OMIT_PRAGMA */
78119
78120 /************** End of pragma.c **********************************************/
78121 /************** Begin file prepare.c *****************************************/
78122 /*
78123 ** 2005 May 25
78124 **
78125 ** The author disclaims copyright to this source code.  In place of
78126 ** a legal notice, here is a blessing:
78127 **
78128 **    May you do good and not evil.
78129 **    May you find forgiveness for yourself and forgive others.
78130 **    May you share freely, never taking more than you give.
78131 **
78132 *************************************************************************
78133 ** This file contains the implementation of the sqlite3_prepare()
78134 ** interface, and routines that contribute to loading the database schema
78135 ** from disk.
78136 */
78137
78138 /*
78139 ** Fill the InitData structure with an error message that indicates
78140 ** that the database is corrupt.
78141 */
78142 static void corruptSchema(
78143   InitData *pData,     /* Initialization context */
78144   const char *zObj,    /* Object being parsed at the point of error */
78145   const char *zExtra   /* Error information */
78146 ){
78147   sqlite3 *db = pData->db;
78148   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
78149     if( zObj==0 ) zObj = "?";
78150     sqlite3SetString(pData->pzErrMsg, db,
78151       "malformed database schema (%s)", zObj);
78152     if( zExtra ){
78153       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
78154                                  "%s - %s", *pData->pzErrMsg, zExtra);
78155     }
78156   }
78157   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT;
78158 }
78159
78160 /*
78161 ** This is the callback routine for the code that initializes the
78162 ** database.  See sqlite3Init() below for additional information.
78163 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
78164 **
78165 ** Each callback contains the following information:
78166 **
78167 **     argv[0] = name of thing being created
78168 **     argv[1] = root page number for table or index. 0 for trigger or view.
78169 **     argv[2] = SQL text for the CREATE statement.
78170 **
78171 */
78172 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
78173   InitData *pData = (InitData*)pInit;
78174   sqlite3 *db = pData->db;
78175   int iDb = pData->iDb;
78176
78177   assert( argc==3 );
78178   UNUSED_PARAMETER2(NotUsed, argc);
78179   assert( sqlite3_mutex_held(db->mutex) );
78180   DbClearProperty(db, iDb, DB_Empty);
78181   if( db->mallocFailed ){
78182     corruptSchema(pData, argv[0], 0);
78183     return 1;
78184   }
78185
78186   assert( iDb>=0 && iDb<db->nDb );
78187   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
78188   if( argv[1]==0 ){
78189     corruptSchema(pData, argv[0], 0);
78190   }else if( argv[2] && argv[2][0] ){
78191     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
78192     ** But because db->init.busy is set to 1, no VDBE code is generated
78193     ** or executed.  All the parser does is build the internal data
78194     ** structures that describe the table, index, or view.
78195     */
78196     char *zErr;
78197     int rc;
78198     assert( db->init.busy );
78199     db->init.iDb = iDb;
78200     db->init.newTnum = atoi(argv[1]);
78201     db->init.orphanTrigger = 0;
78202     rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
78203     db->init.iDb = 0;
78204     assert( rc!=SQLITE_OK || zErr==0 );
78205     if( SQLITE_OK!=rc ){
78206       if( db->init.orphanTrigger ){
78207         assert( iDb==1 );
78208       }else{
78209         pData->rc = rc;
78210         if( rc==SQLITE_NOMEM ){
78211           db->mallocFailed = 1;
78212         }else if( rc!=SQLITE_INTERRUPT && rc!=SQLITE_LOCKED ){
78213           corruptSchema(pData, argv[0], zErr);
78214         }
78215       }
78216       sqlite3DbFree(db, zErr);
78217     }
78218   }else if( argv[0]==0 ){
78219     corruptSchema(pData, 0, 0);
78220   }else{
78221     /* If the SQL column is blank it means this is an index that
78222     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
78223     ** constraint for a CREATE TABLE.  The index should have already
78224     ** been created when we processed the CREATE TABLE.  All we have
78225     ** to do here is record the root page number for that index.
78226     */
78227     Index *pIndex;
78228     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
78229     if( pIndex==0 ){
78230       /* This can occur if there exists an index on a TEMP table which
78231       ** has the same name as another index on a permanent index.  Since
78232       ** the permanent table is hidden by the TEMP table, we can also
78233       ** safely ignore the index on the permanent table.
78234       */
78235       /* Do Nothing */;
78236     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
78237       corruptSchema(pData, argv[0], "invalid rootpage");
78238     }
78239   }
78240   return 0;
78241 }
78242
78243 /*
78244 ** Attempt to read the database schema and initialize internal
78245 ** data structures for a single database file.  The index of the
78246 ** database file is given by iDb.  iDb==0 is used for the main
78247 ** database.  iDb==1 should never be used.  iDb>=2 is used for
78248 ** auxiliary databases.  Return one of the SQLITE_ error codes to
78249 ** indicate success or failure.
78250 */
78251 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
78252   int rc;
78253   int i;
78254   int size;
78255   Table *pTab;
78256   Db *pDb;
78257   char const *azArg[4];
78258   int meta[5];
78259   InitData initData;
78260   char const *zMasterSchema;
78261   char const *zMasterName = SCHEMA_TABLE(iDb);
78262   int openedTransaction = 0;
78263
78264   /*
78265   ** The master database table has a structure like this
78266   */
78267   static const char master_schema[] = 
78268      "CREATE TABLE sqlite_master(\n"
78269      "  type text,\n"
78270      "  name text,\n"
78271      "  tbl_name text,\n"
78272      "  rootpage integer,\n"
78273      "  sql text\n"
78274      ")"
78275   ;
78276 #ifndef SQLITE_OMIT_TEMPDB
78277   static const char temp_master_schema[] = 
78278      "CREATE TEMP TABLE sqlite_temp_master(\n"
78279      "  type text,\n"
78280      "  name text,\n"
78281      "  tbl_name text,\n"
78282      "  rootpage integer,\n"
78283      "  sql text\n"
78284      ")"
78285   ;
78286 #else
78287   #define temp_master_schema 0
78288 #endif
78289
78290   assert( iDb>=0 && iDb<db->nDb );
78291   assert( db->aDb[iDb].pSchema );
78292   assert( sqlite3_mutex_held(db->mutex) );
78293   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
78294
78295   /* zMasterSchema and zInitScript are set to point at the master schema
78296   ** and initialisation script appropriate for the database being
78297   ** initialised. zMasterName is the name of the master table.
78298   */
78299   if( !OMIT_TEMPDB && iDb==1 ){
78300     zMasterSchema = temp_master_schema;
78301   }else{
78302     zMasterSchema = master_schema;
78303   }
78304   zMasterName = SCHEMA_TABLE(iDb);
78305
78306   /* Construct the schema tables.  */
78307   azArg[0] = zMasterName;
78308   azArg[1] = "1";
78309   azArg[2] = zMasterSchema;
78310   azArg[3] = 0;
78311   initData.db = db;
78312   initData.iDb = iDb;
78313   initData.rc = SQLITE_OK;
78314   initData.pzErrMsg = pzErrMsg;
78315   (void)sqlite3SafetyOff(db);
78316   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
78317   (void)sqlite3SafetyOn(db);
78318   if( initData.rc ){
78319     rc = initData.rc;
78320     goto error_out;
78321   }
78322   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
78323   if( ALWAYS(pTab) ){
78324     pTab->tabFlags |= TF_Readonly;
78325   }
78326
78327   /* Create a cursor to hold the database open
78328   */
78329   pDb = &db->aDb[iDb];
78330   if( pDb->pBt==0 ){
78331     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
78332       DbSetProperty(db, 1, DB_SchemaLoaded);
78333     }
78334     return SQLITE_OK;
78335   }
78336
78337   /* If there is not already a read-only (or read-write) transaction opened
78338   ** on the b-tree database, open one now. If a transaction is opened, it 
78339   ** will be closed before this function returns.  */
78340   sqlite3BtreeEnter(pDb->pBt);
78341   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
78342     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
78343     if( rc!=SQLITE_OK ){
78344       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
78345       goto initone_error_out;
78346     }
78347     openedTransaction = 1;
78348   }
78349
78350   /* Get the database meta information.
78351   **
78352   ** Meta values are as follows:
78353   **    meta[0]   Schema cookie.  Changes with each schema change.
78354   **    meta[1]   File format of schema layer.
78355   **    meta[2]   Size of the page cache.
78356   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
78357   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
78358   **    meta[5]   User version
78359   **    meta[6]   Incremental vacuum mode
78360   **    meta[7]   unused
78361   **    meta[8]   unused
78362   **    meta[9]   unused
78363   **
78364   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
78365   ** the possible values of meta[4].
78366   */
78367   for(i=0; i<ArraySize(meta); i++){
78368     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
78369   }
78370   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
78371
78372   /* If opening a non-empty database, check the text encoding. For the
78373   ** main database, set sqlite3.enc to the encoding of the main database.
78374   ** For an attached db, it is an error if the encoding is not the same
78375   ** as sqlite3.enc.
78376   */
78377   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
78378     if( iDb==0 ){
78379       u8 encoding;
78380       /* If opening the main database, set ENC(db). */
78381       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
78382       if( encoding==0 ) encoding = SQLITE_UTF8;
78383       ENC(db) = encoding;
78384       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
78385     }else{
78386       /* If opening an attached database, the encoding much match ENC(db) */
78387       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
78388         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
78389             " text encoding as main database");
78390         rc = SQLITE_ERROR;
78391         goto initone_error_out;
78392       }
78393     }
78394   }else{
78395     DbSetProperty(db, iDb, DB_Empty);
78396   }
78397   pDb->pSchema->enc = ENC(db);
78398
78399   if( pDb->pSchema->cache_size==0 ){
78400     size = meta[BTREE_DEFAULT_CACHE_SIZE-1];
78401     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
78402     if( size<0 ) size = -size;
78403     pDb->pSchema->cache_size = size;
78404     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
78405   }
78406
78407   /*
78408   ** file_format==1    Version 3.0.0.
78409   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
78410   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
78411   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
78412   */
78413   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
78414   if( pDb->pSchema->file_format==0 ){
78415     pDb->pSchema->file_format = 1;
78416   }
78417   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
78418     sqlite3SetString(pzErrMsg, db, "unsupported file format");
78419     rc = SQLITE_ERROR;
78420     goto initone_error_out;
78421   }
78422
78423   /* Ticket #2804:  When we open a database in the newer file format,
78424   ** clear the legacy_file_format pragma flag so that a VACUUM will
78425   ** not downgrade the database and thus invalidate any descending
78426   ** indices that the user might have created.
78427   */
78428   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
78429     db->flags &= ~SQLITE_LegacyFileFmt;
78430   }
78431
78432   /* Read the schema information out of the schema tables
78433   */
78434   assert( db->init.busy );
78435   {
78436     char *zSql;
78437     zSql = sqlite3MPrintf(db, 
78438         "SELECT name, rootpage, sql FROM '%q'.%s",
78439         db->aDb[iDb].zName, zMasterName);
78440     (void)sqlite3SafetyOff(db);
78441 #ifndef SQLITE_OMIT_AUTHORIZATION
78442     {
78443       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
78444       xAuth = db->xAuth;
78445       db->xAuth = 0;
78446 #endif
78447       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
78448 #ifndef SQLITE_OMIT_AUTHORIZATION
78449       db->xAuth = xAuth;
78450     }
78451 #endif
78452     if( rc==SQLITE_OK ) rc = initData.rc;
78453     (void)sqlite3SafetyOn(db);
78454     sqlite3DbFree(db, zSql);
78455 #ifndef SQLITE_OMIT_ANALYZE
78456     if( rc==SQLITE_OK ){
78457       sqlite3AnalysisLoad(db, iDb);
78458     }
78459 #endif
78460   }
78461   if( db->mallocFailed ){
78462     rc = SQLITE_NOMEM;
78463     sqlite3ResetInternalSchema(db, 0);
78464   }
78465   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
78466     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
78467     ** the schema loaded, even if errors occurred. In this situation the 
78468     ** current sqlite3_prepare() operation will fail, but the following one
78469     ** will attempt to compile the supplied statement against whatever subset
78470     ** of the schema was loaded before the error occurred. The primary
78471     ** purpose of this is to allow access to the sqlite_master table
78472     ** even when its contents have been corrupted.
78473     */
78474     DbSetProperty(db, iDb, DB_SchemaLoaded);
78475     rc = SQLITE_OK;
78476   }
78477
78478   /* Jump here for an error that occurs after successfully allocating
78479   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
78480   ** before that point, jump to error_out.
78481   */
78482 initone_error_out:
78483   if( openedTransaction ){
78484     sqlite3BtreeCommit(pDb->pBt);
78485   }
78486   sqlite3BtreeLeave(pDb->pBt);
78487
78488 error_out:
78489   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
78490     db->mallocFailed = 1;
78491   }
78492   return rc;
78493 }
78494
78495 /*
78496 ** Initialize all database files - the main database file, the file
78497 ** used to store temporary tables, and any additional database files
78498 ** created using ATTACH statements.  Return a success code.  If an
78499 ** error occurs, write an error message into *pzErrMsg.
78500 **
78501 ** After a database is initialized, the DB_SchemaLoaded bit is set
78502 ** bit is set in the flags field of the Db structure. If the database
78503 ** file was of zero-length, then the DB_Empty flag is also set.
78504 */
78505 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
78506   int i, rc;
78507   int commit_internal = !(db->flags&SQLITE_InternChanges);
78508   
78509   assert( sqlite3_mutex_held(db->mutex) );
78510   rc = SQLITE_OK;
78511   db->init.busy = 1;
78512   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
78513     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
78514     rc = sqlite3InitOne(db, i, pzErrMsg);
78515     if( rc ){
78516       sqlite3ResetInternalSchema(db, i);
78517     }
78518   }
78519
78520   /* Once all the other databases have been initialised, load the schema
78521   ** for the TEMP database. This is loaded last, as the TEMP database
78522   ** schema may contain references to objects in other databases.
78523   */
78524 #ifndef SQLITE_OMIT_TEMPDB
78525   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
78526                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
78527     rc = sqlite3InitOne(db, 1, pzErrMsg);
78528     if( rc ){
78529       sqlite3ResetInternalSchema(db, 1);
78530     }
78531   }
78532 #endif
78533
78534   db->init.busy = 0;
78535   if( rc==SQLITE_OK && commit_internal ){
78536     sqlite3CommitInternalChanges(db);
78537   }
78538
78539   return rc; 
78540 }
78541
78542 /*
78543 ** This routine is a no-op if the database schema is already initialised.
78544 ** Otherwise, the schema is loaded. An error code is returned.
78545 */
78546 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
78547   int rc = SQLITE_OK;
78548   sqlite3 *db = pParse->db;
78549   assert( sqlite3_mutex_held(db->mutex) );
78550   if( !db->init.busy ){
78551     rc = sqlite3Init(db, &pParse->zErrMsg);
78552   }
78553   if( rc!=SQLITE_OK ){
78554     pParse->rc = rc;
78555     pParse->nErr++;
78556   }
78557   return rc;
78558 }
78559
78560
78561 /*
78562 ** Check schema cookies in all databases.  If any cookie is out
78563 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
78564 ** make no changes to pParse->rc.
78565 */
78566 static void schemaIsValid(Parse *pParse){
78567   sqlite3 *db = pParse->db;
78568   int iDb;
78569   int rc;
78570   int cookie;
78571
78572   assert( pParse->checkSchema );
78573   assert( sqlite3_mutex_held(db->mutex) );
78574   for(iDb=0; iDb<db->nDb; iDb++){
78575     int openedTransaction = 0;         /* True if a transaction is opened */
78576     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
78577     if( pBt==0 ) continue;
78578
78579     /* If there is not already a read-only (or read-write) transaction opened
78580     ** on the b-tree database, open one now. If a transaction is opened, it 
78581     ** will be closed immediately after reading the meta-value. */
78582     if( !sqlite3BtreeIsInReadTrans(pBt) ){
78583       rc = sqlite3BtreeBeginTrans(pBt, 0);
78584       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
78585         db->mallocFailed = 1;
78586       }
78587       if( rc!=SQLITE_OK ) return;
78588       openedTransaction = 1;
78589     }
78590
78591     /* Read the schema cookie from the database. If it does not match the 
78592     ** value stored as part of the in-memory schema representation,
78593     ** set Parse.rc to SQLITE_SCHEMA. */
78594     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
78595     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
78596       pParse->rc = SQLITE_SCHEMA;
78597     }
78598
78599     /* Close the transaction, if one was opened. */
78600     if( openedTransaction ){
78601       sqlite3BtreeCommit(pBt);
78602     }
78603   }
78604 }
78605
78606 /*
78607 ** Convert a schema pointer into the iDb index that indicates
78608 ** which database file in db->aDb[] the schema refers to.
78609 **
78610 ** If the same database is attached more than once, the first
78611 ** attached database is returned.
78612 */
78613 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
78614   int i = -1000000;
78615
78616   /* If pSchema is NULL, then return -1000000. This happens when code in 
78617   ** expr.c is trying to resolve a reference to a transient table (i.e. one
78618   ** created by a sub-select). In this case the return value of this 
78619   ** function should never be used.
78620   **
78621   ** We return -1000000 instead of the more usual -1 simply because using
78622   ** -1000000 as the incorrect index into db->aDb[] is much 
78623   ** more likely to cause a segfault than -1 (of course there are assert()
78624   ** statements too, but it never hurts to play the odds).
78625   */
78626   assert( sqlite3_mutex_held(db->mutex) );
78627   if( pSchema ){
78628     for(i=0; ALWAYS(i<db->nDb); i++){
78629       if( db->aDb[i].pSchema==pSchema ){
78630         break;
78631       }
78632     }
78633     assert( i>=0 && i<db->nDb );
78634   }
78635   return i;
78636 }
78637
78638 /*
78639 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
78640 */
78641 static int sqlite3Prepare(
78642   sqlite3 *db,              /* Database handle. */
78643   const char *zSql,         /* UTF-8 encoded SQL statement. */
78644   int nBytes,               /* Length of zSql in bytes. */
78645   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
78646   Vdbe *pReprepare,         /* VM being reprepared */
78647   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78648   const char **pzTail       /* OUT: End of parsed string */
78649 ){
78650   Parse *pParse;            /* Parsing context */
78651   char *zErrMsg = 0;        /* Error message */
78652   int rc = SQLITE_OK;       /* Result code */
78653   int i;                    /* Loop counter */
78654
78655   /* Allocate the parsing context */
78656   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
78657   if( pParse==0 ){
78658     rc = SQLITE_NOMEM;
78659     goto end_prepare;
78660   }
78661   pParse->pReprepare = pReprepare;
78662
78663   if( sqlite3SafetyOn(db) ){
78664     rc = SQLITE_MISUSE;
78665     goto end_prepare;
78666   }
78667   assert( ppStmt && *ppStmt==0 );
78668   assert( !db->mallocFailed );
78669   assert( sqlite3_mutex_held(db->mutex) );
78670
78671   /* Check to verify that it is possible to get a read lock on all
78672   ** database schemas.  The inability to get a read lock indicates that
78673   ** some other database connection is holding a write-lock, which in
78674   ** turn means that the other connection has made uncommitted changes
78675   ** to the schema.
78676   **
78677   ** Were we to proceed and prepare the statement against the uncommitted
78678   ** schema changes and if those schema changes are subsequently rolled
78679   ** back and different changes are made in their place, then when this
78680   ** prepared statement goes to run the schema cookie would fail to detect
78681   ** the schema change.  Disaster would follow.
78682   **
78683   ** This thread is currently holding mutexes on all Btrees (because
78684   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
78685   ** is not possible for another thread to start a new schema change
78686   ** while this routine is running.  Hence, we do not need to hold 
78687   ** locks on the schema, we just need to make sure nobody else is 
78688   ** holding them.
78689   **
78690   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
78691   ** but it does *not* override schema lock detection, so this all still
78692   ** works even if READ_UNCOMMITTED is set.
78693   */
78694   for(i=0; i<db->nDb; i++) {
78695     Btree *pBt = db->aDb[i].pBt;
78696     if( pBt ){
78697       assert( sqlite3BtreeHoldsMutex(pBt) );
78698       rc = sqlite3BtreeSchemaLocked(pBt);
78699       if( rc ){
78700         const char *zDb = db->aDb[i].zName;
78701         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
78702         (void)sqlite3SafetyOff(db);
78703         testcase( db->flags & SQLITE_ReadUncommitted );
78704         goto end_prepare;
78705       }
78706     }
78707   }
78708
78709   sqlite3VtabUnlockList(db);
78710
78711   pParse->db = db;
78712   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
78713     char *zSqlCopy;
78714     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
78715     testcase( nBytes==mxLen );
78716     testcase( nBytes==mxLen+1 );
78717     if( nBytes>mxLen ){
78718       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
78719       (void)sqlite3SafetyOff(db);
78720       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
78721       goto end_prepare;
78722     }
78723     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
78724     if( zSqlCopy ){
78725       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
78726       sqlite3DbFree(db, zSqlCopy);
78727       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
78728     }else{
78729       pParse->zTail = &zSql[nBytes];
78730     }
78731   }else{
78732     sqlite3RunParser(pParse, zSql, &zErrMsg);
78733   }
78734
78735   if( db->mallocFailed ){
78736     pParse->rc = SQLITE_NOMEM;
78737   }
78738   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
78739   if( pParse->checkSchema ){
78740     schemaIsValid(pParse);
78741   }
78742   if( pParse->rc==SQLITE_SCHEMA ){
78743     sqlite3ResetInternalSchema(db, 0);
78744   }
78745   if( db->mallocFailed ){
78746     pParse->rc = SQLITE_NOMEM;
78747   }
78748   if( pzTail ){
78749     *pzTail = pParse->zTail;
78750   }
78751   rc = pParse->rc;
78752
78753 #ifndef SQLITE_OMIT_EXPLAIN
78754   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
78755     static const char * const azColName[] = {
78756        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
78757        "order", "from", "detail"
78758     };
78759     int iFirst, mx;
78760     if( pParse->explain==2 ){
78761       sqlite3VdbeSetNumCols(pParse->pVdbe, 3);
78762       iFirst = 8;
78763       mx = 11;
78764     }else{
78765       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
78766       iFirst = 0;
78767       mx = 8;
78768     }
78769     for(i=iFirst; i<mx; i++){
78770       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
78771                             azColName[i], SQLITE_STATIC);
78772     }
78773   }
78774 #endif
78775
78776   if( sqlite3SafetyOff(db) ){
78777     rc = SQLITE_MISUSE;
78778   }
78779
78780   assert( db->init.busy==0 || saveSqlFlag==0 );
78781   if( db->init.busy==0 ){
78782     Vdbe *pVdbe = pParse->pVdbe;
78783     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
78784   }
78785   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
78786     sqlite3VdbeFinalize(pParse->pVdbe);
78787     assert(!(*ppStmt));
78788   }else{
78789     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
78790   }
78791
78792   if( zErrMsg ){
78793     sqlite3Error(db, rc, "%s", zErrMsg);
78794     sqlite3DbFree(db, zErrMsg);
78795   }else{
78796     sqlite3Error(db, rc, 0);
78797   }
78798
78799   /* Delete any TriggerPrg structures allocated while parsing this statement. */
78800   while( pParse->pTriggerPrg ){
78801     TriggerPrg *pT = pParse->pTriggerPrg;
78802     pParse->pTriggerPrg = pT->pNext;
78803     sqlite3VdbeProgramDelete(db, pT->pProgram, 0);
78804     sqlite3DbFree(db, pT);
78805   }
78806
78807 end_prepare:
78808
78809   sqlite3StackFree(db, pParse);
78810   rc = sqlite3ApiExit(db, rc);
78811   assert( (rc&db->errMask)==rc );
78812   return rc;
78813 }
78814 static int sqlite3LockAndPrepare(
78815   sqlite3 *db,              /* Database handle. */
78816   const char *zSql,         /* UTF-8 encoded SQL statement. */
78817   int nBytes,               /* Length of zSql in bytes. */
78818   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
78819   Vdbe *pOld,               /* VM being reprepared */
78820   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78821   const char **pzTail       /* OUT: End of parsed string */
78822 ){
78823   int rc;
78824   assert( ppStmt!=0 );
78825   *ppStmt = 0;
78826   if( !sqlite3SafetyCheckOk(db) ){
78827     return SQLITE_MISUSE;
78828   }
78829   sqlite3_mutex_enter(db->mutex);
78830   sqlite3BtreeEnterAll(db);
78831   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
78832   if( rc==SQLITE_SCHEMA ){
78833     sqlite3_finalize(*ppStmt);
78834     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
78835   }
78836   sqlite3BtreeLeaveAll(db);
78837   sqlite3_mutex_leave(db->mutex);
78838   return rc;
78839 }
78840
78841 /*
78842 ** Rerun the compilation of a statement after a schema change.
78843 **
78844 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
78845 ** if the statement cannot be recompiled because another connection has
78846 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
78847 ** occurs, return SQLITE_SCHEMA.
78848 */
78849 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
78850   int rc;
78851   sqlite3_stmt *pNew;
78852   const char *zSql;
78853   sqlite3 *db;
78854
78855   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
78856   zSql = sqlite3_sql((sqlite3_stmt *)p);
78857   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
78858   db = sqlite3VdbeDb(p);
78859   assert( sqlite3_mutex_held(db->mutex) );
78860   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
78861   if( rc ){
78862     if( rc==SQLITE_NOMEM ){
78863       db->mallocFailed = 1;
78864     }
78865     assert( pNew==0 );
78866     return (rc==SQLITE_LOCKED) ? SQLITE_LOCKED : SQLITE_SCHEMA;
78867   }else{
78868     assert( pNew!=0 );
78869   }
78870   sqlite3VdbeSwap((Vdbe*)pNew, p);
78871   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
78872   sqlite3VdbeResetStepResult((Vdbe*)pNew);
78873   sqlite3VdbeFinalize((Vdbe*)pNew);
78874   return SQLITE_OK;
78875 }
78876
78877
78878 /*
78879 ** Two versions of the official API.  Legacy and new use.  In the legacy
78880 ** version, the original SQL text is not saved in the prepared statement
78881 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
78882 ** sqlite3_step().  In the new version, the original SQL text is retained
78883 ** and the statement is automatically recompiled if an schema change
78884 ** occurs.
78885 */
78886 SQLITE_API int sqlite3_prepare(
78887   sqlite3 *db,              /* Database handle. */
78888   const char *zSql,         /* UTF-8 encoded SQL statement. */
78889   int nBytes,               /* Length of zSql in bytes. */
78890   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78891   const char **pzTail       /* OUT: End of parsed string */
78892 ){
78893   int rc;
78894   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
78895   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
78896   return rc;
78897 }
78898 SQLITE_API int sqlite3_prepare_v2(
78899   sqlite3 *db,              /* Database handle. */
78900   const char *zSql,         /* UTF-8 encoded SQL statement. */
78901   int nBytes,               /* Length of zSql in bytes. */
78902   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78903   const char **pzTail       /* OUT: End of parsed string */
78904 ){
78905   int rc;
78906   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
78907   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
78908   return rc;
78909 }
78910
78911
78912 #ifndef SQLITE_OMIT_UTF16
78913 /*
78914 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
78915 */
78916 static int sqlite3Prepare16(
78917   sqlite3 *db,              /* Database handle. */ 
78918   const void *zSql,         /* UTF-8 encoded SQL statement. */
78919   int nBytes,               /* Length of zSql in bytes. */
78920   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
78921   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78922   const void **pzTail       /* OUT: End of parsed string */
78923 ){
78924   /* This function currently works by first transforming the UTF-16
78925   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
78926   ** tricky bit is figuring out the pointer to return in *pzTail.
78927   */
78928   char *zSql8;
78929   const char *zTail8 = 0;
78930   int rc = SQLITE_OK;
78931
78932   assert( ppStmt );
78933   *ppStmt = 0;
78934   if( !sqlite3SafetyCheckOk(db) ){
78935     return SQLITE_MISUSE;
78936   }
78937   sqlite3_mutex_enter(db->mutex);
78938   zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
78939   if( zSql8 ){
78940     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
78941   }
78942
78943   if( zTail8 && pzTail ){
78944     /* If sqlite3_prepare returns a tail pointer, we calculate the
78945     ** equivalent pointer into the UTF-16 string by counting the unicode
78946     ** characters between zSql8 and zTail8, and then returning a pointer
78947     ** the same number of characters into the UTF-16 string.
78948     */
78949     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
78950     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
78951   }
78952   sqlite3DbFree(db, zSql8); 
78953   rc = sqlite3ApiExit(db, rc);
78954   sqlite3_mutex_leave(db->mutex);
78955   return rc;
78956 }
78957
78958 /*
78959 ** Two versions of the official API.  Legacy and new use.  In the legacy
78960 ** version, the original SQL text is not saved in the prepared statement
78961 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
78962 ** sqlite3_step().  In the new version, the original SQL text is retained
78963 ** and the statement is automatically recompiled if an schema change
78964 ** occurs.
78965 */
78966 SQLITE_API int sqlite3_prepare16(
78967   sqlite3 *db,              /* Database handle. */ 
78968   const void *zSql,         /* UTF-8 encoded SQL statement. */
78969   int nBytes,               /* Length of zSql in bytes. */
78970   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78971   const void **pzTail       /* OUT: End of parsed string */
78972 ){
78973   int rc;
78974   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
78975   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
78976   return rc;
78977 }
78978 SQLITE_API int sqlite3_prepare16_v2(
78979   sqlite3 *db,              /* Database handle. */ 
78980   const void *zSql,         /* UTF-8 encoded SQL statement. */
78981   int nBytes,               /* Length of zSql in bytes. */
78982   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78983   const void **pzTail       /* OUT: End of parsed string */
78984 ){
78985   int rc;
78986   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
78987   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
78988   return rc;
78989 }
78990
78991 #endif /* SQLITE_OMIT_UTF16 */
78992
78993 /************** End of prepare.c *********************************************/
78994 /************** Begin file select.c ******************************************/
78995 /*
78996 ** 2001 September 15
78997 **
78998 ** The author disclaims copyright to this source code.  In place of
78999 ** a legal notice, here is a blessing:
79000 **
79001 **    May you do good and not evil.
79002 **    May you find forgiveness for yourself and forgive others.
79003 **    May you share freely, never taking more than you give.
79004 **
79005 *************************************************************************
79006 ** This file contains C code routines that are called by the parser
79007 ** to handle SELECT statements in SQLite.
79008 */
79009
79010
79011 /*
79012 ** Delete all the content of a Select structure but do not deallocate
79013 ** the select structure itself.
79014 */
79015 static void clearSelect(sqlite3 *db, Select *p){
79016   sqlite3ExprListDelete(db, p->pEList);
79017   sqlite3SrcListDelete(db, p->pSrc);
79018   sqlite3ExprDelete(db, p->pWhere);
79019   sqlite3ExprListDelete(db, p->pGroupBy);
79020   sqlite3ExprDelete(db, p->pHaving);
79021   sqlite3ExprListDelete(db, p->pOrderBy);
79022   sqlite3SelectDelete(db, p->pPrior);
79023   sqlite3ExprDelete(db, p->pLimit);
79024   sqlite3ExprDelete(db, p->pOffset);
79025 }
79026
79027 /*
79028 ** Initialize a SelectDest structure.
79029 */
79030 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
79031   pDest->eDest = (u8)eDest;
79032   pDest->iParm = iParm;
79033   pDest->affinity = 0;
79034   pDest->iMem = 0;
79035   pDest->nMem = 0;
79036 }
79037
79038
79039 /*
79040 ** Allocate a new Select structure and return a pointer to that
79041 ** structure.
79042 */
79043 SQLITE_PRIVATE Select *sqlite3SelectNew(
79044   Parse *pParse,        /* Parsing context */
79045   ExprList *pEList,     /* which columns to include in the result */
79046   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
79047   Expr *pWhere,         /* the WHERE clause */
79048   ExprList *pGroupBy,   /* the GROUP BY clause */
79049   Expr *pHaving,        /* the HAVING clause */
79050   ExprList *pOrderBy,   /* the ORDER BY clause */
79051   int isDistinct,       /* true if the DISTINCT keyword is present */
79052   Expr *pLimit,         /* LIMIT value.  NULL means not used */
79053   Expr *pOffset         /* OFFSET value.  NULL means no offset */
79054 ){
79055   Select *pNew;
79056   Select standin;
79057   sqlite3 *db = pParse->db;
79058   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
79059   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
79060   if( pNew==0 ){
79061     pNew = &standin;
79062     memset(pNew, 0, sizeof(*pNew));
79063   }
79064   if( pEList==0 ){
79065     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
79066   }
79067   pNew->pEList = pEList;
79068   pNew->pSrc = pSrc;
79069   pNew->pWhere = pWhere;
79070   pNew->pGroupBy = pGroupBy;
79071   pNew->pHaving = pHaving;
79072   pNew->pOrderBy = pOrderBy;
79073   pNew->selFlags = isDistinct ? SF_Distinct : 0;
79074   pNew->op = TK_SELECT;
79075   pNew->pLimit = pLimit;
79076   pNew->pOffset = pOffset;
79077   assert( pOffset==0 || pLimit!=0 );
79078   pNew->addrOpenEphm[0] = -1;
79079   pNew->addrOpenEphm[1] = -1;
79080   pNew->addrOpenEphm[2] = -1;
79081   if( db->mallocFailed ) {
79082     clearSelect(db, pNew);
79083     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
79084     pNew = 0;
79085   }
79086   return pNew;
79087 }
79088
79089 /*
79090 ** Delete the given Select structure and all of its substructures.
79091 */
79092 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
79093   if( p ){
79094     clearSelect(db, p);
79095     sqlite3DbFree(db, p);
79096   }
79097 }
79098
79099 /*
79100 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
79101 ** type of join.  Return an integer constant that expresses that type
79102 ** in terms of the following bit values:
79103 **
79104 **     JT_INNER
79105 **     JT_CROSS
79106 **     JT_OUTER
79107 **     JT_NATURAL
79108 **     JT_LEFT
79109 **     JT_RIGHT
79110 **
79111 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
79112 **
79113 ** If an illegal or unsupported join type is seen, then still return
79114 ** a join type, but put an error in the pParse structure.
79115 */
79116 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
79117   int jointype = 0;
79118   Token *apAll[3];
79119   Token *p;
79120                              /*   0123456789 123456789 123456789 123 */
79121   static const char zKeyText[] = "naturaleftouterightfullinnercross";
79122   static const struct {
79123     u8 i;        /* Beginning of keyword text in zKeyText[] */
79124     u8 nChar;    /* Length of the keyword in characters */
79125     u8 code;     /* Join type mask */
79126   } aKeyword[] = {
79127     /* natural */ { 0,  7, JT_NATURAL                },
79128     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
79129     /* outer   */ { 10, 5, JT_OUTER                  },
79130     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
79131     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
79132     /* inner   */ { 23, 5, JT_INNER                  },
79133     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
79134   };
79135   int i, j;
79136   apAll[0] = pA;
79137   apAll[1] = pB;
79138   apAll[2] = pC;
79139   for(i=0; i<3 && apAll[i]; i++){
79140     p = apAll[i];
79141     for(j=0; j<ArraySize(aKeyword); j++){
79142       if( p->n==aKeyword[j].nChar 
79143           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
79144         jointype |= aKeyword[j].code;
79145         break;
79146       }
79147     }
79148     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
79149     if( j>=ArraySize(aKeyword) ){
79150       jointype |= JT_ERROR;
79151       break;
79152     }
79153   }
79154   if(
79155      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
79156      (jointype & JT_ERROR)!=0
79157   ){
79158     const char *zSp = " ";
79159     assert( pB!=0 );
79160     if( pC==0 ){ zSp++; }
79161     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
79162        "%T %T%s%T", pA, pB, zSp, pC);
79163     jointype = JT_INNER;
79164   }else if( (jointype & JT_OUTER)!=0 
79165          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
79166     sqlite3ErrorMsg(pParse, 
79167       "RIGHT and FULL OUTER JOINs are not currently supported");
79168     jointype = JT_INNER;
79169   }
79170   return jointype;
79171 }
79172
79173 /*
79174 ** Return the index of a column in a table.  Return -1 if the column
79175 ** is not contained in the table.
79176 */
79177 static int columnIndex(Table *pTab, const char *zCol){
79178   int i;
79179   for(i=0; i<pTab->nCol; i++){
79180     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
79181   }
79182   return -1;
79183 }
79184
79185 /*
79186 ** Search the first N tables in pSrc, from left to right, looking for a
79187 ** table that has a column named zCol.  
79188 **
79189 ** When found, set *piTab and *piCol to the table index and column index
79190 ** of the matching column and return TRUE.
79191 **
79192 ** If not found, return FALSE.
79193 */
79194 static int tableAndColumnIndex(
79195   SrcList *pSrc,       /* Array of tables to search */
79196   int N,               /* Number of tables in pSrc->a[] to search */
79197   const char *zCol,    /* Name of the column we are looking for */
79198   int *piTab,          /* Write index of pSrc->a[] here */
79199   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
79200 ){
79201   int i;               /* For looping over tables in pSrc */
79202   int iCol;            /* Index of column matching zCol */
79203
79204   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
79205   for(i=0; i<N; i++){
79206     iCol = columnIndex(pSrc->a[i].pTab, zCol);
79207     if( iCol>=0 ){
79208       if( piTab ){
79209         *piTab = i;
79210         *piCol = iCol;
79211       }
79212       return 1;
79213     }
79214   }
79215   return 0;
79216 }
79217
79218 /*
79219 ** This function is used to add terms implied by JOIN syntax to the
79220 ** WHERE clause expression of a SELECT statement. The new term, which
79221 ** is ANDed with the existing WHERE clause, is of the form:
79222 **
79223 **    (tab1.col1 = tab2.col2)
79224 **
79225 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
79226 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
79227 ** column iColRight of tab2.
79228 */
79229 static void addWhereTerm(
79230   Parse *pParse,                  /* Parsing context */
79231   SrcList *pSrc,                  /* List of tables in FROM clause */
79232   int iLeft,                      /* Index of first table to join in pSrc */
79233   int iColLeft,                   /* Index of column in first table */
79234   int iRight,                     /* Index of second table in pSrc */
79235   int iColRight,                  /* Index of column in second table */
79236   int isOuterJoin,                /* True if this is an OUTER join */
79237   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
79238 ){
79239   sqlite3 *db = pParse->db;
79240   Expr *pE1;
79241   Expr *pE2;
79242   Expr *pEq;
79243
79244   assert( iLeft<iRight );
79245   assert( pSrc->nSrc>iRight );
79246   assert( pSrc->a[iLeft].pTab );
79247   assert( pSrc->a[iRight].pTab );
79248
79249   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
79250   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
79251
79252   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
79253   if( pEq && isOuterJoin ){
79254     ExprSetProperty(pEq, EP_FromJoin);
79255     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
79256     ExprSetIrreducible(pEq);
79257     pEq->iRightJoinTable = (i16)pE2->iTable;
79258   }
79259   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
79260 }
79261
79262 /*
79263 ** Set the EP_FromJoin property on all terms of the given expression.
79264 ** And set the Expr.iRightJoinTable to iTable for every term in the
79265 ** expression.
79266 **
79267 ** The EP_FromJoin property is used on terms of an expression to tell
79268 ** the LEFT OUTER JOIN processing logic that this term is part of the
79269 ** join restriction specified in the ON or USING clause and not a part
79270 ** of the more general WHERE clause.  These terms are moved over to the
79271 ** WHERE clause during join processing but we need to remember that they
79272 ** originated in the ON or USING clause.
79273 **
79274 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
79275 ** expression depends on table iRightJoinTable even if that table is not
79276 ** explicitly mentioned in the expression.  That information is needed
79277 ** for cases like this:
79278 **
79279 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
79280 **
79281 ** The where clause needs to defer the handling of the t1.x=5
79282 ** term until after the t2 loop of the join.  In that way, a
79283 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
79284 ** defer the handling of t1.x=5, it will be processed immediately
79285 ** after the t1 loop and rows with t1.x!=5 will never appear in
79286 ** the output, which is incorrect.
79287 */
79288 static void setJoinExpr(Expr *p, int iTable){
79289   while( p ){
79290     ExprSetProperty(p, EP_FromJoin);
79291     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
79292     ExprSetIrreducible(p);
79293     p->iRightJoinTable = (i16)iTable;
79294     setJoinExpr(p->pLeft, iTable);
79295     p = p->pRight;
79296   } 
79297 }
79298
79299 /*
79300 ** This routine processes the join information for a SELECT statement.
79301 ** ON and USING clauses are converted into extra terms of the WHERE clause.
79302 ** NATURAL joins also create extra WHERE clause terms.
79303 **
79304 ** The terms of a FROM clause are contained in the Select.pSrc structure.
79305 ** The left most table is the first entry in Select.pSrc.  The right-most
79306 ** table is the last entry.  The join operator is held in the entry to
79307 ** the left.  Thus entry 0 contains the join operator for the join between
79308 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
79309 ** also attached to the left entry.
79310 **
79311 ** This routine returns the number of errors encountered.
79312 */
79313 static int sqliteProcessJoin(Parse *pParse, Select *p){
79314   SrcList *pSrc;                  /* All tables in the FROM clause */
79315   int i, j;                       /* Loop counters */
79316   struct SrcList_item *pLeft;     /* Left table being joined */
79317   struct SrcList_item *pRight;    /* Right table being joined */
79318
79319   pSrc = p->pSrc;
79320   pLeft = &pSrc->a[0];
79321   pRight = &pLeft[1];
79322   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
79323     Table *pLeftTab = pLeft->pTab;
79324     Table *pRightTab = pRight->pTab;
79325     int isOuter;
79326
79327     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
79328     isOuter = (pRight->jointype & JT_OUTER)!=0;
79329
79330     /* When the NATURAL keyword is present, add WHERE clause terms for
79331     ** every column that the two tables have in common.
79332     */
79333     if( pRight->jointype & JT_NATURAL ){
79334       if( pRight->pOn || pRight->pUsing ){
79335         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
79336            "an ON or USING clause", 0);
79337         return 1;
79338       }
79339       for(j=0; j<pRightTab->nCol; j++){
79340         char *zName;   /* Name of column in the right table */
79341         int iLeft;     /* Matching left table */
79342         int iLeftCol;  /* Matching column in the left table */
79343
79344         zName = pRightTab->aCol[j].zName;
79345         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
79346           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
79347                        isOuter, &p->pWhere);
79348         }
79349       }
79350     }
79351
79352     /* Disallow both ON and USING clauses in the same join
79353     */
79354     if( pRight->pOn && pRight->pUsing ){
79355       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
79356         "clauses in the same join");
79357       return 1;
79358     }
79359
79360     /* Add the ON clause to the end of the WHERE clause, connected by
79361     ** an AND operator.
79362     */
79363     if( pRight->pOn ){
79364       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
79365       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
79366       pRight->pOn = 0;
79367     }
79368
79369     /* Create extra terms on the WHERE clause for each column named
79370     ** in the USING clause.  Example: If the two tables to be joined are 
79371     ** A and B and the USING clause names X, Y, and Z, then add this
79372     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
79373     ** Report an error if any column mentioned in the USING clause is
79374     ** not contained in both tables to be joined.
79375     */
79376     if( pRight->pUsing ){
79377       IdList *pList = pRight->pUsing;
79378       for(j=0; j<pList->nId; j++){
79379         char *zName;     /* Name of the term in the USING clause */
79380         int iLeft;       /* Table on the left with matching column name */
79381         int iLeftCol;    /* Column number of matching column on the left */
79382         int iRightCol;   /* Column number of matching column on the right */
79383
79384         zName = pList->a[j].zName;
79385         iRightCol = columnIndex(pRightTab, zName);
79386         if( iRightCol<0
79387          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
79388         ){
79389           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
79390             "not present in both tables", zName);
79391           return 1;
79392         }
79393         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
79394                      isOuter, &p->pWhere);
79395       }
79396     }
79397   }
79398   return 0;
79399 }
79400
79401 /*
79402 ** Insert code into "v" that will push the record on the top of the
79403 ** stack into the sorter.
79404 */
79405 static void pushOntoSorter(
79406   Parse *pParse,         /* Parser context */
79407   ExprList *pOrderBy,    /* The ORDER BY clause */
79408   Select *pSelect,       /* The whole SELECT statement */
79409   int regData            /* Register holding data to be sorted */
79410 ){
79411   Vdbe *v = pParse->pVdbe;
79412   int nExpr = pOrderBy->nExpr;
79413   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
79414   int regRecord = sqlite3GetTempReg(pParse);
79415   sqlite3ExprCacheClear(pParse);
79416   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
79417   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
79418   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
79419   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
79420   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
79421   sqlite3ReleaseTempReg(pParse, regRecord);
79422   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
79423   if( pSelect->iLimit ){
79424     int addr1, addr2;
79425     int iLimit;
79426     if( pSelect->iOffset ){
79427       iLimit = pSelect->iOffset+1;
79428     }else{
79429       iLimit = pSelect->iLimit;
79430     }
79431     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
79432     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
79433     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
79434     sqlite3VdbeJumpHere(v, addr1);
79435     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
79436     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
79437     sqlite3VdbeJumpHere(v, addr2);
79438     pSelect->iLimit = 0;
79439   }
79440 }
79441
79442 /*
79443 ** Add code to implement the OFFSET
79444 */
79445 static void codeOffset(
79446   Vdbe *v,          /* Generate code into this VM */
79447   Select *p,        /* The SELECT statement being coded */
79448   int iContinue     /* Jump here to skip the current record */
79449 ){
79450   if( p->iOffset && iContinue!=0 ){
79451     int addr;
79452     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
79453     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
79454     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
79455     VdbeComment((v, "skip OFFSET records"));
79456     sqlite3VdbeJumpHere(v, addr);
79457   }
79458 }
79459
79460 /*
79461 ** Add code that will check to make sure the N registers starting at iMem
79462 ** form a distinct entry.  iTab is a sorting index that holds previously
79463 ** seen combinations of the N values.  A new entry is made in iTab
79464 ** if the current N values are new.
79465 **
79466 ** A jump to addrRepeat is made and the N+1 values are popped from the
79467 ** stack if the top N elements are not distinct.
79468 */
79469 static void codeDistinct(
79470   Parse *pParse,     /* Parsing and code generating context */
79471   int iTab,          /* A sorting index used to test for distinctness */
79472   int addrRepeat,    /* Jump to here if not distinct */
79473   int N,             /* Number of elements */
79474   int iMem           /* First element */
79475 ){
79476   Vdbe *v;
79477   int r1;
79478
79479   v = pParse->pVdbe;
79480   r1 = sqlite3GetTempReg(pParse);
79481   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
79482   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
79483   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
79484   sqlite3ReleaseTempReg(pParse, r1);
79485 }
79486
79487 /*
79488 ** Generate an error message when a SELECT is used within a subexpression
79489 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
79490 ** column.  We do this in a subroutine because the error occurs in multiple
79491 ** places.
79492 */
79493 static int checkForMultiColumnSelectError(
79494   Parse *pParse,       /* Parse context. */
79495   SelectDest *pDest,   /* Destination of SELECT results */
79496   int nExpr            /* Number of result columns returned by SELECT */
79497 ){
79498   int eDest = pDest->eDest;
79499   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
79500     sqlite3ErrorMsg(pParse, "only a single result allowed for "
79501        "a SELECT that is part of an expression");
79502     return 1;
79503   }else{
79504     return 0;
79505   }
79506 }
79507
79508 /*
79509 ** This routine generates the code for the inside of the inner loop
79510 ** of a SELECT.
79511 **
79512 ** If srcTab and nColumn are both zero, then the pEList expressions
79513 ** are evaluated in order to get the data for this row.  If nColumn>0
79514 ** then data is pulled from srcTab and pEList is used only to get the
79515 ** datatypes for each column.
79516 */
79517 static void selectInnerLoop(
79518   Parse *pParse,          /* The parser context */
79519   Select *p,              /* The complete select statement being coded */
79520   ExprList *pEList,       /* List of values being extracted */
79521   int srcTab,             /* Pull data from this table */
79522   int nColumn,            /* Number of columns in the source table */
79523   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
79524   int distinct,           /* If >=0, make sure results are distinct */
79525   SelectDest *pDest,      /* How to dispose of the results */
79526   int iContinue,          /* Jump here to continue with next row */
79527   int iBreak              /* Jump here to break out of the inner loop */
79528 ){
79529   Vdbe *v = pParse->pVdbe;
79530   int i;
79531   int hasDistinct;        /* True if the DISTINCT keyword is present */
79532   int regResult;              /* Start of memory holding result set */
79533   int eDest = pDest->eDest;   /* How to dispose of results */
79534   int iParm = pDest->iParm;   /* First argument to disposal method */
79535   int nResultCol;             /* Number of result columns */
79536
79537   assert( v );
79538   if( NEVER(v==0) ) return;
79539   assert( pEList!=0 );
79540   hasDistinct = distinct>=0;
79541   if( pOrderBy==0 && !hasDistinct ){
79542     codeOffset(v, p, iContinue);
79543   }
79544
79545   /* Pull the requested columns.
79546   */
79547   if( nColumn>0 ){
79548     nResultCol = nColumn;
79549   }else{
79550     nResultCol = pEList->nExpr;
79551   }
79552   if( pDest->iMem==0 ){
79553     pDest->iMem = pParse->nMem+1;
79554     pDest->nMem = nResultCol;
79555     pParse->nMem += nResultCol;
79556   }else{ 
79557     assert( pDest->nMem==nResultCol );
79558   }
79559   regResult = pDest->iMem;
79560   if( nColumn>0 ){
79561     for(i=0; i<nColumn; i++){
79562       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
79563     }
79564   }else if( eDest!=SRT_Exists ){
79565     /* If the destination is an EXISTS(...) expression, the actual
79566     ** values returned by the SELECT are not required.
79567     */
79568     sqlite3ExprCacheClear(pParse);
79569     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
79570   }
79571   nColumn = nResultCol;
79572
79573   /* If the DISTINCT keyword was present on the SELECT statement
79574   ** and this row has been seen before, then do not make this row
79575   ** part of the result.
79576   */
79577   if( hasDistinct ){
79578     assert( pEList!=0 );
79579     assert( pEList->nExpr==nColumn );
79580     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
79581     if( pOrderBy==0 ){
79582       codeOffset(v, p, iContinue);
79583     }
79584   }
79585
79586   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
79587     return;
79588   }
79589
79590   switch( eDest ){
79591     /* In this mode, write each query result to the key of the temporary
79592     ** table iParm.
79593     */
79594 #ifndef SQLITE_OMIT_COMPOUND_SELECT
79595     case SRT_Union: {
79596       int r1;
79597       r1 = sqlite3GetTempReg(pParse);
79598       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
79599       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
79600       sqlite3ReleaseTempReg(pParse, r1);
79601       break;
79602     }
79603
79604     /* Construct a record from the query result, but instead of
79605     ** saving that record, use it as a key to delete elements from
79606     ** the temporary table iParm.
79607     */
79608     case SRT_Except: {
79609       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
79610       break;
79611     }
79612 #endif
79613
79614     /* Store the result as data using a unique key.
79615     */
79616     case SRT_Table:
79617     case SRT_EphemTab: {
79618       int r1 = sqlite3GetTempReg(pParse);
79619       testcase( eDest==SRT_Table );
79620       testcase( eDest==SRT_EphemTab );
79621       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
79622       if( pOrderBy ){
79623         pushOntoSorter(pParse, pOrderBy, p, r1);
79624       }else{
79625         int r2 = sqlite3GetTempReg(pParse);
79626         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
79627         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
79628         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79629         sqlite3ReleaseTempReg(pParse, r2);
79630       }
79631       sqlite3ReleaseTempReg(pParse, r1);
79632       break;
79633     }
79634
79635 #ifndef SQLITE_OMIT_SUBQUERY
79636     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
79637     ** then there should be a single item on the stack.  Write this
79638     ** item into the set table with bogus data.
79639     */
79640     case SRT_Set: {
79641       assert( nColumn==1 );
79642       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
79643       if( pOrderBy ){
79644         /* At first glance you would think we could optimize out the
79645         ** ORDER BY in this case since the order of entries in the set
79646         ** does not matter.  But there might be a LIMIT clause, in which
79647         ** case the order does matter */
79648         pushOntoSorter(pParse, pOrderBy, p, regResult);
79649       }else{
79650         int r1 = sqlite3GetTempReg(pParse);
79651         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
79652         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
79653         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
79654         sqlite3ReleaseTempReg(pParse, r1);
79655       }
79656       break;
79657     }
79658
79659     /* If any row exist in the result set, record that fact and abort.
79660     */
79661     case SRT_Exists: {
79662       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
79663       /* The LIMIT clause will terminate the loop for us */
79664       break;
79665     }
79666
79667     /* If this is a scalar select that is part of an expression, then
79668     ** store the results in the appropriate memory cell and break out
79669     ** of the scan loop.
79670     */
79671     case SRT_Mem: {
79672       assert( nColumn==1 );
79673       if( pOrderBy ){
79674         pushOntoSorter(pParse, pOrderBy, p, regResult);
79675       }else{
79676         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
79677         /* The LIMIT clause will jump out of the loop for us */
79678       }
79679       break;
79680     }
79681 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
79682
79683     /* Send the data to the callback function or to a subroutine.  In the
79684     ** case of a subroutine, the subroutine itself is responsible for
79685     ** popping the data from the stack.
79686     */
79687     case SRT_Coroutine:
79688     case SRT_Output: {
79689       testcase( eDest==SRT_Coroutine );
79690       testcase( eDest==SRT_Output );
79691       if( pOrderBy ){
79692         int r1 = sqlite3GetTempReg(pParse);
79693         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
79694         pushOntoSorter(pParse, pOrderBy, p, r1);
79695         sqlite3ReleaseTempReg(pParse, r1);
79696       }else if( eDest==SRT_Coroutine ){
79697         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
79698       }else{
79699         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
79700         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
79701       }
79702       break;
79703     }
79704
79705 #if !defined(SQLITE_OMIT_TRIGGER)
79706     /* Discard the results.  This is used for SELECT statements inside
79707     ** the body of a TRIGGER.  The purpose of such selects is to call
79708     ** user-defined functions that have side effects.  We do not care
79709     ** about the actual results of the select.
79710     */
79711     default: {
79712       assert( eDest==SRT_Discard );
79713       break;
79714     }
79715 #endif
79716   }
79717
79718   /* Jump to the end of the loop if the LIMIT is reached.
79719   */
79720   if( p->iLimit ){
79721     assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
79722                             ** pushOntoSorter() would have cleared p->iLimit */
79723     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
79724   }
79725 }
79726
79727 /*
79728 ** Given an expression list, generate a KeyInfo structure that records
79729 ** the collating sequence for each expression in that expression list.
79730 **
79731 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
79732 ** KeyInfo structure is appropriate for initializing a virtual index to
79733 ** implement that clause.  If the ExprList is the result set of a SELECT
79734 ** then the KeyInfo structure is appropriate for initializing a virtual
79735 ** index to implement a DISTINCT test.
79736 **
79737 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
79738 ** function is responsible for seeing that this structure is eventually
79739 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
79740 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
79741 */
79742 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
79743   sqlite3 *db = pParse->db;
79744   int nExpr;
79745   KeyInfo *pInfo;
79746   struct ExprList_item *pItem;
79747   int i;
79748
79749   nExpr = pList->nExpr;
79750   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
79751   if( pInfo ){
79752     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
79753     pInfo->nField = (u16)nExpr;
79754     pInfo->enc = ENC(db);
79755     pInfo->db = db;
79756     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
79757       CollSeq *pColl;
79758       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
79759       if( !pColl ){
79760         pColl = db->pDfltColl;
79761       }
79762       pInfo->aColl[i] = pColl;
79763       pInfo->aSortOrder[i] = pItem->sortOrder;
79764     }
79765   }
79766   return pInfo;
79767 }
79768
79769
79770 /*
79771 ** If the inner loop was generated using a non-null pOrderBy argument,
79772 ** then the results were placed in a sorter.  After the loop is terminated
79773 ** we need to run the sorter and output the results.  The following
79774 ** routine generates the code needed to do that.
79775 */
79776 static void generateSortTail(
79777   Parse *pParse,    /* Parsing context */
79778   Select *p,        /* The SELECT statement */
79779   Vdbe *v,          /* Generate code into this VDBE */
79780   int nColumn,      /* Number of columns of data */
79781   SelectDest *pDest /* Write the sorted results here */
79782 ){
79783   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
79784   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
79785   int addr;
79786   int iTab;
79787   int pseudoTab = 0;
79788   ExprList *pOrderBy = p->pOrderBy;
79789
79790   int eDest = pDest->eDest;
79791   int iParm = pDest->iParm;
79792
79793   int regRow;
79794   int regRowid;
79795
79796   iTab = pOrderBy->iECursor;
79797   regRow = sqlite3GetTempReg(pParse);
79798   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
79799     pseudoTab = pParse->nTab++;
79800     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
79801     regRowid = 0;
79802   }else{
79803     regRowid = sqlite3GetTempReg(pParse);
79804   }
79805   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
79806   codeOffset(v, p, addrContinue);
79807   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
79808   switch( eDest ){
79809     case SRT_Table:
79810     case SRT_EphemTab: {
79811       testcase( eDest==SRT_Table );
79812       testcase( eDest==SRT_EphemTab );
79813       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
79814       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
79815       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79816       break;
79817     }
79818 #ifndef SQLITE_OMIT_SUBQUERY
79819     case SRT_Set: {
79820       assert( nColumn==1 );
79821       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
79822       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
79823       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
79824       break;
79825     }
79826     case SRT_Mem: {
79827       assert( nColumn==1 );
79828       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
79829       /* The LIMIT clause will terminate the loop for us */
79830       break;
79831     }
79832 #endif
79833     default: {
79834       int i;
79835       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
79836       testcase( eDest==SRT_Output );
79837       testcase( eDest==SRT_Coroutine );
79838       for(i=0; i<nColumn; i++){
79839         assert( regRow!=pDest->iMem+i );
79840         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
79841         if( i==0 ){
79842           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
79843         }
79844       }
79845       if( eDest==SRT_Output ){
79846         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
79847         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
79848       }else{
79849         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
79850       }
79851       break;
79852     }
79853   }
79854   sqlite3ReleaseTempReg(pParse, regRow);
79855   sqlite3ReleaseTempReg(pParse, regRowid);
79856
79857   /* LIMIT has been implemented by the pushOntoSorter() routine.
79858   */
79859   assert( p->iLimit==0 );
79860
79861   /* The bottom of the loop
79862   */
79863   sqlite3VdbeResolveLabel(v, addrContinue);
79864   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
79865   sqlite3VdbeResolveLabel(v, addrBreak);
79866   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
79867     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
79868   }
79869 }
79870
79871 /*
79872 ** Return a pointer to a string containing the 'declaration type' of the
79873 ** expression pExpr. The string may be treated as static by the caller.
79874 **
79875 ** The declaration type is the exact datatype definition extracted from the
79876 ** original CREATE TABLE statement if the expression is a column. The
79877 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
79878 ** is considered a column can be complex in the presence of subqueries. The
79879 ** result-set expression in all of the following SELECT statements is 
79880 ** considered a column by this function.
79881 **
79882 **   SELECT col FROM tbl;
79883 **   SELECT (SELECT col FROM tbl;
79884 **   SELECT (SELECT col FROM tbl);
79885 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
79886 ** 
79887 ** The declaration type for any expression other than a column is NULL.
79888 */
79889 static const char *columnType(
79890   NameContext *pNC, 
79891   Expr *pExpr,
79892   const char **pzOriginDb,
79893   const char **pzOriginTab,
79894   const char **pzOriginCol
79895 ){
79896   char const *zType = 0;
79897   char const *zOriginDb = 0;
79898   char const *zOriginTab = 0;
79899   char const *zOriginCol = 0;
79900   int j;
79901   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
79902
79903   switch( pExpr->op ){
79904     case TK_AGG_COLUMN:
79905     case TK_COLUMN: {
79906       /* The expression is a column. Locate the table the column is being
79907       ** extracted from in NameContext.pSrcList. This table may be real
79908       ** database table or a subquery.
79909       */
79910       Table *pTab = 0;            /* Table structure column is extracted from */
79911       Select *pS = 0;             /* Select the column is extracted from */
79912       int iCol = pExpr->iColumn;  /* Index of column in pTab */
79913       testcase( pExpr->op==TK_AGG_COLUMN );
79914       testcase( pExpr->op==TK_COLUMN );
79915       while( pNC && !pTab ){
79916         SrcList *pTabList = pNC->pSrcList;
79917         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
79918         if( j<pTabList->nSrc ){
79919           pTab = pTabList->a[j].pTab;
79920           pS = pTabList->a[j].pSelect;
79921         }else{
79922           pNC = pNC->pNext;
79923         }
79924       }
79925
79926       if( pTab==0 ){
79927         /* At one time, code such as "SELECT new.x" within a trigger would
79928         ** cause this condition to run.  Since then, we have restructured how
79929         ** trigger code is generated and so this condition is no longer 
79930         ** possible. However, it can still be true for statements like
79931         ** the following:
79932         **
79933         **   CREATE TABLE t1(col INTEGER);
79934         **   SELECT (SELECT t1.col) FROM FROM t1;
79935         **
79936         ** when columnType() is called on the expression "t1.col" in the 
79937         ** sub-select. In this case, set the column type to NULL, even
79938         ** though it should really be "INTEGER".
79939         **
79940         ** This is not a problem, as the column type of "t1.col" is never
79941         ** used. When columnType() is called on the expression 
79942         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
79943         ** branch below.  */
79944         break;
79945       }
79946
79947       assert( pTab && pExpr->pTab==pTab );
79948       if( pS ){
79949         /* The "table" is actually a sub-select or a view in the FROM clause
79950         ** of the SELECT statement. Return the declaration type and origin
79951         ** data for the result-set column of the sub-select.
79952         */
79953         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
79954           /* If iCol is less than zero, then the expression requests the
79955           ** rowid of the sub-select or view. This expression is legal (see 
79956           ** test case misc2.2.2) - it always evaluates to NULL.
79957           */
79958           NameContext sNC;
79959           Expr *p = pS->pEList->a[iCol].pExpr;
79960           sNC.pSrcList = pS->pSrc;
79961           sNC.pNext = pNC;
79962           sNC.pParse = pNC->pParse;
79963           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
79964         }
79965       }else if( ALWAYS(pTab->pSchema) ){
79966         /* A real table */
79967         assert( !pS );
79968         if( iCol<0 ) iCol = pTab->iPKey;
79969         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
79970         if( iCol<0 ){
79971           zType = "INTEGER";
79972           zOriginCol = "rowid";
79973         }else{
79974           zType = pTab->aCol[iCol].zType;
79975           zOriginCol = pTab->aCol[iCol].zName;
79976         }
79977         zOriginTab = pTab->zName;
79978         if( pNC->pParse ){
79979           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
79980           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
79981         }
79982       }
79983       break;
79984     }
79985 #ifndef SQLITE_OMIT_SUBQUERY
79986     case TK_SELECT: {
79987       /* The expression is a sub-select. Return the declaration type and
79988       ** origin info for the single column in the result set of the SELECT
79989       ** statement.
79990       */
79991       NameContext sNC;
79992       Select *pS = pExpr->x.pSelect;
79993       Expr *p = pS->pEList->a[0].pExpr;
79994       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
79995       sNC.pSrcList = pS->pSrc;
79996       sNC.pNext = pNC;
79997       sNC.pParse = pNC->pParse;
79998       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
79999       break;
80000     }
80001 #endif
80002   }
80003   
80004   if( pzOriginDb ){
80005     assert( pzOriginTab && pzOriginCol );
80006     *pzOriginDb = zOriginDb;
80007     *pzOriginTab = zOriginTab;
80008     *pzOriginCol = zOriginCol;
80009   }
80010   return zType;
80011 }
80012
80013 /*
80014 ** Generate code that will tell the VDBE the declaration types of columns
80015 ** in the result set.
80016 */
80017 static void generateColumnTypes(
80018   Parse *pParse,      /* Parser context */
80019   SrcList *pTabList,  /* List of tables */
80020   ExprList *pEList    /* Expressions defining the result set */
80021 ){
80022 #ifndef SQLITE_OMIT_DECLTYPE
80023   Vdbe *v = pParse->pVdbe;
80024   int i;
80025   NameContext sNC;
80026   sNC.pSrcList = pTabList;
80027   sNC.pParse = pParse;
80028   for(i=0; i<pEList->nExpr; i++){
80029     Expr *p = pEList->a[i].pExpr;
80030     const char *zType;
80031 #ifdef SQLITE_ENABLE_COLUMN_METADATA
80032     const char *zOrigDb = 0;
80033     const char *zOrigTab = 0;
80034     const char *zOrigCol = 0;
80035     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
80036
80037     /* The vdbe must make its own copy of the column-type and other 
80038     ** column specific strings, in case the schema is reset before this
80039     ** virtual machine is deleted.
80040     */
80041     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
80042     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
80043     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
80044 #else
80045     zType = columnType(&sNC, p, 0, 0, 0);
80046 #endif
80047     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
80048   }
80049 #endif /* SQLITE_OMIT_DECLTYPE */
80050 }
80051
80052 /*
80053 ** Generate code that will tell the VDBE the names of columns
80054 ** in the result set.  This information is used to provide the
80055 ** azCol[] values in the callback.
80056 */
80057 static void generateColumnNames(
80058   Parse *pParse,      /* Parser context */
80059   SrcList *pTabList,  /* List of tables */
80060   ExprList *pEList    /* Expressions defining the result set */
80061 ){
80062   Vdbe *v = pParse->pVdbe;
80063   int i, j;
80064   sqlite3 *db = pParse->db;
80065   int fullNames, shortNames;
80066
80067 #ifndef SQLITE_OMIT_EXPLAIN
80068   /* If this is an EXPLAIN, skip this step */
80069   if( pParse->explain ){
80070     return;
80071   }
80072 #endif
80073
80074   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
80075   pParse->colNamesSet = 1;
80076   fullNames = (db->flags & SQLITE_FullColNames)!=0;
80077   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
80078   sqlite3VdbeSetNumCols(v, pEList->nExpr);
80079   for(i=0; i<pEList->nExpr; i++){
80080     Expr *p;
80081     p = pEList->a[i].pExpr;
80082     if( NEVER(p==0) ) continue;
80083     if( pEList->a[i].zName ){
80084       char *zName = pEList->a[i].zName;
80085       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
80086     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
80087       Table *pTab;
80088       char *zCol;
80089       int iCol = p->iColumn;
80090       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
80091         if( pTabList->a[j].iCursor==p->iTable ) break;
80092       }
80093       assert( j<pTabList->nSrc );
80094       pTab = pTabList->a[j].pTab;
80095       if( iCol<0 ) iCol = pTab->iPKey;
80096       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
80097       if( iCol<0 ){
80098         zCol = "rowid";
80099       }else{
80100         zCol = pTab->aCol[iCol].zName;
80101       }
80102       if( !shortNames && !fullNames ){
80103         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
80104             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
80105       }else if( fullNames ){
80106         char *zName = 0;
80107         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
80108         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
80109       }else{
80110         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
80111       }
80112     }else{
80113       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
80114           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
80115     }
80116   }
80117   generateColumnTypes(pParse, pTabList, pEList);
80118 }
80119
80120 #ifndef SQLITE_OMIT_COMPOUND_SELECT
80121 /*
80122 ** Name of the connection operator, used for error messages.
80123 */
80124 static const char *selectOpName(int id){
80125   char *z;
80126   switch( id ){
80127     case TK_ALL:       z = "UNION ALL";   break;
80128     case TK_INTERSECT: z = "INTERSECT";   break;
80129     case TK_EXCEPT:    z = "EXCEPT";      break;
80130     default:           z = "UNION";       break;
80131   }
80132   return z;
80133 }
80134 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
80135
80136 /*
80137 ** Given a an expression list (which is really the list of expressions
80138 ** that form the result set of a SELECT statement) compute appropriate
80139 ** column names for a table that would hold the expression list.
80140 **
80141 ** All column names will be unique.
80142 **
80143 ** Only the column names are computed.  Column.zType, Column.zColl,
80144 ** and other fields of Column are zeroed.
80145 **
80146 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
80147 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
80148 */
80149 static int selectColumnsFromExprList(
80150   Parse *pParse,          /* Parsing context */
80151   ExprList *pEList,       /* Expr list from which to derive column names */
80152   int *pnCol,             /* Write the number of columns here */
80153   Column **paCol          /* Write the new column list here */
80154 ){
80155   sqlite3 *db = pParse->db;   /* Database connection */
80156   int i, j;                   /* Loop counters */
80157   int cnt;                    /* Index added to make the name unique */
80158   Column *aCol, *pCol;        /* For looping over result columns */
80159   int nCol;                   /* Number of columns in the result set */
80160   Expr *p;                    /* Expression for a single result column */
80161   char *zName;                /* Column name */
80162   int nName;                  /* Size of name in zName[] */
80163
80164   *pnCol = nCol = pEList->nExpr;
80165   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
80166   if( aCol==0 ) return SQLITE_NOMEM;
80167   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
80168     /* Get an appropriate name for the column
80169     */
80170     p = pEList->a[i].pExpr;
80171     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
80172                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
80173     if( (zName = pEList->a[i].zName)!=0 ){
80174       /* If the column contains an "AS <name>" phrase, use <name> as the name */
80175       zName = sqlite3DbStrDup(db, zName);
80176     }else{
80177       Expr *pColExpr = p;  /* The expression that is the result column name */
80178       Table *pTab;         /* Table associated with this expression */
80179       while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
80180       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
80181         /* For columns use the column name name */
80182         int iCol = pColExpr->iColumn;
80183         pTab = pColExpr->pTab;
80184         if( iCol<0 ) iCol = pTab->iPKey;
80185         zName = sqlite3MPrintf(db, "%s",
80186                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
80187       }else if( pColExpr->op==TK_ID ){
80188         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
80189         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
80190       }else{
80191         /* Use the original text of the column expression as its name */
80192         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
80193       }
80194     }
80195     if( db->mallocFailed ){
80196       sqlite3DbFree(db, zName);
80197       break;
80198     }
80199
80200     /* Make sure the column name is unique.  If the name is not unique,
80201     ** append a integer to the name so that it becomes unique.
80202     */
80203     nName = sqlite3Strlen30(zName);
80204     for(j=cnt=0; j<i; j++){
80205       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
80206         char *zNewName;
80207         zName[nName] = 0;
80208         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
80209         sqlite3DbFree(db, zName);
80210         zName = zNewName;
80211         j = -1;
80212         if( zName==0 ) break;
80213       }
80214     }
80215     pCol->zName = zName;
80216   }
80217   if( db->mallocFailed ){
80218     for(j=0; j<i; j++){
80219       sqlite3DbFree(db, aCol[j].zName);
80220     }
80221     sqlite3DbFree(db, aCol);
80222     *paCol = 0;
80223     *pnCol = 0;
80224     return SQLITE_NOMEM;
80225   }
80226   return SQLITE_OK;
80227 }
80228
80229 /*
80230 ** Add type and collation information to a column list based on
80231 ** a SELECT statement.
80232 ** 
80233 ** The column list presumably came from selectColumnNamesFromExprList().
80234 ** The column list has only names, not types or collations.  This
80235 ** routine goes through and adds the types and collations.
80236 **
80237 ** This routine requires that all identifiers in the SELECT
80238 ** statement be resolved.
80239 */
80240 static void selectAddColumnTypeAndCollation(
80241   Parse *pParse,        /* Parsing contexts */
80242   int nCol,             /* Number of columns */
80243   Column *aCol,         /* List of columns */
80244   Select *pSelect       /* SELECT used to determine types and collations */
80245 ){
80246   sqlite3 *db = pParse->db;
80247   NameContext sNC;
80248   Column *pCol;
80249   CollSeq *pColl;
80250   int i;
80251   Expr *p;
80252   struct ExprList_item *a;
80253
80254   assert( pSelect!=0 );
80255   assert( (pSelect->selFlags & SF_Resolved)!=0 );
80256   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
80257   if( db->mallocFailed ) return;
80258   memset(&sNC, 0, sizeof(sNC));
80259   sNC.pSrcList = pSelect->pSrc;
80260   a = pSelect->pEList->a;
80261   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
80262     p = a[i].pExpr;
80263     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
80264     pCol->affinity = sqlite3ExprAffinity(p);
80265     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
80266     pColl = sqlite3ExprCollSeq(pParse, p);
80267     if( pColl ){
80268       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
80269     }
80270   }
80271 }
80272
80273 /*
80274 ** Given a SELECT statement, generate a Table structure that describes
80275 ** the result set of that SELECT.
80276 */
80277 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
80278   Table *pTab;
80279   sqlite3 *db = pParse->db;
80280   int savedFlags;
80281
80282   savedFlags = db->flags;
80283   db->flags &= ~SQLITE_FullColNames;
80284   db->flags |= SQLITE_ShortColNames;
80285   sqlite3SelectPrep(pParse, pSelect, 0);
80286   if( pParse->nErr ) return 0;
80287   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
80288   db->flags = savedFlags;
80289   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
80290   if( pTab==0 ){
80291     return 0;
80292   }
80293   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
80294   ** is disabled, so we might as well hard-code pTab->dbMem to NULL. */
80295   assert( db->lookaside.bEnabled==0 );
80296   pTab->dbMem = 0;
80297   pTab->nRef = 1;
80298   pTab->zName = 0;
80299   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
80300   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
80301   pTab->iPKey = -1;
80302   if( db->mallocFailed ){
80303     sqlite3DeleteTable(pTab);
80304     return 0;
80305   }
80306   return pTab;
80307 }
80308
80309 /*
80310 ** Get a VDBE for the given parser context.  Create a new one if necessary.
80311 ** If an error occurs, return NULL and leave a message in pParse.
80312 */
80313 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
80314   Vdbe *v = pParse->pVdbe;
80315   if( v==0 ){
80316     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
80317 #ifndef SQLITE_OMIT_TRACE
80318     if( v ){
80319       sqlite3VdbeAddOp0(v, OP_Trace);
80320     }
80321 #endif
80322   }
80323   return v;
80324 }
80325
80326
80327 /*
80328 ** Compute the iLimit and iOffset fields of the SELECT based on the
80329 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
80330 ** that appear in the original SQL statement after the LIMIT and OFFSET
80331 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
80332 ** are the integer memory register numbers for counters used to compute 
80333 ** the limit and offset.  If there is no limit and/or offset, then 
80334 ** iLimit and iOffset are negative.
80335 **
80336 ** This routine changes the values of iLimit and iOffset only if
80337 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
80338 ** iOffset should have been preset to appropriate default values
80339 ** (usually but not always -1) prior to calling this routine.
80340 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
80341 ** redefined.  The UNION ALL operator uses this property to force
80342 ** the reuse of the same limit and offset registers across multiple
80343 ** SELECT statements.
80344 */
80345 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
80346   Vdbe *v = 0;
80347   int iLimit = 0;
80348   int iOffset;
80349   int addr1, n;
80350   if( p->iLimit ) return;
80351
80352   /* 
80353   ** "LIMIT -1" always shows all rows.  There is some
80354   ** contraversy about what the correct behavior should be.
80355   ** The current implementation interprets "LIMIT 0" to mean
80356   ** no rows.
80357   */
80358   sqlite3ExprCacheClear(pParse);
80359   assert( p->pOffset==0 || p->pLimit!=0 );
80360   if( p->pLimit ){
80361     p->iLimit = iLimit = ++pParse->nMem;
80362     v = sqlite3GetVdbe(pParse);
80363     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
80364     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
80365       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
80366       VdbeComment((v, "LIMIT counter"));
80367       if( n==0 ){
80368         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
80369       }
80370     }else{
80371       sqlite3ExprCode(pParse, p->pLimit, iLimit);
80372       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
80373       VdbeComment((v, "LIMIT counter"));
80374       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
80375     }
80376     if( p->pOffset ){
80377       p->iOffset = iOffset = ++pParse->nMem;
80378       pParse->nMem++;   /* Allocate an extra register for limit+offset */
80379       sqlite3ExprCode(pParse, p->pOffset, iOffset);
80380       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
80381       VdbeComment((v, "OFFSET counter"));
80382       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
80383       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
80384       sqlite3VdbeJumpHere(v, addr1);
80385       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
80386       VdbeComment((v, "LIMIT+OFFSET"));
80387       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
80388       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
80389       sqlite3VdbeJumpHere(v, addr1);
80390     }
80391   }
80392 }
80393
80394 #ifndef SQLITE_OMIT_COMPOUND_SELECT
80395 /*
80396 ** Return the appropriate collating sequence for the iCol-th column of
80397 ** the result set for the compound-select statement "p".  Return NULL if
80398 ** the column has no default collating sequence.
80399 **
80400 ** The collating sequence for the compound select is taken from the
80401 ** left-most term of the select that has a collating sequence.
80402 */
80403 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
80404   CollSeq *pRet;
80405   if( p->pPrior ){
80406     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
80407   }else{
80408     pRet = 0;
80409   }
80410   assert( iCol>=0 );
80411   if( pRet==0 && iCol<p->pEList->nExpr ){
80412     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
80413   }
80414   return pRet;
80415 }
80416 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
80417
80418 /* Forward reference */
80419 static int multiSelectOrderBy(
80420   Parse *pParse,        /* Parsing context */
80421   Select *p,            /* The right-most of SELECTs to be coded */
80422   SelectDest *pDest     /* What to do with query results */
80423 );
80424
80425
80426 #ifndef SQLITE_OMIT_COMPOUND_SELECT
80427 /*
80428 ** This routine is called to process a compound query form from
80429 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
80430 ** INTERSECT
80431 **
80432 ** "p" points to the right-most of the two queries.  the query on the
80433 ** left is p->pPrior.  The left query could also be a compound query
80434 ** in which case this routine will be called recursively. 
80435 **
80436 ** The results of the total query are to be written into a destination
80437 ** of type eDest with parameter iParm.
80438 **
80439 ** Example 1:  Consider a three-way compound SQL statement.
80440 **
80441 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
80442 **
80443 ** This statement is parsed up as follows:
80444 **
80445 **     SELECT c FROM t3
80446 **      |
80447 **      `----->  SELECT b FROM t2
80448 **                |
80449 **                `------>  SELECT a FROM t1
80450 **
80451 ** The arrows in the diagram above represent the Select.pPrior pointer.
80452 ** So if this routine is called with p equal to the t3 query, then
80453 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
80454 **
80455 ** Notice that because of the way SQLite parses compound SELECTs, the
80456 ** individual selects always group from left to right.
80457 */
80458 static int multiSelect(
80459   Parse *pParse,        /* Parsing context */
80460   Select *p,            /* The right-most of SELECTs to be coded */
80461   SelectDest *pDest     /* What to do with query results */
80462 ){
80463   int rc = SQLITE_OK;   /* Success code from a subroutine */
80464   Select *pPrior;       /* Another SELECT immediately to our left */
80465   Vdbe *v;              /* Generate code to this VDBE */
80466   SelectDest dest;      /* Alternative data destination */
80467   Select *pDelete = 0;  /* Chain of simple selects to delete */
80468   sqlite3 *db;          /* Database connection */
80469
80470   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
80471   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
80472   */
80473   assert( p && p->pPrior );  /* Calling function guarantees this much */
80474   db = pParse->db;
80475   pPrior = p->pPrior;
80476   assert( pPrior->pRightmost!=pPrior );
80477   assert( pPrior->pRightmost==p->pRightmost );
80478   dest = *pDest;
80479   if( pPrior->pOrderBy ){
80480     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
80481       selectOpName(p->op));
80482     rc = 1;
80483     goto multi_select_end;
80484   }
80485   if( pPrior->pLimit ){
80486     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
80487       selectOpName(p->op));
80488     rc = 1;
80489     goto multi_select_end;
80490   }
80491
80492   v = sqlite3GetVdbe(pParse);
80493   assert( v!=0 );  /* The VDBE already created by calling function */
80494
80495   /* Create the destination temporary table if necessary
80496   */
80497   if( dest.eDest==SRT_EphemTab ){
80498     assert( p->pEList );
80499     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
80500     dest.eDest = SRT_Table;
80501   }
80502
80503   /* Make sure all SELECTs in the statement have the same number of elements
80504   ** in their result sets.
80505   */
80506   assert( p->pEList && pPrior->pEList );
80507   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
80508     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
80509       " do not have the same number of result columns", selectOpName(p->op));
80510     rc = 1;
80511     goto multi_select_end;
80512   }
80513
80514   /* Compound SELECTs that have an ORDER BY clause are handled separately.
80515   */
80516   if( p->pOrderBy ){
80517     return multiSelectOrderBy(pParse, p, pDest);
80518   }
80519
80520   /* Generate code for the left and right SELECT statements.
80521   */
80522   switch( p->op ){
80523     case TK_ALL: {
80524       int addr = 0;
80525       assert( !pPrior->pLimit );
80526       pPrior->pLimit = p->pLimit;
80527       pPrior->pOffset = p->pOffset;
80528       rc = sqlite3Select(pParse, pPrior, &dest);
80529       p->pLimit = 0;
80530       p->pOffset = 0;
80531       if( rc ){
80532         goto multi_select_end;
80533       }
80534       p->pPrior = 0;
80535       p->iLimit = pPrior->iLimit;
80536       p->iOffset = pPrior->iOffset;
80537       if( p->iLimit ){
80538         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
80539         VdbeComment((v, "Jump ahead if LIMIT reached"));
80540       }
80541       rc = sqlite3Select(pParse, p, &dest);
80542       testcase( rc!=SQLITE_OK );
80543       pDelete = p->pPrior;
80544       p->pPrior = pPrior;
80545       if( addr ){
80546         sqlite3VdbeJumpHere(v, addr);
80547       }
80548       break;
80549     }
80550     case TK_EXCEPT:
80551     case TK_UNION: {
80552       int unionTab;    /* Cursor number of the temporary table holding result */
80553       u8 op = 0;       /* One of the SRT_ operations to apply to self */
80554       int priorOp;     /* The SRT_ operation to apply to prior selects */
80555       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
80556       int addr;
80557       SelectDest uniondest;
80558
80559       testcase( p->op==TK_EXCEPT );
80560       testcase( p->op==TK_UNION );
80561       priorOp = SRT_Union;
80562       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
80563         /* We can reuse a temporary table generated by a SELECT to our
80564         ** right.
80565         */
80566         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
80567                                      ** of a 3-way or more compound */
80568         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
80569         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
80570         unionTab = dest.iParm;
80571       }else{
80572         /* We will need to create our own temporary table to hold the
80573         ** intermediate results.
80574         */
80575         unionTab = pParse->nTab++;
80576         assert( p->pOrderBy==0 );
80577         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
80578         assert( p->addrOpenEphm[0] == -1 );
80579         p->addrOpenEphm[0] = addr;
80580         p->pRightmost->selFlags |= SF_UsesEphemeral;
80581         assert( p->pEList );
80582       }
80583
80584       /* Code the SELECT statements to our left
80585       */
80586       assert( !pPrior->pOrderBy );
80587       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
80588       rc = sqlite3Select(pParse, pPrior, &uniondest);
80589       if( rc ){
80590         goto multi_select_end;
80591       }
80592
80593       /* Code the current SELECT statement
80594       */
80595       if( p->op==TK_EXCEPT ){
80596         op = SRT_Except;
80597       }else{
80598         assert( p->op==TK_UNION );
80599         op = SRT_Union;
80600       }
80601       p->pPrior = 0;
80602       pLimit = p->pLimit;
80603       p->pLimit = 0;
80604       pOffset = p->pOffset;
80605       p->pOffset = 0;
80606       uniondest.eDest = op;
80607       rc = sqlite3Select(pParse, p, &uniondest);
80608       testcase( rc!=SQLITE_OK );
80609       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
80610       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
80611       sqlite3ExprListDelete(db, p->pOrderBy);
80612       pDelete = p->pPrior;
80613       p->pPrior = pPrior;
80614       p->pOrderBy = 0;
80615       sqlite3ExprDelete(db, p->pLimit);
80616       p->pLimit = pLimit;
80617       p->pOffset = pOffset;
80618       p->iLimit = 0;
80619       p->iOffset = 0;
80620
80621       /* Convert the data in the temporary table into whatever form
80622       ** it is that we currently need.
80623       */
80624       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
80625       if( dest.eDest!=priorOp ){
80626         int iCont, iBreak, iStart;
80627         assert( p->pEList );
80628         if( dest.eDest==SRT_Output ){
80629           Select *pFirst = p;
80630           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
80631           generateColumnNames(pParse, 0, pFirst->pEList);
80632         }
80633         iBreak = sqlite3VdbeMakeLabel(v);
80634         iCont = sqlite3VdbeMakeLabel(v);
80635         computeLimitRegisters(pParse, p, iBreak);
80636         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
80637         iStart = sqlite3VdbeCurrentAddr(v);
80638         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
80639                         0, -1, &dest, iCont, iBreak);
80640         sqlite3VdbeResolveLabel(v, iCont);
80641         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
80642         sqlite3VdbeResolveLabel(v, iBreak);
80643         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
80644       }
80645       break;
80646     }
80647     default: assert( p->op==TK_INTERSECT ); {
80648       int tab1, tab2;
80649       int iCont, iBreak, iStart;
80650       Expr *pLimit, *pOffset;
80651       int addr;
80652       SelectDest intersectdest;
80653       int r1;
80654
80655       /* INTERSECT is different from the others since it requires
80656       ** two temporary tables.  Hence it has its own case.  Begin
80657       ** by allocating the tables we will need.
80658       */
80659       tab1 = pParse->nTab++;
80660       tab2 = pParse->nTab++;
80661       assert( p->pOrderBy==0 );
80662
80663       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
80664       assert( p->addrOpenEphm[0] == -1 );
80665       p->addrOpenEphm[0] = addr;
80666       p->pRightmost->selFlags |= SF_UsesEphemeral;
80667       assert( p->pEList );
80668
80669       /* Code the SELECTs to our left into temporary table "tab1".
80670       */
80671       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
80672       rc = sqlite3Select(pParse, pPrior, &intersectdest);
80673       if( rc ){
80674         goto multi_select_end;
80675       }
80676
80677       /* Code the current SELECT into temporary table "tab2"
80678       */
80679       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
80680       assert( p->addrOpenEphm[1] == -1 );
80681       p->addrOpenEphm[1] = addr;
80682       p->pPrior = 0;
80683       pLimit = p->pLimit;
80684       p->pLimit = 0;
80685       pOffset = p->pOffset;
80686       p->pOffset = 0;
80687       intersectdest.iParm = tab2;
80688       rc = sqlite3Select(pParse, p, &intersectdest);
80689       testcase( rc!=SQLITE_OK );
80690       pDelete = p->pPrior;
80691       p->pPrior = pPrior;
80692       sqlite3ExprDelete(db, p->pLimit);
80693       p->pLimit = pLimit;
80694       p->pOffset = pOffset;
80695
80696       /* Generate code to take the intersection of the two temporary
80697       ** tables.
80698       */
80699       assert( p->pEList );
80700       if( dest.eDest==SRT_Output ){
80701         Select *pFirst = p;
80702         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
80703         generateColumnNames(pParse, 0, pFirst->pEList);
80704       }
80705       iBreak = sqlite3VdbeMakeLabel(v);
80706       iCont = sqlite3VdbeMakeLabel(v);
80707       computeLimitRegisters(pParse, p, iBreak);
80708       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
80709       r1 = sqlite3GetTempReg(pParse);
80710       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
80711       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
80712       sqlite3ReleaseTempReg(pParse, r1);
80713       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
80714                       0, -1, &dest, iCont, iBreak);
80715       sqlite3VdbeResolveLabel(v, iCont);
80716       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
80717       sqlite3VdbeResolveLabel(v, iBreak);
80718       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
80719       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
80720       break;
80721     }
80722   }
80723
80724   /* Compute collating sequences used by 
80725   ** temporary tables needed to implement the compound select.
80726   ** Attach the KeyInfo structure to all temporary tables.
80727   **
80728   ** This section is run by the right-most SELECT statement only.
80729   ** SELECT statements to the left always skip this part.  The right-most
80730   ** SELECT might also skip this part if it has no ORDER BY clause and
80731   ** no temp tables are required.
80732   */
80733   if( p->selFlags & SF_UsesEphemeral ){
80734     int i;                        /* Loop counter */
80735     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
80736     Select *pLoop;                /* For looping through SELECT statements */
80737     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
80738     int nCol;                     /* Number of columns in result set */
80739
80740     assert( p->pRightmost==p );
80741     nCol = p->pEList->nExpr;
80742     pKeyInfo = sqlite3DbMallocZero(db,
80743                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
80744     if( !pKeyInfo ){
80745       rc = SQLITE_NOMEM;
80746       goto multi_select_end;
80747     }
80748
80749     pKeyInfo->enc = ENC(db);
80750     pKeyInfo->nField = (u16)nCol;
80751
80752     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
80753       *apColl = multiSelectCollSeq(pParse, p, i);
80754       if( 0==*apColl ){
80755         *apColl = db->pDfltColl;
80756       }
80757     }
80758
80759     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
80760       for(i=0; i<2; i++){
80761         int addr = pLoop->addrOpenEphm[i];
80762         if( addr<0 ){
80763           /* If [0] is unused then [1] is also unused.  So we can
80764           ** always safely abort as soon as the first unused slot is found */
80765           assert( pLoop->addrOpenEphm[1]<0 );
80766           break;
80767         }
80768         sqlite3VdbeChangeP2(v, addr, nCol);
80769         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
80770         pLoop->addrOpenEphm[i] = -1;
80771       }
80772     }
80773     sqlite3DbFree(db, pKeyInfo);
80774   }
80775
80776 multi_select_end:
80777   pDest->iMem = dest.iMem;
80778   pDest->nMem = dest.nMem;
80779   sqlite3SelectDelete(db, pDelete);
80780   return rc;
80781 }
80782 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
80783
80784 /*
80785 ** Code an output subroutine for a coroutine implementation of a
80786 ** SELECT statment.
80787 **
80788 ** The data to be output is contained in pIn->iMem.  There are
80789 ** pIn->nMem columns to be output.  pDest is where the output should
80790 ** be sent.
80791 **
80792 ** regReturn is the number of the register holding the subroutine
80793 ** return address.
80794 **
80795 ** If regPrev>0 then it is a the first register in a vector that
80796 ** records the previous output.  mem[regPrev] is a flag that is false
80797 ** if there has been no previous output.  If regPrev>0 then code is
80798 ** generated to suppress duplicates.  pKeyInfo is used for comparing
80799 ** keys.
80800 **
80801 ** If the LIMIT found in p->iLimit is reached, jump immediately to
80802 ** iBreak.
80803 */
80804 static int generateOutputSubroutine(
80805   Parse *pParse,          /* Parsing context */
80806   Select *p,              /* The SELECT statement */
80807   SelectDest *pIn,        /* Coroutine supplying data */
80808   SelectDest *pDest,      /* Where to send the data */
80809   int regReturn,          /* The return address register */
80810   int regPrev,            /* Previous result register.  No uniqueness if 0 */
80811   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
80812   int p4type,             /* The p4 type for pKeyInfo */
80813   int iBreak              /* Jump here if we hit the LIMIT */
80814 ){
80815   Vdbe *v = pParse->pVdbe;
80816   int iContinue;
80817   int addr;
80818
80819   addr = sqlite3VdbeCurrentAddr(v);
80820   iContinue = sqlite3VdbeMakeLabel(v);
80821
80822   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
80823   */
80824   if( regPrev ){
80825     int j1, j2;
80826     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
80827     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
80828                               (char*)pKeyInfo, p4type);
80829     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
80830     sqlite3VdbeJumpHere(v, j1);
80831     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
80832     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
80833   }
80834   if( pParse->db->mallocFailed ) return 0;
80835
80836   /* Suppress the the first OFFSET entries if there is an OFFSET clause
80837   */
80838   codeOffset(v, p, iContinue);
80839
80840   switch( pDest->eDest ){
80841     /* Store the result as data using a unique key.
80842     */
80843     case SRT_Table:
80844     case SRT_EphemTab: {
80845       int r1 = sqlite3GetTempReg(pParse);
80846       int r2 = sqlite3GetTempReg(pParse);
80847       testcase( pDest->eDest==SRT_Table );
80848       testcase( pDest->eDest==SRT_EphemTab );
80849       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
80850       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
80851       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
80852       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80853       sqlite3ReleaseTempReg(pParse, r2);
80854       sqlite3ReleaseTempReg(pParse, r1);
80855       break;
80856     }
80857
80858 #ifndef SQLITE_OMIT_SUBQUERY
80859     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
80860     ** then there should be a single item on the stack.  Write this
80861     ** item into the set table with bogus data.
80862     */
80863     case SRT_Set: {
80864       int r1;
80865       assert( pIn->nMem==1 );
80866       p->affinity = 
80867          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
80868       r1 = sqlite3GetTempReg(pParse);
80869       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
80870       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
80871       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
80872       sqlite3ReleaseTempReg(pParse, r1);
80873       break;
80874     }
80875
80876 #if 0  /* Never occurs on an ORDER BY query */
80877     /* If any row exist in the result set, record that fact and abort.
80878     */
80879     case SRT_Exists: {
80880       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
80881       /* The LIMIT clause will terminate the loop for us */
80882       break;
80883     }
80884 #endif
80885
80886     /* If this is a scalar select that is part of an expression, then
80887     ** store the results in the appropriate memory cell and break out
80888     ** of the scan loop.
80889     */
80890     case SRT_Mem: {
80891       assert( pIn->nMem==1 );
80892       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
80893       /* The LIMIT clause will jump out of the loop for us */
80894       break;
80895     }
80896 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
80897
80898     /* The results are stored in a sequence of registers
80899     ** starting at pDest->iMem.  Then the co-routine yields.
80900     */
80901     case SRT_Coroutine: {
80902       if( pDest->iMem==0 ){
80903         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
80904         pDest->nMem = pIn->nMem;
80905       }
80906       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
80907       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
80908       break;
80909     }
80910
80911     /* If none of the above, then the result destination must be
80912     ** SRT_Output.  This routine is never called with any other
80913     ** destination other than the ones handled above or SRT_Output.
80914     **
80915     ** For SRT_Output, results are stored in a sequence of registers.  
80916     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
80917     ** return the next row of result.
80918     */
80919     default: {
80920       assert( pDest->eDest==SRT_Output );
80921       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
80922       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
80923       break;
80924     }
80925   }
80926
80927   /* Jump to the end of the loop if the LIMIT is reached.
80928   */
80929   if( p->iLimit ){
80930     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
80931   }
80932
80933   /* Generate the subroutine return
80934   */
80935   sqlite3VdbeResolveLabel(v, iContinue);
80936   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
80937
80938   return addr;
80939 }
80940
80941 /*
80942 ** Alternative compound select code generator for cases when there
80943 ** is an ORDER BY clause.
80944 **
80945 ** We assume a query of the following form:
80946 **
80947 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
80948 **
80949 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
80950 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
80951 ** co-routines.  Then run the co-routines in parallel and merge the results
80952 ** into the output.  In addition to the two coroutines (called selectA and
80953 ** selectB) there are 7 subroutines:
80954 **
80955 **    outA:    Move the output of the selectA coroutine into the output
80956 **             of the compound query.
80957 **
80958 **    outB:    Move the output of the selectB coroutine into the output
80959 **             of the compound query.  (Only generated for UNION and
80960 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
80961 **             appears only in B.)
80962 **
80963 **    AltB:    Called when there is data from both coroutines and A<B.
80964 **
80965 **    AeqB:    Called when there is data from both coroutines and A==B.
80966 **
80967 **    AgtB:    Called when there is data from both coroutines and A>B.
80968 **
80969 **    EofA:    Called when data is exhausted from selectA.
80970 **
80971 **    EofB:    Called when data is exhausted from selectB.
80972 **
80973 ** The implementation of the latter five subroutines depend on which 
80974 ** <operator> is used:
80975 **
80976 **
80977 **             UNION ALL         UNION            EXCEPT          INTERSECT
80978 **          -------------  -----------------  --------------  -----------------
80979 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
80980 **
80981 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
80982 **
80983 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
80984 **
80985 **   EofA:   outB, nextB      outB, nextB          halt             halt
80986 **
80987 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
80988 **
80989 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
80990 ** causes an immediate jump to EofA and an EOF on B following nextB causes
80991 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
80992 ** following nextX causes a jump to the end of the select processing.
80993 **
80994 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
80995 ** within the output subroutine.  The regPrev register set holds the previously
80996 ** output value.  A comparison is made against this value and the output
80997 ** is skipped if the next results would be the same as the previous.
80998 **
80999 ** The implementation plan is to implement the two coroutines and seven
81000 ** subroutines first, then put the control logic at the bottom.  Like this:
81001 **
81002 **          goto Init
81003 **     coA: coroutine for left query (A)
81004 **     coB: coroutine for right query (B)
81005 **    outA: output one row of A
81006 **    outB: output one row of B (UNION and UNION ALL only)
81007 **    EofA: ...
81008 **    EofB: ...
81009 **    AltB: ...
81010 **    AeqB: ...
81011 **    AgtB: ...
81012 **    Init: initialize coroutine registers
81013 **          yield coA
81014 **          if eof(A) goto EofA
81015 **          yield coB
81016 **          if eof(B) goto EofB
81017 **    Cmpr: Compare A, B
81018 **          Jump AltB, AeqB, AgtB
81019 **     End: ...
81020 **
81021 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
81022 ** actually called using Gosub and they do not Return.  EofA and EofB loop
81023 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
81024 ** and AgtB jump to either L2 or to one of EofA or EofB.
81025 */
81026 #ifndef SQLITE_OMIT_COMPOUND_SELECT
81027 static int multiSelectOrderBy(
81028   Parse *pParse,        /* Parsing context */
81029   Select *p,            /* The right-most of SELECTs to be coded */
81030   SelectDest *pDest     /* What to do with query results */
81031 ){
81032   int i, j;             /* Loop counters */
81033   Select *pPrior;       /* Another SELECT immediately to our left */
81034   Vdbe *v;              /* Generate code to this VDBE */
81035   SelectDest destA;     /* Destination for coroutine A */
81036   SelectDest destB;     /* Destination for coroutine B */
81037   int regAddrA;         /* Address register for select-A coroutine */
81038   int regEofA;          /* Flag to indicate when select-A is complete */
81039   int regAddrB;         /* Address register for select-B coroutine */
81040   int regEofB;          /* Flag to indicate when select-B is complete */
81041   int addrSelectA;      /* Address of the select-A coroutine */
81042   int addrSelectB;      /* Address of the select-B coroutine */
81043   int regOutA;          /* Address register for the output-A subroutine */
81044   int regOutB;          /* Address register for the output-B subroutine */
81045   int addrOutA;         /* Address of the output-A subroutine */
81046   int addrOutB = 0;     /* Address of the output-B subroutine */
81047   int addrEofA;         /* Address of the select-A-exhausted subroutine */
81048   int addrEofB;         /* Address of the select-B-exhausted subroutine */
81049   int addrAltB;         /* Address of the A<B subroutine */
81050   int addrAeqB;         /* Address of the A==B subroutine */
81051   int addrAgtB;         /* Address of the A>B subroutine */
81052   int regLimitA;        /* Limit register for select-A */
81053   int regLimitB;        /* Limit register for select-A */
81054   int regPrev;          /* A range of registers to hold previous output */
81055   int savedLimit;       /* Saved value of p->iLimit */
81056   int savedOffset;      /* Saved value of p->iOffset */
81057   int labelCmpr;        /* Label for the start of the merge algorithm */
81058   int labelEnd;         /* Label for the end of the overall SELECT stmt */
81059   int j1;               /* Jump instructions that get retargetted */
81060   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
81061   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
81062   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
81063   sqlite3 *db;          /* Database connection */
81064   ExprList *pOrderBy;   /* The ORDER BY clause */
81065   int nOrderBy;         /* Number of terms in the ORDER BY clause */
81066   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
81067
81068   assert( p->pOrderBy!=0 );
81069   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
81070   db = pParse->db;
81071   v = pParse->pVdbe;
81072   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
81073   labelEnd = sqlite3VdbeMakeLabel(v);
81074   labelCmpr = sqlite3VdbeMakeLabel(v);
81075
81076
81077   /* Patch up the ORDER BY clause
81078   */
81079   op = p->op;  
81080   pPrior = p->pPrior;
81081   assert( pPrior->pOrderBy==0 );
81082   pOrderBy = p->pOrderBy;
81083   assert( pOrderBy );
81084   nOrderBy = pOrderBy->nExpr;
81085
81086   /* For operators other than UNION ALL we have to make sure that
81087   ** the ORDER BY clause covers every term of the result set.  Add
81088   ** terms to the ORDER BY clause as necessary.
81089   */
81090   if( op!=TK_ALL ){
81091     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
81092       struct ExprList_item *pItem;
81093       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
81094         assert( pItem->iCol>0 );
81095         if( pItem->iCol==i ) break;
81096       }
81097       if( j==nOrderBy ){
81098         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
81099         if( pNew==0 ) return SQLITE_NOMEM;
81100         pNew->flags |= EP_IntValue;
81101         pNew->u.iValue = i;
81102         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
81103         pOrderBy->a[nOrderBy++].iCol = (u16)i;
81104       }
81105     }
81106   }
81107
81108   /* Compute the comparison permutation and keyinfo that is used with
81109   ** the permutation used to determine if the next
81110   ** row of results comes from selectA or selectB.  Also add explicit
81111   ** collations to the ORDER BY clause terms so that when the subqueries
81112   ** to the right and the left are evaluated, they use the correct
81113   ** collation.
81114   */
81115   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
81116   if( aPermute ){
81117     struct ExprList_item *pItem;
81118     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
81119       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
81120       aPermute[i] = pItem->iCol - 1;
81121     }
81122     pKeyMerge =
81123       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
81124     if( pKeyMerge ){
81125       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
81126       pKeyMerge->nField = (u16)nOrderBy;
81127       pKeyMerge->enc = ENC(db);
81128       for(i=0; i<nOrderBy; i++){
81129         CollSeq *pColl;
81130         Expr *pTerm = pOrderBy->a[i].pExpr;
81131         if( pTerm->flags & EP_ExpCollate ){
81132           pColl = pTerm->pColl;
81133         }else{
81134           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
81135           pTerm->flags |= EP_ExpCollate;
81136           pTerm->pColl = pColl;
81137         }
81138         pKeyMerge->aColl[i] = pColl;
81139         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
81140       }
81141     }
81142   }else{
81143     pKeyMerge = 0;
81144   }
81145
81146   /* Reattach the ORDER BY clause to the query.
81147   */
81148   p->pOrderBy = pOrderBy;
81149   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
81150
81151   /* Allocate a range of temporary registers and the KeyInfo needed
81152   ** for the logic that removes duplicate result rows when the
81153   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
81154   */
81155   if( op==TK_ALL ){
81156     regPrev = 0;
81157   }else{
81158     int nExpr = p->pEList->nExpr;
81159     assert( nOrderBy>=nExpr || db->mallocFailed );
81160     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
81161     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
81162     pKeyDup = sqlite3DbMallocZero(db,
81163                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
81164     if( pKeyDup ){
81165       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
81166       pKeyDup->nField = (u16)nExpr;
81167       pKeyDup->enc = ENC(db);
81168       for(i=0; i<nExpr; i++){
81169         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
81170         pKeyDup->aSortOrder[i] = 0;
81171       }
81172     }
81173   }
81174  
81175   /* Separate the left and the right query from one another
81176   */
81177   p->pPrior = 0;
81178   pPrior->pRightmost = 0;
81179   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
81180   if( pPrior->pPrior==0 ){
81181     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
81182   }
81183
81184   /* Compute the limit registers */
81185   computeLimitRegisters(pParse, p, labelEnd);
81186   if( p->iLimit && op==TK_ALL ){
81187     regLimitA = ++pParse->nMem;
81188     regLimitB = ++pParse->nMem;
81189     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
81190                                   regLimitA);
81191     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
81192   }else{
81193     regLimitA = regLimitB = 0;
81194   }
81195   sqlite3ExprDelete(db, p->pLimit);
81196   p->pLimit = 0;
81197   sqlite3ExprDelete(db, p->pOffset);
81198   p->pOffset = 0;
81199
81200   regAddrA = ++pParse->nMem;
81201   regEofA = ++pParse->nMem;
81202   regAddrB = ++pParse->nMem;
81203   regEofB = ++pParse->nMem;
81204   regOutA = ++pParse->nMem;
81205   regOutB = ++pParse->nMem;
81206   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
81207   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
81208
81209   /* Jump past the various subroutines and coroutines to the main
81210   ** merge loop
81211   */
81212   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
81213   addrSelectA = sqlite3VdbeCurrentAddr(v);
81214
81215
81216   /* Generate a coroutine to evaluate the SELECT statement to the
81217   ** left of the compound operator - the "A" select.
81218   */
81219   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
81220   pPrior->iLimit = regLimitA;
81221   sqlite3Select(pParse, pPrior, &destA);
81222   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
81223   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81224   VdbeNoopComment((v, "End coroutine for left SELECT"));
81225
81226   /* Generate a coroutine to evaluate the SELECT statement on 
81227   ** the right - the "B" select
81228   */
81229   addrSelectB = sqlite3VdbeCurrentAddr(v);
81230   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
81231   savedLimit = p->iLimit;
81232   savedOffset = p->iOffset;
81233   p->iLimit = regLimitB;
81234   p->iOffset = 0;  
81235   sqlite3Select(pParse, p, &destB);
81236   p->iLimit = savedLimit;
81237   p->iOffset = savedOffset;
81238   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
81239   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
81240   VdbeNoopComment((v, "End coroutine for right SELECT"));
81241
81242   /* Generate a subroutine that outputs the current row of the A
81243   ** select as the next output row of the compound select.
81244   */
81245   VdbeNoopComment((v, "Output routine for A"));
81246   addrOutA = generateOutputSubroutine(pParse,
81247                  p, &destA, pDest, regOutA,
81248                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
81249   
81250   /* Generate a subroutine that outputs the current row of the B
81251   ** select as the next output row of the compound select.
81252   */
81253   if( op==TK_ALL || op==TK_UNION ){
81254     VdbeNoopComment((v, "Output routine for B"));
81255     addrOutB = generateOutputSubroutine(pParse,
81256                  p, &destB, pDest, regOutB,
81257                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
81258   }
81259
81260   /* Generate a subroutine to run when the results from select A
81261   ** are exhausted and only data in select B remains.
81262   */
81263   VdbeNoopComment((v, "eof-A subroutine"));
81264   if( op==TK_EXCEPT || op==TK_INTERSECT ){
81265     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
81266   }else{  
81267     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
81268     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
81269     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
81270     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
81271   }
81272
81273   /* Generate a subroutine to run when the results from select B
81274   ** are exhausted and only data in select A remains.
81275   */
81276   if( op==TK_INTERSECT ){
81277     addrEofB = addrEofA;
81278   }else{  
81279     VdbeNoopComment((v, "eof-B subroutine"));
81280     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
81281     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
81282     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81283     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
81284   }
81285
81286   /* Generate code to handle the case of A<B
81287   */
81288   VdbeNoopComment((v, "A-lt-B subroutine"));
81289   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
81290   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81291   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
81292   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
81293
81294   /* Generate code to handle the case of A==B
81295   */
81296   if( op==TK_ALL ){
81297     addrAeqB = addrAltB;
81298   }else if( op==TK_INTERSECT ){
81299     addrAeqB = addrAltB;
81300     addrAltB++;
81301   }else{
81302     VdbeNoopComment((v, "A-eq-B subroutine"));
81303     addrAeqB =
81304     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81305     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
81306     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
81307   }
81308
81309   /* Generate code to handle the case of A>B
81310   */
81311   VdbeNoopComment((v, "A-gt-B subroutine"));
81312   addrAgtB = sqlite3VdbeCurrentAddr(v);
81313   if( op==TK_ALL || op==TK_UNION ){
81314     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
81315   }
81316   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
81317   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
81318   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
81319
81320   /* This code runs once to initialize everything.
81321   */
81322   sqlite3VdbeJumpHere(v, j1);
81323   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
81324   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
81325   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
81326   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
81327   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
81328   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
81329
81330   /* Implement the main merge loop
81331   */
81332   sqlite3VdbeResolveLabel(v, labelCmpr);
81333   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
81334   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
81335                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
81336   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
81337
81338   /* Release temporary registers
81339   */
81340   if( regPrev ){
81341     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
81342   }
81343
81344   /* Jump to the this point in order to terminate the query.
81345   */
81346   sqlite3VdbeResolveLabel(v, labelEnd);
81347
81348   /* Set the number of output columns
81349   */
81350   if( pDest->eDest==SRT_Output ){
81351     Select *pFirst = pPrior;
81352     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
81353     generateColumnNames(pParse, 0, pFirst->pEList);
81354   }
81355
81356   /* Reassembly the compound query so that it will be freed correctly
81357   ** by the calling function */
81358   if( p->pPrior ){
81359     sqlite3SelectDelete(db, p->pPrior);
81360   }
81361   p->pPrior = pPrior;
81362
81363   /*** TBD:  Insert subroutine calls to close cursors on incomplete
81364   **** subqueries ****/
81365   return SQLITE_OK;
81366 }
81367 #endif
81368
81369 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
81370 /* Forward Declarations */
81371 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
81372 static void substSelect(sqlite3*, Select *, int, ExprList *);
81373
81374 /*
81375 ** Scan through the expression pExpr.  Replace every reference to
81376 ** a column in table number iTable with a copy of the iColumn-th
81377 ** entry in pEList.  (But leave references to the ROWID column 
81378 ** unchanged.)
81379 **
81380 ** This routine is part of the flattening procedure.  A subquery
81381 ** whose result set is defined by pEList appears as entry in the
81382 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
81383 ** FORM clause entry is iTable.  This routine make the necessary 
81384 ** changes to pExpr so that it refers directly to the source table
81385 ** of the subquery rather the result set of the subquery.
81386 */
81387 static Expr *substExpr(
81388   sqlite3 *db,        /* Report malloc errors to this connection */
81389   Expr *pExpr,        /* Expr in which substitution occurs */
81390   int iTable,         /* Table to be substituted */
81391   ExprList *pEList    /* Substitute expressions */
81392 ){
81393   if( pExpr==0 ) return 0;
81394   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
81395     if( pExpr->iColumn<0 ){
81396       pExpr->op = TK_NULL;
81397     }else{
81398       Expr *pNew;
81399       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
81400       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
81401       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
81402       if( pNew && pExpr->pColl ){
81403         pNew->pColl = pExpr->pColl;
81404       }
81405       sqlite3ExprDelete(db, pExpr);
81406       pExpr = pNew;
81407     }
81408   }else{
81409     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
81410     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
81411     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
81412       substSelect(db, pExpr->x.pSelect, iTable, pEList);
81413     }else{
81414       substExprList(db, pExpr->x.pList, iTable, pEList);
81415     }
81416   }
81417   return pExpr;
81418 }
81419 static void substExprList(
81420   sqlite3 *db,         /* Report malloc errors here */
81421   ExprList *pList,     /* List to scan and in which to make substitutes */
81422   int iTable,          /* Table to be substituted */
81423   ExprList *pEList     /* Substitute values */
81424 ){
81425   int i;
81426   if( pList==0 ) return;
81427   for(i=0; i<pList->nExpr; i++){
81428     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
81429   }
81430 }
81431 static void substSelect(
81432   sqlite3 *db,         /* Report malloc errors here */
81433   Select *p,           /* SELECT statement in which to make substitutions */
81434   int iTable,          /* Table to be replaced */
81435   ExprList *pEList     /* Substitute values */
81436 ){
81437   SrcList *pSrc;
81438   struct SrcList_item *pItem;
81439   int i;
81440   if( !p ) return;
81441   substExprList(db, p->pEList, iTable, pEList);
81442   substExprList(db, p->pGroupBy, iTable, pEList);
81443   substExprList(db, p->pOrderBy, iTable, pEList);
81444   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
81445   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
81446   substSelect(db, p->pPrior, iTable, pEList);
81447   pSrc = p->pSrc;
81448   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
81449   if( ALWAYS(pSrc) ){
81450     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
81451       substSelect(db, pItem->pSelect, iTable, pEList);
81452     }
81453   }
81454 }
81455 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
81456
81457 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
81458 /*
81459 ** This routine attempts to flatten subqueries in order to speed
81460 ** execution.  It returns 1 if it makes changes and 0 if no flattening
81461 ** occurs.
81462 **
81463 ** To understand the concept of flattening, consider the following
81464 ** query:
81465 **
81466 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
81467 **
81468 ** The default way of implementing this query is to execute the
81469 ** subquery first and store the results in a temporary table, then
81470 ** run the outer query on that temporary table.  This requires two
81471 ** passes over the data.  Furthermore, because the temporary table
81472 ** has no indices, the WHERE clause on the outer query cannot be
81473 ** optimized.
81474 **
81475 ** This routine attempts to rewrite queries such as the above into
81476 ** a single flat select, like this:
81477 **
81478 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
81479 **
81480 ** The code generated for this simpification gives the same result
81481 ** but only has to scan the data once.  And because indices might 
81482 ** exist on the table t1, a complete scan of the data might be
81483 ** avoided.
81484 **
81485 ** Flattening is only attempted if all of the following are true:
81486 **
81487 **   (1)  The subquery and the outer query do not both use aggregates.
81488 **
81489 **   (2)  The subquery is not an aggregate or the outer query is not a join.
81490 **
81491 **   (3)  The subquery is not the right operand of a left outer join
81492 **        (Originally ticket #306.  Strenghtened by ticket #3300)
81493 **
81494 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
81495 **
81496 **   (5)  The subquery is not DISTINCT or the outer query does not use
81497 **        aggregates.
81498 **
81499 **   (6)  The subquery does not use aggregates or the outer query is not
81500 **        DISTINCT.
81501 **
81502 **   (7)  The subquery has a FROM clause.
81503 **
81504 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
81505 **
81506 **   (9)  The subquery does not use LIMIT or the outer query does not use
81507 **        aggregates.
81508 **
81509 **  (10)  The subquery does not use aggregates or the outer query does not
81510 **        use LIMIT.
81511 **
81512 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
81513 **
81514 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
81515 **        a separate restriction deriving from ticket #350.
81516 **
81517 **  (13)  The subquery and outer query do not both use LIMIT
81518 **
81519 **  (14)  The subquery does not use OFFSET
81520 **
81521 **  (15)  The outer query is not part of a compound select or the
81522 **        subquery does not have both an ORDER BY and a LIMIT clause.
81523 **        (See ticket #2339)
81524 **
81525 **  (16)  The outer query is not an aggregate or the subquery does
81526 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
81527 **        until we introduced the group_concat() function.  
81528 **
81529 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
81530 **        compound clause made up entirely of non-aggregate queries, and 
81531 **        the parent query:
81532 **
81533 **          * is not itself part of a compound select,
81534 **          * is not an aggregate or DISTINCT query, and
81535 **          * has no other tables or sub-selects in the FROM clause.
81536 **
81537 **        The parent and sub-query may contain WHERE clauses. Subject to
81538 **        rules (11), (13) and (14), they may also contain ORDER BY,
81539 **        LIMIT and OFFSET clauses.
81540 **
81541 **  (18)  If the sub-query is a compound select, then all terms of the
81542 **        ORDER by clause of the parent must be simple references to 
81543 **        columns of the sub-query.
81544 **
81545 **  (19)  The subquery does not use LIMIT or the outer query does not
81546 **        have a WHERE clause.
81547 **
81548 **  (20)  If the sub-query is a compound select, then it must not use
81549 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
81550 **        somewhat by saying that the terms of the ORDER BY clause must
81551 **        appear as unmodified result columns in the outer query.  But
81552 **        have other optimizations in mind to deal with that case.
81553 **
81554 ** In this routine, the "p" parameter is a pointer to the outer query.
81555 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
81556 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
81557 **
81558 ** If flattening is not attempted, this routine is a no-op and returns 0.
81559 ** If flattening is attempted this routine returns 1.
81560 **
81561 ** All of the expression analysis must occur on both the outer query and
81562 ** the subquery before this routine runs.
81563 */
81564 static int flattenSubquery(
81565   Parse *pParse,       /* Parsing context */
81566   Select *p,           /* The parent or outer SELECT statement */
81567   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
81568   int isAgg,           /* True if outer SELECT uses aggregate functions */
81569   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
81570 ){
81571   const char *zSavedAuthContext = pParse->zAuthContext;
81572   Select *pParent;
81573   Select *pSub;       /* The inner query or "subquery" */
81574   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
81575   SrcList *pSrc;      /* The FROM clause of the outer query */
81576   SrcList *pSubSrc;   /* The FROM clause of the subquery */
81577   ExprList *pList;    /* The result set of the outer query */
81578   int iParent;        /* VDBE cursor number of the pSub result set temp table */
81579   int i;              /* Loop counter */
81580   Expr *pWhere;                    /* The WHERE clause */
81581   struct SrcList_item *pSubitem;   /* The subquery */
81582   sqlite3 *db = pParse->db;
81583
81584   /* Check to see if flattening is permitted.  Return 0 if not.
81585   */
81586   assert( p!=0 );
81587   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
81588   if( db->flags & SQLITE_QueryFlattener ) return 0;
81589   pSrc = p->pSrc;
81590   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
81591   pSubitem = &pSrc->a[iFrom];
81592   iParent = pSubitem->iCursor;
81593   pSub = pSubitem->pSelect;
81594   assert( pSub!=0 );
81595   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
81596   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
81597   pSubSrc = pSub->pSrc;
81598   assert( pSubSrc );
81599   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
81600   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
81601   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
81602   ** became arbitrary expressions, we were forced to add restrictions (13)
81603   ** and (14). */
81604   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
81605   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
81606   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
81607     return 0;                                            /* Restriction (15) */
81608   }
81609   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
81610   if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit) 
81611          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
81612      return 0;       
81613   }
81614   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
81615      return 0;         /* Restriction (6)  */
81616   }
81617   if( p->pOrderBy && pSub->pOrderBy ){
81618      return 0;                                           /* Restriction (11) */
81619   }
81620   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
81621   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
81622
81623   /* OBSOLETE COMMENT 1:
81624   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
81625   ** not used as the right operand of an outer join.  Examples of why this
81626   ** is not allowed:
81627   **
81628   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
81629   **
81630   ** If we flatten the above, we would get
81631   **
81632   **         (t1 LEFT OUTER JOIN t2) JOIN t3
81633   **
81634   ** which is not at all the same thing.
81635   **
81636   ** OBSOLETE COMMENT 2:
81637   ** Restriction 12:  If the subquery is the right operand of a left outer
81638   ** join, make sure the subquery has no WHERE clause.
81639   ** An examples of why this is not allowed:
81640   **
81641   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
81642   **
81643   ** If we flatten the above, we would get
81644   **
81645   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
81646   **
81647   ** But the t2.x>0 test will always fail on a NULL row of t2, which
81648   ** effectively converts the OUTER JOIN into an INNER JOIN.
81649   **
81650   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
81651   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
81652   ** is fraught with danger.  Best to avoid the whole thing.  If the
81653   ** subquery is the right term of a LEFT JOIN, then do not flatten.
81654   */
81655   if( (pSubitem->jointype & JT_OUTER)!=0 ){
81656     return 0;
81657   }
81658
81659   /* Restriction 17: If the sub-query is a compound SELECT, then it must
81660   ** use only the UNION ALL operator. And none of the simple select queries
81661   ** that make up the compound SELECT are allowed to be aggregate or distinct
81662   ** queries.
81663   */
81664   if( pSub->pPrior ){
81665     if( pSub->pOrderBy ){
81666       return 0;  /* Restriction 20 */
81667     }
81668     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
81669       return 0;
81670     }
81671     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
81672       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
81673       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
81674       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
81675        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
81676        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
81677       ){
81678         return 0;
81679       }
81680     }
81681
81682     /* Restriction 18. */
81683     if( p->pOrderBy ){
81684       int ii;
81685       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
81686         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
81687       }
81688     }
81689   }
81690
81691   /***** If we reach this point, flattening is permitted. *****/
81692
81693   /* Authorize the subquery */
81694   pParse->zAuthContext = pSubitem->zName;
81695   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
81696   pParse->zAuthContext = zSavedAuthContext;
81697
81698   /* If the sub-query is a compound SELECT statement, then (by restrictions
81699   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
81700   ** be of the form:
81701   **
81702   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
81703   **
81704   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
81705   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
81706   ** OFFSET clauses and joins them to the left-hand-side of the original
81707   ** using UNION ALL operators. In this case N is the number of simple
81708   ** select statements in the compound sub-query.
81709   **
81710   ** Example:
81711   **
81712   **     SELECT a+1 FROM (
81713   **        SELECT x FROM tab
81714   **        UNION ALL
81715   **        SELECT y FROM tab
81716   **        UNION ALL
81717   **        SELECT abs(z*2) FROM tab2
81718   **     ) WHERE a!=5 ORDER BY 1
81719   **
81720   ** Transformed into:
81721   **
81722   **     SELECT x+1 FROM tab WHERE x+1!=5
81723   **     UNION ALL
81724   **     SELECT y+1 FROM tab WHERE y+1!=5
81725   **     UNION ALL
81726   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
81727   **     ORDER BY 1
81728   **
81729   ** We call this the "compound-subquery flattening".
81730   */
81731   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
81732     Select *pNew;
81733     ExprList *pOrderBy = p->pOrderBy;
81734     Expr *pLimit = p->pLimit;
81735     Select *pPrior = p->pPrior;
81736     p->pOrderBy = 0;
81737     p->pSrc = 0;
81738     p->pPrior = 0;
81739     p->pLimit = 0;
81740     pNew = sqlite3SelectDup(db, p, 0);
81741     p->pLimit = pLimit;
81742     p->pOrderBy = pOrderBy;
81743     p->pSrc = pSrc;
81744     p->op = TK_ALL;
81745     p->pRightmost = 0;
81746     if( pNew==0 ){
81747       pNew = pPrior;
81748     }else{
81749       pNew->pPrior = pPrior;
81750       pNew->pRightmost = 0;
81751     }
81752     p->pPrior = pNew;
81753     if( db->mallocFailed ) return 1;
81754   }
81755
81756   /* Begin flattening the iFrom-th entry of the FROM clause 
81757   ** in the outer query.
81758   */
81759   pSub = pSub1 = pSubitem->pSelect;
81760
81761   /* Delete the transient table structure associated with the
81762   ** subquery
81763   */
81764   sqlite3DbFree(db, pSubitem->zDatabase);
81765   sqlite3DbFree(db, pSubitem->zName);
81766   sqlite3DbFree(db, pSubitem->zAlias);
81767   pSubitem->zDatabase = 0;
81768   pSubitem->zName = 0;
81769   pSubitem->zAlias = 0;
81770   pSubitem->pSelect = 0;
81771
81772   /* Defer deleting the Table object associated with the
81773   ** subquery until code generation is
81774   ** complete, since there may still exist Expr.pTab entries that
81775   ** refer to the subquery even after flattening.  Ticket #3346.
81776   **
81777   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
81778   */
81779   if( ALWAYS(pSubitem->pTab!=0) ){
81780     Table *pTabToDel = pSubitem->pTab;
81781     if( pTabToDel->nRef==1 ){
81782       Parse *pToplevel = sqlite3ParseToplevel(pParse);
81783       pTabToDel->pNextZombie = pToplevel->pZombieTab;
81784       pToplevel->pZombieTab = pTabToDel;
81785     }else{
81786       pTabToDel->nRef--;
81787     }
81788     pSubitem->pTab = 0;
81789   }
81790
81791   /* The following loop runs once for each term in a compound-subquery
81792   ** flattening (as described above).  If we are doing a different kind
81793   ** of flattening - a flattening other than a compound-subquery flattening -
81794   ** then this loop only runs once.
81795   **
81796   ** This loop moves all of the FROM elements of the subquery into the
81797   ** the FROM clause of the outer query.  Before doing this, remember
81798   ** the cursor number for the original outer query FROM element in
81799   ** iParent.  The iParent cursor will never be used.  Subsequent code
81800   ** will scan expressions looking for iParent references and replace
81801   ** those references with expressions that resolve to the subquery FROM
81802   ** elements we are now copying in.
81803   */
81804   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
81805     int nSubSrc;
81806     u8 jointype = 0;
81807     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
81808     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
81809     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
81810
81811     if( pSrc ){
81812       assert( pParent==p );  /* First time through the loop */
81813       jointype = pSubitem->jointype;
81814     }else{
81815       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
81816       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
81817       if( pSrc==0 ){
81818         assert( db->mallocFailed );
81819         break;
81820       }
81821     }
81822
81823     /* The subquery uses a single slot of the FROM clause of the outer
81824     ** query.  If the subquery has more than one element in its FROM clause,
81825     ** then expand the outer query to make space for it to hold all elements
81826     ** of the subquery.
81827     **
81828     ** Example:
81829     **
81830     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
81831     **
81832     ** The outer query has 3 slots in its FROM clause.  One slot of the
81833     ** outer query (the middle slot) is used by the subquery.  The next
81834     ** block of code will expand the out query to 4 slots.  The middle
81835     ** slot is expanded to two slots in order to make space for the
81836     ** two elements in the FROM clause of the subquery.
81837     */
81838     if( nSubSrc>1 ){
81839       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
81840       if( db->mallocFailed ){
81841         break;
81842       }
81843     }
81844
81845     /* Transfer the FROM clause terms from the subquery into the
81846     ** outer query.
81847     */
81848     for(i=0; i<nSubSrc; i++){
81849       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
81850       pSrc->a[i+iFrom] = pSubSrc->a[i];
81851       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
81852     }
81853     pSrc->a[iFrom].jointype = jointype;
81854   
81855     /* Now begin substituting subquery result set expressions for 
81856     ** references to the iParent in the outer query.
81857     ** 
81858     ** Example:
81859     **
81860     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
81861     **   \                     \_____________ subquery __________/          /
81862     **    \_____________________ outer query ______________________________/
81863     **
81864     ** We look at every expression in the outer query and every place we see
81865     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
81866     */
81867     pList = pParent->pEList;
81868     for(i=0; i<pList->nExpr; i++){
81869       if( pList->a[i].zName==0 ){
81870         const char *zSpan = pList->a[i].zSpan;
81871         if( ALWAYS(zSpan) ){
81872           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
81873         }
81874       }
81875     }
81876     substExprList(db, pParent->pEList, iParent, pSub->pEList);
81877     if( isAgg ){
81878       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
81879       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
81880     }
81881     if( pSub->pOrderBy ){
81882       assert( pParent->pOrderBy==0 );
81883       pParent->pOrderBy = pSub->pOrderBy;
81884       pSub->pOrderBy = 0;
81885     }else if( pParent->pOrderBy ){
81886       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
81887     }
81888     if( pSub->pWhere ){
81889       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
81890     }else{
81891       pWhere = 0;
81892     }
81893     if( subqueryIsAgg ){
81894       assert( pParent->pHaving==0 );
81895       pParent->pHaving = pParent->pWhere;
81896       pParent->pWhere = pWhere;
81897       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
81898       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
81899                                   sqlite3ExprDup(db, pSub->pHaving, 0));
81900       assert( pParent->pGroupBy==0 );
81901       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
81902     }else{
81903       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
81904       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
81905     }
81906   
81907     /* The flattened query is distinct if either the inner or the
81908     ** outer query is distinct. 
81909     */
81910     pParent->selFlags |= pSub->selFlags & SF_Distinct;
81911   
81912     /*
81913     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
81914     **
81915     ** One is tempted to try to add a and b to combine the limits.  But this
81916     ** does not work if either limit is negative.
81917     */
81918     if( pSub->pLimit ){
81919       pParent->pLimit = pSub->pLimit;
81920       pSub->pLimit = 0;
81921     }
81922   }
81923
81924   /* Finially, delete what is left of the subquery and return
81925   ** success.
81926   */
81927   sqlite3SelectDelete(db, pSub1);
81928
81929   return 1;
81930 }
81931 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
81932
81933 /*
81934 ** Analyze the SELECT statement passed as an argument to see if it
81935 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
81936 ** it is, or 0 otherwise. At present, a query is considered to be
81937 ** a min()/max() query if:
81938 **
81939 **   1. There is a single object in the FROM clause.
81940 **
81941 **   2. There is a single expression in the result set, and it is
81942 **      either min(x) or max(x), where x is a column reference.
81943 */
81944 static u8 minMaxQuery(Select *p){
81945   Expr *pExpr;
81946   ExprList *pEList = p->pEList;
81947
81948   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
81949   pExpr = pEList->a[0].pExpr;
81950   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
81951   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
81952   pEList = pExpr->x.pList;
81953   if( pEList==0 || pEList->nExpr!=1 ) return 0;
81954   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
81955   assert( !ExprHasProperty(pExpr, EP_IntValue) );
81956   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
81957     return WHERE_ORDERBY_MIN;
81958   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
81959     return WHERE_ORDERBY_MAX;
81960   }
81961   return WHERE_ORDERBY_NORMAL;
81962 }
81963
81964 /*
81965 ** The select statement passed as the first argument is an aggregate query.
81966 ** The second argment is the associated aggregate-info object. This 
81967 ** function tests if the SELECT is of the form:
81968 **
81969 **   SELECT count(*) FROM <tbl>
81970 **
81971 ** where table is a database table, not a sub-select or view. If the query
81972 ** does match this pattern, then a pointer to the Table object representing
81973 ** <tbl> is returned. Otherwise, 0 is returned.
81974 */
81975 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
81976   Table *pTab;
81977   Expr *pExpr;
81978
81979   assert( !p->pGroupBy );
81980
81981   if( p->pWhere || p->pEList->nExpr!=1 
81982    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
81983   ){
81984     return 0;
81985   }
81986   pTab = p->pSrc->a[0].pTab;
81987   pExpr = p->pEList->a[0].pExpr;
81988   assert( pTab && !pTab->pSelect && pExpr );
81989
81990   if( IsVirtual(pTab) ) return 0;
81991   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
81992   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
81993   if( pExpr->flags&EP_Distinct ) return 0;
81994
81995   return pTab;
81996 }
81997
81998 /*
81999 ** If the source-list item passed as an argument was augmented with an
82000 ** INDEXED BY clause, then try to locate the specified index. If there
82001 ** was such a clause and the named index cannot be found, return 
82002 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
82003 ** pFrom->pIndex and return SQLITE_OK.
82004 */
82005 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
82006   if( pFrom->pTab && pFrom->zIndex ){
82007     Table *pTab = pFrom->pTab;
82008     char *zIndex = pFrom->zIndex;
82009     Index *pIdx;
82010     for(pIdx=pTab->pIndex; 
82011         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
82012         pIdx=pIdx->pNext
82013     );
82014     if( !pIdx ){
82015       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
82016       return SQLITE_ERROR;
82017     }
82018     pFrom->pIndex = pIdx;
82019   }
82020   return SQLITE_OK;
82021 }
82022
82023 /*
82024 ** This routine is a Walker callback for "expanding" a SELECT statement.
82025 ** "Expanding" means to do the following:
82026 **
82027 **    (1)  Make sure VDBE cursor numbers have been assigned to every
82028 **         element of the FROM clause.
82029 **
82030 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
82031 **         defines FROM clause.  When views appear in the FROM clause,
82032 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
82033 **         that implements the view.  A copy is made of the view's SELECT
82034 **         statement so that we can freely modify or delete that statement
82035 **         without worrying about messing up the presistent representation
82036 **         of the view.
82037 **
82038 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
82039 **         on joins and the ON and USING clause of joins.
82040 **
82041 **    (4)  Scan the list of columns in the result set (pEList) looking
82042 **         for instances of the "*" operator or the TABLE.* operator.
82043 **         If found, expand each "*" to be every column in every table
82044 **         and TABLE.* to be every column in TABLE.
82045 **
82046 */
82047 static int selectExpander(Walker *pWalker, Select *p){
82048   Parse *pParse = pWalker->pParse;
82049   int i, j, k;
82050   SrcList *pTabList;
82051   ExprList *pEList;
82052   struct SrcList_item *pFrom;
82053   sqlite3 *db = pParse->db;
82054
82055   if( db->mallocFailed  ){
82056     return WRC_Abort;
82057   }
82058   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
82059     return WRC_Prune;
82060   }
82061   p->selFlags |= SF_Expanded;
82062   pTabList = p->pSrc;
82063   pEList = p->pEList;
82064
82065   /* Make sure cursor numbers have been assigned to all entries in
82066   ** the FROM clause of the SELECT statement.
82067   */
82068   sqlite3SrcListAssignCursors(pParse, pTabList);
82069
82070   /* Look up every table named in the FROM clause of the select.  If
82071   ** an entry of the FROM clause is a subquery instead of a table or view,
82072   ** then create a transient table structure to describe the subquery.
82073   */
82074   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
82075     Table *pTab;
82076     if( pFrom->pTab!=0 ){
82077       /* This statement has already been prepared.  There is no need
82078       ** to go further. */
82079       assert( i==0 );
82080       return WRC_Prune;
82081     }
82082     if( pFrom->zName==0 ){
82083 #ifndef SQLITE_OMIT_SUBQUERY
82084       Select *pSel = pFrom->pSelect;
82085       /* A sub-query in the FROM clause of a SELECT */
82086       assert( pSel!=0 );
82087       assert( pFrom->pTab==0 );
82088       sqlite3WalkSelect(pWalker, pSel);
82089       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
82090       if( pTab==0 ) return WRC_Abort;
82091       pTab->dbMem = db->lookaside.bEnabled ? db : 0;
82092       pTab->nRef = 1;
82093       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
82094       while( pSel->pPrior ){ pSel = pSel->pPrior; }
82095       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
82096       pTab->iPKey = -1;
82097       pTab->tabFlags |= TF_Ephemeral;
82098 #endif
82099     }else{
82100       /* An ordinary table or view name in the FROM clause */
82101       assert( pFrom->pTab==0 );
82102       pFrom->pTab = pTab = 
82103         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
82104       if( pTab==0 ) return WRC_Abort;
82105       pTab->nRef++;
82106 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
82107       if( pTab->pSelect || IsVirtual(pTab) ){
82108         /* We reach here if the named table is a really a view */
82109         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
82110         assert( pFrom->pSelect==0 );
82111         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
82112         sqlite3WalkSelect(pWalker, pFrom->pSelect);
82113       }
82114 #endif
82115     }
82116
82117     /* Locate the index named by the INDEXED BY clause, if any. */
82118     if( sqlite3IndexedByLookup(pParse, pFrom) ){
82119       return WRC_Abort;
82120     }
82121   }
82122
82123   /* Process NATURAL keywords, and ON and USING clauses of joins.
82124   */
82125   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
82126     return WRC_Abort;
82127   }
82128
82129   /* For every "*" that occurs in the column list, insert the names of
82130   ** all columns in all tables.  And for every TABLE.* insert the names
82131   ** of all columns in TABLE.  The parser inserted a special expression
82132   ** with the TK_ALL operator for each "*" that it found in the column list.
82133   ** The following code just has to locate the TK_ALL expressions and expand
82134   ** each one to the list of all columns in all tables.
82135   **
82136   ** The first loop just checks to see if there are any "*" operators
82137   ** that need expanding.
82138   */
82139   for(k=0; k<pEList->nExpr; k++){
82140     Expr *pE = pEList->a[k].pExpr;
82141     if( pE->op==TK_ALL ) break;
82142     assert( pE->op!=TK_DOT || pE->pRight!=0 );
82143     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
82144     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
82145   }
82146   if( k<pEList->nExpr ){
82147     /*
82148     ** If we get here it means the result set contains one or more "*"
82149     ** operators that need to be expanded.  Loop through each expression
82150     ** in the result set and expand them one by one.
82151     */
82152     struct ExprList_item *a = pEList->a;
82153     ExprList *pNew = 0;
82154     int flags = pParse->db->flags;
82155     int longNames = (flags & SQLITE_FullColNames)!=0
82156                       && (flags & SQLITE_ShortColNames)==0;
82157
82158     for(k=0; k<pEList->nExpr; k++){
82159       Expr *pE = a[k].pExpr;
82160       assert( pE->op!=TK_DOT || pE->pRight!=0 );
82161       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
82162         /* This particular expression does not need to be expanded.
82163         */
82164         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
82165         if( pNew ){
82166           pNew->a[pNew->nExpr-1].zName = a[k].zName;
82167           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
82168           a[k].zName = 0;
82169           a[k].zSpan = 0;
82170         }
82171         a[k].pExpr = 0;
82172       }else{
82173         /* This expression is a "*" or a "TABLE.*" and needs to be
82174         ** expanded. */
82175         int tableSeen = 0;      /* Set to 1 when TABLE matches */
82176         char *zTName;            /* text of name of TABLE */
82177         if( pE->op==TK_DOT ){
82178           assert( pE->pLeft!=0 );
82179           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
82180           zTName = pE->pLeft->u.zToken;
82181         }else{
82182           zTName = 0;
82183         }
82184         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
82185           Table *pTab = pFrom->pTab;
82186           char *zTabName = pFrom->zAlias;
82187           if( zTabName==0 ){
82188             zTabName = pTab->zName;
82189           }
82190           if( db->mallocFailed ) break;
82191           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
82192             continue;
82193           }
82194           tableSeen = 1;
82195           for(j=0; j<pTab->nCol; j++){
82196             Expr *pExpr, *pRight;
82197             char *zName = pTab->aCol[j].zName;
82198             char *zColname;  /* The computed column name */
82199             char *zToFree;   /* Malloced string that needs to be freed */
82200             Token sColname;  /* Computed column name as a token */
82201
82202             /* If a column is marked as 'hidden' (currently only possible
82203             ** for virtual tables), do not include it in the expanded
82204             ** result-set list.
82205             */
82206             if( IsHiddenColumn(&pTab->aCol[j]) ){
82207               assert(IsVirtual(pTab));
82208               continue;
82209             }
82210
82211             if( i>0 && zTName==0 ){
82212               if( (pFrom->jointype & JT_NATURAL)!=0
82213                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
82214               ){
82215                 /* In a NATURAL join, omit the join columns from the 
82216                 ** table to the right of the join */
82217                 continue;
82218               }
82219               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
82220                 /* In a join with a USING clause, omit columns in the
82221                 ** using clause from the table on the right. */
82222                 continue;
82223               }
82224             }
82225             pRight = sqlite3Expr(db, TK_ID, zName);
82226             zColname = zName;
82227             zToFree = 0;
82228             if( longNames || pTabList->nSrc>1 ){
82229               Expr *pLeft;
82230               pLeft = sqlite3Expr(db, TK_ID, zTabName);
82231               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
82232               if( longNames ){
82233                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
82234                 zToFree = zColname;
82235               }
82236             }else{
82237               pExpr = pRight;
82238             }
82239             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
82240             sColname.z = zColname;
82241             sColname.n = sqlite3Strlen30(zColname);
82242             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
82243             sqlite3DbFree(db, zToFree);
82244           }
82245         }
82246         if( !tableSeen ){
82247           if( zTName ){
82248             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
82249           }else{
82250             sqlite3ErrorMsg(pParse, "no tables specified");
82251           }
82252         }
82253       }
82254     }
82255     sqlite3ExprListDelete(db, pEList);
82256     p->pEList = pNew;
82257   }
82258 #if SQLITE_MAX_COLUMN
82259   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
82260     sqlite3ErrorMsg(pParse, "too many columns in result set");
82261   }
82262 #endif
82263   return WRC_Continue;
82264 }
82265
82266 /*
82267 ** No-op routine for the parse-tree walker.
82268 **
82269 ** When this routine is the Walker.xExprCallback then expression trees
82270 ** are walked without any actions being taken at each node.  Presumably,
82271 ** when this routine is used for Walker.xExprCallback then 
82272 ** Walker.xSelectCallback is set to do something useful for every 
82273 ** subquery in the parser tree.
82274 */
82275 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
82276   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82277   return WRC_Continue;
82278 }
82279
82280 /*
82281 ** This routine "expands" a SELECT statement and all of its subqueries.
82282 ** For additional information on what it means to "expand" a SELECT
82283 ** statement, see the comment on the selectExpand worker callback above.
82284 **
82285 ** Expanding a SELECT statement is the first step in processing a
82286 ** SELECT statement.  The SELECT statement must be expanded before
82287 ** name resolution is performed.
82288 **
82289 ** If anything goes wrong, an error message is written into pParse.
82290 ** The calling function can detect the problem by looking at pParse->nErr
82291 ** and/or pParse->db->mallocFailed.
82292 */
82293 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
82294   Walker w;
82295   w.xSelectCallback = selectExpander;
82296   w.xExprCallback = exprWalkNoop;
82297   w.pParse = pParse;
82298   sqlite3WalkSelect(&w, pSelect);
82299 }
82300
82301
82302 #ifndef SQLITE_OMIT_SUBQUERY
82303 /*
82304 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
82305 ** interface.
82306 **
82307 ** For each FROM-clause subquery, add Column.zType and Column.zColl
82308 ** information to the Table structure that represents the result set
82309 ** of that subquery.
82310 **
82311 ** The Table structure that represents the result set was constructed
82312 ** by selectExpander() but the type and collation information was omitted
82313 ** at that point because identifiers had not yet been resolved.  This
82314 ** routine is called after identifier resolution.
82315 */
82316 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
82317   Parse *pParse;
82318   int i;
82319   SrcList *pTabList;
82320   struct SrcList_item *pFrom;
82321
82322   assert( p->selFlags & SF_Resolved );
82323   assert( (p->selFlags & SF_HasTypeInfo)==0 );
82324   p->selFlags |= SF_HasTypeInfo;
82325   pParse = pWalker->pParse;
82326   pTabList = p->pSrc;
82327   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
82328     Table *pTab = pFrom->pTab;
82329     if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
82330       /* A sub-query in the FROM clause of a SELECT */
82331       Select *pSel = pFrom->pSelect;
82332       assert( pSel );
82333       while( pSel->pPrior ) pSel = pSel->pPrior;
82334       selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
82335     }
82336   }
82337   return WRC_Continue;
82338 }
82339 #endif
82340
82341
82342 /*
82343 ** This routine adds datatype and collating sequence information to
82344 ** the Table structures of all FROM-clause subqueries in a
82345 ** SELECT statement.
82346 **
82347 ** Use this routine after name resolution.
82348 */
82349 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
82350 #ifndef SQLITE_OMIT_SUBQUERY
82351   Walker w;
82352   w.xSelectCallback = selectAddSubqueryTypeInfo;
82353   w.xExprCallback = exprWalkNoop;
82354   w.pParse = pParse;
82355   sqlite3WalkSelect(&w, pSelect);
82356 #endif
82357 }
82358
82359
82360 /*
82361 ** This routine sets of a SELECT statement for processing.  The
82362 ** following is accomplished:
82363 **
82364 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
82365 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
82366 **     *  ON and USING clauses are shifted into WHERE statements
82367 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
82368 **     *  Identifiers in expression are matched to tables.
82369 **
82370 ** This routine acts recursively on all subqueries within the SELECT.
82371 */
82372 SQLITE_PRIVATE void sqlite3SelectPrep(
82373   Parse *pParse,         /* The parser context */
82374   Select *p,             /* The SELECT statement being coded. */
82375   NameContext *pOuterNC  /* Name context for container */
82376 ){
82377   sqlite3 *db;
82378   if( NEVER(p==0) ) return;
82379   db = pParse->db;
82380   if( p->selFlags & SF_HasTypeInfo ) return;
82381   sqlite3SelectExpand(pParse, p);
82382   if( pParse->nErr || db->mallocFailed ) return;
82383   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
82384   if( pParse->nErr || db->mallocFailed ) return;
82385   sqlite3SelectAddTypeInfo(pParse, p);
82386 }
82387
82388 /*
82389 ** Reset the aggregate accumulator.
82390 **
82391 ** The aggregate accumulator is a set of memory cells that hold
82392 ** intermediate results while calculating an aggregate.  This
82393 ** routine simply stores NULLs in all of those memory cells.
82394 */
82395 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
82396   Vdbe *v = pParse->pVdbe;
82397   int i;
82398   struct AggInfo_func *pFunc;
82399   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
82400     return;
82401   }
82402   for(i=0; i<pAggInfo->nColumn; i++){
82403     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
82404   }
82405   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
82406     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
82407     if( pFunc->iDistinct>=0 ){
82408       Expr *pE = pFunc->pExpr;
82409       assert( !ExprHasProperty(pE, EP_xIsSelect) );
82410       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
82411         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
82412            "argument");
82413         pFunc->iDistinct = -1;
82414       }else{
82415         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
82416         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
82417                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82418       }
82419     }
82420   }
82421 }
82422
82423 /*
82424 ** Invoke the OP_AggFinalize opcode for every aggregate function
82425 ** in the AggInfo structure.
82426 */
82427 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
82428   Vdbe *v = pParse->pVdbe;
82429   int i;
82430   struct AggInfo_func *pF;
82431   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
82432     ExprList *pList = pF->pExpr->x.pList;
82433     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
82434     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
82435                       (void*)pF->pFunc, P4_FUNCDEF);
82436   }
82437 }
82438
82439 /*
82440 ** Update the accumulator memory cells for an aggregate based on
82441 ** the current cursor position.
82442 */
82443 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
82444   Vdbe *v = pParse->pVdbe;
82445   int i;
82446   struct AggInfo_func *pF;
82447   struct AggInfo_col *pC;
82448
82449   pAggInfo->directMode = 1;
82450   sqlite3ExprCacheClear(pParse);
82451   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
82452     int nArg;
82453     int addrNext = 0;
82454     int regAgg;
82455     ExprList *pList = pF->pExpr->x.pList;
82456     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
82457     if( pList ){
82458       nArg = pList->nExpr;
82459       regAgg = sqlite3GetTempRange(pParse, nArg);
82460       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
82461     }else{
82462       nArg = 0;
82463       regAgg = 0;
82464     }
82465     if( pF->iDistinct>=0 ){
82466       addrNext = sqlite3VdbeMakeLabel(v);
82467       assert( nArg==1 );
82468       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
82469     }
82470     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
82471       CollSeq *pColl = 0;
82472       struct ExprList_item *pItem;
82473       int j;
82474       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
82475       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
82476         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
82477       }
82478       if( !pColl ){
82479         pColl = pParse->db->pDfltColl;
82480       }
82481       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
82482     }
82483     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
82484                       (void*)pF->pFunc, P4_FUNCDEF);
82485     sqlite3VdbeChangeP5(v, (u8)nArg);
82486     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
82487     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
82488     if( addrNext ){
82489       sqlite3VdbeResolveLabel(v, addrNext);
82490       sqlite3ExprCacheClear(pParse);
82491     }
82492   }
82493   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
82494     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
82495   }
82496   pAggInfo->directMode = 0;
82497   sqlite3ExprCacheClear(pParse);
82498 }
82499
82500 /*
82501 ** Generate code for the SELECT statement given in the p argument.  
82502 **
82503 ** The results are distributed in various ways depending on the
82504 ** contents of the SelectDest structure pointed to by argument pDest
82505 ** as follows:
82506 **
82507 **     pDest->eDest    Result
82508 **     ------------    -------------------------------------------
82509 **     SRT_Output      Generate a row of output (using the OP_ResultRow
82510 **                     opcode) for each row in the result set.
82511 **
82512 **     SRT_Mem         Only valid if the result is a single column.
82513 **                     Store the first column of the first result row
82514 **                     in register pDest->iParm then abandon the rest
82515 **                     of the query.  This destination implies "LIMIT 1".
82516 **
82517 **     SRT_Set         The result must be a single column.  Store each
82518 **                     row of result as the key in table pDest->iParm. 
82519 **                     Apply the affinity pDest->affinity before storing
82520 **                     results.  Used to implement "IN (SELECT ...)".
82521 **
82522 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
82523 **
82524 **     SRT_Except      Remove results from the temporary table pDest->iParm.
82525 **
82526 **     SRT_Table       Store results in temporary table pDest->iParm.
82527 **                     This is like SRT_EphemTab except that the table
82528 **                     is assumed to already be open.
82529 **
82530 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
82531 **                     the result there. The cursor is left open after
82532 **                     returning.  This is like SRT_Table except that
82533 **                     this destination uses OP_OpenEphemeral to create
82534 **                     the table first.
82535 **
82536 **     SRT_Coroutine   Generate a co-routine that returns a new row of
82537 **                     results each time it is invoked.  The entry point
82538 **                     of the co-routine is stored in register pDest->iParm.
82539 **
82540 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
82541 **                     set is not empty.
82542 **
82543 **     SRT_Discard     Throw the results away.  This is used by SELECT
82544 **                     statements within triggers whose only purpose is
82545 **                     the side-effects of functions.
82546 **
82547 ** This routine returns the number of errors.  If any errors are
82548 ** encountered, then an appropriate error message is left in
82549 ** pParse->zErrMsg.
82550 **
82551 ** This routine does NOT free the Select structure passed in.  The
82552 ** calling function needs to do that.
82553 */
82554 SQLITE_PRIVATE int sqlite3Select(
82555   Parse *pParse,         /* The parser context */
82556   Select *p,             /* The SELECT statement being coded. */
82557   SelectDest *pDest      /* What to do with the query results */
82558 ){
82559   int i, j;              /* Loop counters */
82560   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
82561   Vdbe *v;               /* The virtual machine under construction */
82562   int isAgg;             /* True for select lists like "count(*)" */
82563   ExprList *pEList;      /* List of columns to extract. */
82564   SrcList *pTabList;     /* List of tables to select from */
82565   Expr *pWhere;          /* The WHERE clause.  May be NULL */
82566   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
82567   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
82568   Expr *pHaving;         /* The HAVING clause.  May be NULL */
82569   int isDistinct;        /* True if the DISTINCT keyword is present */
82570   int distinct;          /* Table to use for the distinct set */
82571   int rc = 1;            /* Value to return from this function */
82572   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
82573   AggInfo sAggInfo;      /* Information used by aggregate queries */
82574   int iEnd;              /* Address of the end of the query */
82575   sqlite3 *db;           /* The database connection */
82576
82577   db = pParse->db;
82578   if( p==0 || db->mallocFailed || pParse->nErr ){
82579     return 1;
82580   }
82581   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
82582   memset(&sAggInfo, 0, sizeof(sAggInfo));
82583
82584   if( IgnorableOrderby(pDest) ){
82585     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
82586            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
82587     /* If ORDER BY makes no difference in the output then neither does
82588     ** DISTINCT so it can be removed too. */
82589     sqlite3ExprListDelete(db, p->pOrderBy);
82590     p->pOrderBy = 0;
82591     p->selFlags &= ~SF_Distinct;
82592   }
82593   sqlite3SelectPrep(pParse, p, 0);
82594   pOrderBy = p->pOrderBy;
82595   pTabList = p->pSrc;
82596   pEList = p->pEList;
82597   if( pParse->nErr || db->mallocFailed ){
82598     goto select_end;
82599   }
82600   isAgg = (p->selFlags & SF_Aggregate)!=0;
82601   assert( pEList!=0 );
82602
82603   /* Begin generating code.
82604   */
82605   v = sqlite3GetVdbe(pParse);
82606   if( v==0 ) goto select_end;
82607
82608   /* Generate code for all sub-queries in the FROM clause
82609   */
82610 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
82611   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
82612     struct SrcList_item *pItem = &pTabList->a[i];
82613     SelectDest dest;
82614     Select *pSub = pItem->pSelect;
82615     int isAggSub;
82616
82617     if( pSub==0 || pItem->isPopulated ) continue;
82618
82619     /* Increment Parse.nHeight by the height of the largest expression
82620     ** tree refered to by this, the parent select. The child select
82621     ** may contain expression trees of at most
82622     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
82623     ** more conservative than necessary, but much easier than enforcing
82624     ** an exact limit.
82625     */
82626     pParse->nHeight += sqlite3SelectExprHeight(p);
82627
82628     /* Check to see if the subquery can be absorbed into the parent. */
82629     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
82630     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
82631       if( isAggSub ){
82632         isAgg = 1;
82633         p->selFlags |= SF_Aggregate;
82634       }
82635       i = -1;
82636     }else{
82637       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
82638       assert( pItem->isPopulated==0 );
82639       sqlite3Select(pParse, pSub, &dest);
82640       pItem->isPopulated = 1;
82641     }
82642     if( /*pParse->nErr ||*/ db->mallocFailed ){
82643       goto select_end;
82644     }
82645     pParse->nHeight -= sqlite3SelectExprHeight(p);
82646     pTabList = p->pSrc;
82647     if( !IgnorableOrderby(pDest) ){
82648       pOrderBy = p->pOrderBy;
82649     }
82650   }
82651   pEList = p->pEList;
82652 #endif
82653   pWhere = p->pWhere;
82654   pGroupBy = p->pGroupBy;
82655   pHaving = p->pHaving;
82656   isDistinct = (p->selFlags & SF_Distinct)!=0;
82657
82658 #ifndef SQLITE_OMIT_COMPOUND_SELECT
82659   /* If there is are a sequence of queries, do the earlier ones first.
82660   */
82661   if( p->pPrior ){
82662     if( p->pRightmost==0 ){
82663       Select *pLoop, *pRight = 0;
82664       int cnt = 0;
82665       int mxSelect;
82666       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
82667         pLoop->pRightmost = p;
82668         pLoop->pNext = pRight;
82669         pRight = pLoop;
82670       }
82671       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
82672       if( mxSelect && cnt>mxSelect ){
82673         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
82674         return 1;
82675       }
82676     }
82677     return multiSelect(pParse, p, pDest);
82678   }
82679 #endif
82680
82681   /* If writing to memory or generating a set
82682   ** only a single column may be output.
82683   */
82684 #ifndef SQLITE_OMIT_SUBQUERY
82685   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
82686     goto select_end;
82687   }
82688 #endif
82689
82690   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
82691   ** GROUP BY might use an index, DISTINCT never does.
82692   */
82693   assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
82694   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
82695     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
82696     pGroupBy = p->pGroupBy;
82697     p->selFlags &= ~SF_Distinct;
82698     isDistinct = 0;
82699   }
82700
82701   /* If there is an ORDER BY clause, then this sorting
82702   ** index might end up being unused if the data can be 
82703   ** extracted in pre-sorted order.  If that is the case, then the
82704   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
82705   ** we figure out that the sorting index is not needed.  The addrSortIndex
82706   ** variable is used to facilitate that change.
82707   */
82708   if( pOrderBy ){
82709     KeyInfo *pKeyInfo;
82710     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
82711     pOrderBy->iECursor = pParse->nTab++;
82712     p->addrOpenEphm[2] = addrSortIndex =
82713       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
82714                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
82715                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82716   }else{
82717     addrSortIndex = -1;
82718   }
82719
82720   /* If the output is destined for a temporary table, open that table.
82721   */
82722   if( pDest->eDest==SRT_EphemTab ){
82723     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
82724   }
82725
82726   /* Set the limiter.
82727   */
82728   iEnd = sqlite3VdbeMakeLabel(v);
82729   computeLimitRegisters(pParse, p, iEnd);
82730
82731   /* Open a virtual index to use for the distinct set.
82732   */
82733   if( isDistinct ){
82734     KeyInfo *pKeyInfo;
82735     assert( isAgg || pGroupBy );
82736     distinct = pParse->nTab++;
82737     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
82738     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
82739                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82740   }else{
82741     distinct = -1;
82742   }
82743
82744   /* Aggregate and non-aggregate queries are handled differently */
82745   if( !isAgg && pGroupBy==0 ){
82746     /* This case is for non-aggregate queries
82747     ** Begin the database scan
82748     */
82749     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
82750     if( pWInfo==0 ) goto select_end;
82751
82752     /* If sorting index that was created by a prior OP_OpenEphemeral 
82753     ** instruction ended up not being needed, then change the OP_OpenEphemeral
82754     ** into an OP_Noop.
82755     */
82756     if( addrSortIndex>=0 && pOrderBy==0 ){
82757       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
82758       p->addrOpenEphm[2] = -1;
82759     }
82760
82761     /* Use the standard inner loop
82762     */
82763     assert(!isDistinct);
82764     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
82765                     pWInfo->iContinue, pWInfo->iBreak);
82766
82767     /* End the database scan loop.
82768     */
82769     sqlite3WhereEnd(pWInfo);
82770   }else{
82771     /* This is the processing for aggregate queries */
82772     NameContext sNC;    /* Name context for processing aggregate information */
82773     int iAMem;          /* First Mem address for storing current GROUP BY */
82774     int iBMem;          /* First Mem address for previous GROUP BY */
82775     int iUseFlag;       /* Mem address holding flag indicating that at least
82776                         ** one row of the input to the aggregator has been
82777                         ** processed */
82778     int iAbortFlag;     /* Mem address which causes query abort if positive */
82779     int groupBySort;    /* Rows come from source in GROUP BY order */
82780     int addrEnd;        /* End of processing for this SELECT */
82781
82782     /* Remove any and all aliases between the result set and the
82783     ** GROUP BY clause.
82784     */
82785     if( pGroupBy ){
82786       int k;                        /* Loop counter */
82787       struct ExprList_item *pItem;  /* For looping over expression in a list */
82788
82789       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
82790         pItem->iAlias = 0;
82791       }
82792       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
82793         pItem->iAlias = 0;
82794       }
82795     }
82796
82797  
82798     /* Create a label to jump to when we want to abort the query */
82799     addrEnd = sqlite3VdbeMakeLabel(v);
82800
82801     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
82802     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
82803     ** SELECT statement.
82804     */
82805     memset(&sNC, 0, sizeof(sNC));
82806     sNC.pParse = pParse;
82807     sNC.pSrcList = pTabList;
82808     sNC.pAggInfo = &sAggInfo;
82809     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
82810     sAggInfo.pGroupBy = pGroupBy;
82811     sqlite3ExprAnalyzeAggList(&sNC, pEList);
82812     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
82813     if( pHaving ){
82814       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
82815     }
82816     sAggInfo.nAccumulator = sAggInfo.nColumn;
82817     for(i=0; i<sAggInfo.nFunc; i++){
82818       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
82819       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
82820     }
82821     if( db->mallocFailed ) goto select_end;
82822
82823     /* Processing for aggregates with GROUP BY is very different and
82824     ** much more complex than aggregates without a GROUP BY.
82825     */
82826     if( pGroupBy ){
82827       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
82828       int j1;             /* A-vs-B comparision jump */
82829       int addrOutputRow;  /* Start of subroutine that outputs a result row */
82830       int regOutputRow;   /* Return address register for output subroutine */
82831       int addrSetAbort;   /* Set the abort flag and return */
82832       int addrTopOfLoop;  /* Top of the input loop */
82833       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
82834       int addrReset;      /* Subroutine for resetting the accumulator */
82835       int regReset;       /* Return address register for reset subroutine */
82836
82837       /* If there is a GROUP BY clause we might need a sorting index to
82838       ** implement it.  Allocate that sorting index now.  If it turns out
82839       ** that we do not need it after all, the OpenEphemeral instruction
82840       ** will be converted into a Noop.  
82841       */
82842       sAggInfo.sortingIdx = pParse->nTab++;
82843       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
82844       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
82845           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
82846           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82847
82848       /* Initialize memory locations used by GROUP BY aggregate processing
82849       */
82850       iUseFlag = ++pParse->nMem;
82851       iAbortFlag = ++pParse->nMem;
82852       regOutputRow = ++pParse->nMem;
82853       addrOutputRow = sqlite3VdbeMakeLabel(v);
82854       regReset = ++pParse->nMem;
82855       addrReset = sqlite3VdbeMakeLabel(v);
82856       iAMem = pParse->nMem + 1;
82857       pParse->nMem += pGroupBy->nExpr;
82858       iBMem = pParse->nMem + 1;
82859       pParse->nMem += pGroupBy->nExpr;
82860       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
82861       VdbeComment((v, "clear abort flag"));
82862       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
82863       VdbeComment((v, "indicate accumulator empty"));
82864
82865       /* Begin a loop that will extract all source rows in GROUP BY order.
82866       ** This might involve two separate loops with an OP_Sort in between, or
82867       ** it might be a single loop that uses an index to extract information
82868       ** in the right order to begin with.
82869       */
82870       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
82871       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
82872       if( pWInfo==0 ) goto select_end;
82873       if( pGroupBy==0 ){
82874         /* The optimizer is able to deliver rows in group by order so
82875         ** we do not have to sort.  The OP_OpenEphemeral table will be
82876         ** cancelled later because we still need to use the pKeyInfo
82877         */
82878         pGroupBy = p->pGroupBy;
82879         groupBySort = 0;
82880       }else{
82881         /* Rows are coming out in undetermined order.  We have to push
82882         ** each row into a sorting index, terminate the first loop,
82883         ** then loop over the sorting index in order to get the output
82884         ** in sorted order
82885         */
82886         int regBase;
82887         int regRecord;
82888         int nCol;
82889         int nGroupBy;
82890
82891         groupBySort = 1;
82892         nGroupBy = pGroupBy->nExpr;
82893         nCol = nGroupBy + 1;
82894         j = nGroupBy+1;
82895         for(i=0; i<sAggInfo.nColumn; i++){
82896           if( sAggInfo.aCol[i].iSorterColumn>=j ){
82897             nCol++;
82898             j++;
82899           }
82900         }
82901         regBase = sqlite3GetTempRange(pParse, nCol);
82902         sqlite3ExprCacheClear(pParse);
82903         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
82904         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
82905         j = nGroupBy+1;
82906         for(i=0; i<sAggInfo.nColumn; i++){
82907           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
82908           if( pCol->iSorterColumn>=j ){
82909             int r1 = j + regBase;
82910             int r2;
82911
82912             r2 = sqlite3ExprCodeGetColumn(pParse, 
82913                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
82914             if( r1!=r2 ){
82915               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
82916             }
82917             j++;
82918           }
82919         }
82920         regRecord = sqlite3GetTempReg(pParse);
82921         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
82922         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
82923         sqlite3ReleaseTempReg(pParse, regRecord);
82924         sqlite3ReleaseTempRange(pParse, regBase, nCol);
82925         sqlite3WhereEnd(pWInfo);
82926         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
82927         VdbeComment((v, "GROUP BY sort"));
82928         sAggInfo.useSortingIdx = 1;
82929         sqlite3ExprCacheClear(pParse);
82930       }
82931
82932       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
82933       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
82934       ** Then compare the current GROUP BY terms against the GROUP BY terms
82935       ** from the previous row currently stored in a0, a1, a2...
82936       */
82937       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
82938       sqlite3ExprCacheClear(pParse);
82939       for(j=0; j<pGroupBy->nExpr; j++){
82940         if( groupBySort ){
82941           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
82942         }else{
82943           sAggInfo.directMode = 1;
82944           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
82945         }
82946       }
82947       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
82948                           (char*)pKeyInfo, P4_KEYINFO);
82949       j1 = sqlite3VdbeCurrentAddr(v);
82950       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
82951
82952       /* Generate code that runs whenever the GROUP BY changes.
82953       ** Changes in the GROUP BY are detected by the previous code
82954       ** block.  If there were no changes, this block is skipped.
82955       **
82956       ** This code copies current group by terms in b0,b1,b2,...
82957       ** over to a0,a1,a2.  It then calls the output subroutine
82958       ** and resets the aggregate accumulator registers in preparation
82959       ** for the next GROUP BY batch.
82960       */
82961       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
82962       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
82963       VdbeComment((v, "output one row"));
82964       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
82965       VdbeComment((v, "check abort flag"));
82966       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
82967       VdbeComment((v, "reset accumulator"));
82968
82969       /* Update the aggregate accumulators based on the content of
82970       ** the current row
82971       */
82972       sqlite3VdbeJumpHere(v, j1);
82973       updateAccumulator(pParse, &sAggInfo);
82974       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
82975       VdbeComment((v, "indicate data in accumulator"));
82976
82977       /* End of the loop
82978       */
82979       if( groupBySort ){
82980         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
82981       }else{
82982         sqlite3WhereEnd(pWInfo);
82983         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
82984       }
82985
82986       /* Output the final row of result
82987       */
82988       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
82989       VdbeComment((v, "output final row"));
82990
82991       /* Jump over the subroutines
82992       */
82993       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
82994
82995       /* Generate a subroutine that outputs a single row of the result
82996       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
82997       ** is less than or equal to zero, the subroutine is a no-op.  If
82998       ** the processing calls for the query to abort, this subroutine
82999       ** increments the iAbortFlag memory location before returning in
83000       ** order to signal the caller to abort.
83001       */
83002       addrSetAbort = sqlite3VdbeCurrentAddr(v);
83003       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
83004       VdbeComment((v, "set abort flag"));
83005       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
83006       sqlite3VdbeResolveLabel(v, addrOutputRow);
83007       addrOutputRow = sqlite3VdbeCurrentAddr(v);
83008       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
83009       VdbeComment((v, "Groupby result generator entry point"));
83010       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
83011       finalizeAggFunctions(pParse, &sAggInfo);
83012       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
83013       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
83014                       distinct, pDest,
83015                       addrOutputRow+1, addrSetAbort);
83016       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
83017       VdbeComment((v, "end groupby result generator"));
83018
83019       /* Generate a subroutine that will reset the group-by accumulator
83020       */
83021       sqlite3VdbeResolveLabel(v, addrReset);
83022       resetAccumulator(pParse, &sAggInfo);
83023       sqlite3VdbeAddOp1(v, OP_Return, regReset);
83024      
83025     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
83026     else {
83027       ExprList *pDel = 0;
83028 #ifndef SQLITE_OMIT_BTREECOUNT
83029       Table *pTab;
83030       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
83031         /* If isSimpleCount() returns a pointer to a Table structure, then
83032         ** the SQL statement is of the form:
83033         **
83034         **   SELECT count(*) FROM <tbl>
83035         **
83036         ** where the Table structure returned represents table <tbl>.
83037         **
83038         ** This statement is so common that it is optimized specially. The
83039         ** OP_Count instruction is executed either on the intkey table that
83040         ** contains the data for table <tbl> or on one of its indexes. It
83041         ** is better to execute the op on an index, as indexes are almost
83042         ** always spread across less pages than their corresponding tables.
83043         */
83044         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
83045         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
83046         Index *pIdx;                         /* Iterator variable */
83047         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
83048         Index *pBest = 0;                    /* Best index found so far */
83049         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
83050
83051         sqlite3CodeVerifySchema(pParse, iDb);
83052         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
83053
83054         /* Search for the index that has the least amount of columns. If
83055         ** there is such an index, and it has less columns than the table
83056         ** does, then we can assume that it consumes less space on disk and
83057         ** will therefore be cheaper to scan to determine the query result.
83058         ** In this case set iRoot to the root page number of the index b-tree
83059         ** and pKeyInfo to the KeyInfo structure required to navigate the
83060         ** index.
83061         **
83062         ** In practice the KeyInfo structure will not be used. It is only 
83063         ** passed to keep OP_OpenRead happy.
83064         */
83065         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83066           if( !pBest || pIdx->nColumn<pBest->nColumn ){
83067             pBest = pIdx;
83068           }
83069         }
83070         if( pBest && pBest->nColumn<pTab->nCol ){
83071           iRoot = pBest->tnum;
83072           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
83073         }
83074
83075         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
83076         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
83077         if( pKeyInfo ){
83078           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
83079         }
83080         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
83081         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
83082       }else
83083 #endif /* SQLITE_OMIT_BTREECOUNT */
83084       {
83085         /* Check if the query is of one of the following forms:
83086         **
83087         **   SELECT min(x) FROM ...
83088         **   SELECT max(x) FROM ...
83089         **
83090         ** If it is, then ask the code in where.c to attempt to sort results
83091         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
83092         ** If where.c is able to produce results sorted in this order, then
83093         ** add vdbe code to break out of the processing loop after the 
83094         ** first iteration (since the first iteration of the loop is 
83095         ** guaranteed to operate on the row with the minimum or maximum 
83096         ** value of x, the only row required).
83097         **
83098         ** A special flag must be passed to sqlite3WhereBegin() to slightly
83099         ** modify behaviour as follows:
83100         **
83101         **   + If the query is a "SELECT min(x)", then the loop coded by
83102         **     where.c should not iterate over any values with a NULL value
83103         **     for x.
83104         **
83105         **   + The optimizer code in where.c (the thing that decides which
83106         **     index or indices to use) should place a different priority on 
83107         **     satisfying the 'ORDER BY' clause than it does in other cases.
83108         **     Refer to code and comments in where.c for details.
83109         */
83110         ExprList *pMinMax = 0;
83111         u8 flag = minMaxQuery(p);
83112         if( flag ){
83113           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
83114           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
83115           pDel = pMinMax;
83116           if( pMinMax && !db->mallocFailed ){
83117             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
83118             pMinMax->a[0].pExpr->op = TK_COLUMN;
83119           }
83120         }
83121   
83122         /* This case runs if the aggregate has no GROUP BY clause.  The
83123         ** processing is much simpler since there is only a single row
83124         ** of output.
83125         */
83126         resetAccumulator(pParse, &sAggInfo);
83127         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
83128         if( pWInfo==0 ){
83129           sqlite3ExprListDelete(db, pDel);
83130           goto select_end;
83131         }
83132         updateAccumulator(pParse, &sAggInfo);
83133         if( !pMinMax && flag ){
83134           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
83135           VdbeComment((v, "%s() by index",
83136                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
83137         }
83138         sqlite3WhereEnd(pWInfo);
83139         finalizeAggFunctions(pParse, &sAggInfo);
83140       }
83141
83142       pOrderBy = 0;
83143       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
83144       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
83145                       pDest, addrEnd, addrEnd);
83146       sqlite3ExprListDelete(db, pDel);
83147     }
83148     sqlite3VdbeResolveLabel(v, addrEnd);
83149     
83150   } /* endif aggregate query */
83151
83152   /* If there is an ORDER BY clause, then we need to sort the results
83153   ** and send them to the callback one by one.
83154   */
83155   if( pOrderBy ){
83156     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
83157   }
83158
83159   /* Jump here to skip this query
83160   */
83161   sqlite3VdbeResolveLabel(v, iEnd);
83162
83163   /* The SELECT was successfully coded.   Set the return code to 0
83164   ** to indicate no errors.
83165   */
83166   rc = 0;
83167
83168   /* Control jumps to here if an error is encountered above, or upon
83169   ** successful coding of the SELECT.
83170   */
83171 select_end:
83172
83173   /* Identify column names if results of the SELECT are to be output.
83174   */
83175   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
83176     generateColumnNames(pParse, pTabList, pEList);
83177   }
83178
83179   sqlite3DbFree(db, sAggInfo.aCol);
83180   sqlite3DbFree(db, sAggInfo.aFunc);
83181   return rc;
83182 }
83183
83184 #if defined(SQLITE_DEBUG)
83185 /*
83186 *******************************************************************************
83187 ** The following code is used for testing and debugging only.  The code
83188 ** that follows does not appear in normal builds.
83189 **
83190 ** These routines are used to print out the content of all or part of a 
83191 ** parse structures such as Select or Expr.  Such printouts are useful
83192 ** for helping to understand what is happening inside the code generator
83193 ** during the execution of complex SELECT statements.
83194 **
83195 ** These routine are not called anywhere from within the normal
83196 ** code base.  Then are intended to be called from within the debugger
83197 ** or from temporary "printf" statements inserted for debugging.
83198 */
83199 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
83200   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
83201     sqlite3DebugPrintf("(%s", p->u.zToken);
83202   }else{
83203     sqlite3DebugPrintf("(%d", p->op);
83204   }
83205   if( p->pLeft ){
83206     sqlite3DebugPrintf(" ");
83207     sqlite3PrintExpr(p->pLeft);
83208   }
83209   if( p->pRight ){
83210     sqlite3DebugPrintf(" ");
83211     sqlite3PrintExpr(p->pRight);
83212   }
83213   sqlite3DebugPrintf(")");
83214 }
83215 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
83216   int i;
83217   for(i=0; i<pList->nExpr; i++){
83218     sqlite3PrintExpr(pList->a[i].pExpr);
83219     if( i<pList->nExpr-1 ){
83220       sqlite3DebugPrintf(", ");
83221     }
83222   }
83223 }
83224 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
83225   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
83226   sqlite3PrintExprList(p->pEList);
83227   sqlite3DebugPrintf("\n");
83228   if( p->pSrc ){
83229     char *zPrefix;
83230     int i;
83231     zPrefix = "FROM";
83232     for(i=0; i<p->pSrc->nSrc; i++){
83233       struct SrcList_item *pItem = &p->pSrc->a[i];
83234       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
83235       zPrefix = "";
83236       if( pItem->pSelect ){
83237         sqlite3DebugPrintf("(\n");
83238         sqlite3PrintSelect(pItem->pSelect, indent+10);
83239         sqlite3DebugPrintf("%*s)", indent+8, "");
83240       }else if( pItem->zName ){
83241         sqlite3DebugPrintf("%s", pItem->zName);
83242       }
83243       if( pItem->pTab ){
83244         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
83245       }
83246       if( pItem->zAlias ){
83247         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
83248       }
83249       if( i<p->pSrc->nSrc-1 ){
83250         sqlite3DebugPrintf(",");
83251       }
83252       sqlite3DebugPrintf("\n");
83253     }
83254   }
83255   if( p->pWhere ){
83256     sqlite3DebugPrintf("%*s WHERE ", indent, "");
83257     sqlite3PrintExpr(p->pWhere);
83258     sqlite3DebugPrintf("\n");
83259   }
83260   if( p->pGroupBy ){
83261     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
83262     sqlite3PrintExprList(p->pGroupBy);
83263     sqlite3DebugPrintf("\n");
83264   }
83265   if( p->pHaving ){
83266     sqlite3DebugPrintf("%*s HAVING ", indent, "");
83267     sqlite3PrintExpr(p->pHaving);
83268     sqlite3DebugPrintf("\n");
83269   }
83270   if( p->pOrderBy ){
83271     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
83272     sqlite3PrintExprList(p->pOrderBy);
83273     sqlite3DebugPrintf("\n");
83274   }
83275 }
83276 /* End of the structure debug printing code
83277 *****************************************************************************/
83278 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
83279
83280 /************** End of select.c **********************************************/
83281 /************** Begin file table.c *******************************************/
83282 /*
83283 ** 2001 September 15
83284 **
83285 ** The author disclaims copyright to this source code.  In place of
83286 ** a legal notice, here is a blessing:
83287 **
83288 **    May you do good and not evil.
83289 **    May you find forgiveness for yourself and forgive others.
83290 **    May you share freely, never taking more than you give.
83291 **
83292 *************************************************************************
83293 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
83294 ** interface routines.  These are just wrappers around the main
83295 ** interface routine of sqlite3_exec().
83296 **
83297 ** These routines are in a separate files so that they will not be linked
83298 ** if they are not used.
83299 */
83300
83301 #ifndef SQLITE_OMIT_GET_TABLE
83302
83303 /*
83304 ** This structure is used to pass data from sqlite3_get_table() through
83305 ** to the callback function is uses to build the result.
83306 */
83307 typedef struct TabResult {
83308   char **azResult;   /* Accumulated output */
83309   char *zErrMsg;     /* Error message text, if an error occurs */
83310   int nAlloc;        /* Slots allocated for azResult[] */
83311   int nRow;          /* Number of rows in the result */
83312   int nColumn;       /* Number of columns in the result */
83313   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
83314   int rc;            /* Return code from sqlite3_exec() */
83315 } TabResult;
83316
83317 /*
83318 ** This routine is called once for each row in the result table.  Its job
83319 ** is to fill in the TabResult structure appropriately, allocating new
83320 ** memory as necessary.
83321 */
83322 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
83323   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
83324   int need;                         /* Slots needed in p->azResult[] */
83325   int i;                            /* Loop counter */
83326   char *z;                          /* A single column of result */
83327
83328   /* Make sure there is enough space in p->azResult to hold everything
83329   ** we need to remember from this invocation of the callback.
83330   */
83331   if( p->nRow==0 && argv!=0 ){
83332     need = nCol*2;
83333   }else{
83334     need = nCol;
83335   }
83336   if( p->nData + need > p->nAlloc ){
83337     char **azNew;
83338     p->nAlloc = p->nAlloc*2 + need;
83339     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
83340     if( azNew==0 ) goto malloc_failed;
83341     p->azResult = azNew;
83342   }
83343
83344   /* If this is the first row, then generate an extra row containing
83345   ** the names of all columns.
83346   */
83347   if( p->nRow==0 ){
83348     p->nColumn = nCol;
83349     for(i=0; i<nCol; i++){
83350       z = sqlite3_mprintf("%s", colv[i]);
83351       if( z==0 ) goto malloc_failed;
83352       p->azResult[p->nData++] = z;
83353     }
83354   }else if( p->nColumn!=nCol ){
83355     sqlite3_free(p->zErrMsg);
83356     p->zErrMsg = sqlite3_mprintf(
83357        "sqlite3_get_table() called with two or more incompatible queries"
83358     );
83359     p->rc = SQLITE_ERROR;
83360     return 1;
83361   }
83362
83363   /* Copy over the row data
83364   */
83365   if( argv!=0 ){
83366     for(i=0; i<nCol; i++){
83367       if( argv[i]==0 ){
83368         z = 0;
83369       }else{
83370         int n = sqlite3Strlen30(argv[i])+1;
83371         z = sqlite3_malloc( n );
83372         if( z==0 ) goto malloc_failed;
83373         memcpy(z, argv[i], n);
83374       }
83375       p->azResult[p->nData++] = z;
83376     }
83377     p->nRow++;
83378   }
83379   return 0;
83380
83381 malloc_failed:
83382   p->rc = SQLITE_NOMEM;
83383   return 1;
83384 }
83385
83386 /*
83387 ** Query the database.  But instead of invoking a callback for each row,
83388 ** malloc() for space to hold the result and return the entire results
83389 ** at the conclusion of the call.
83390 **
83391 ** The result that is written to ***pazResult is held in memory obtained
83392 ** from malloc().  But the caller cannot free this memory directly.  
83393 ** Instead, the entire table should be passed to sqlite3_free_table() when
83394 ** the calling procedure is finished using it.
83395 */
83396 SQLITE_API int sqlite3_get_table(
83397   sqlite3 *db,                /* The database on which the SQL executes */
83398   const char *zSql,           /* The SQL to be executed */
83399   char ***pazResult,          /* Write the result table here */
83400   int *pnRow,                 /* Write the number of rows in the result here */
83401   int *pnColumn,              /* Write the number of columns of result here */
83402   char **pzErrMsg             /* Write error messages here */
83403 ){
83404   int rc;
83405   TabResult res;
83406
83407   *pazResult = 0;
83408   if( pnColumn ) *pnColumn = 0;
83409   if( pnRow ) *pnRow = 0;
83410   if( pzErrMsg ) *pzErrMsg = 0;
83411   res.zErrMsg = 0;
83412   res.nRow = 0;
83413   res.nColumn = 0;
83414   res.nData = 1;
83415   res.nAlloc = 20;
83416   res.rc = SQLITE_OK;
83417   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
83418   if( res.azResult==0 ){
83419      db->errCode = SQLITE_NOMEM;
83420      return SQLITE_NOMEM;
83421   }
83422   res.azResult[0] = 0;
83423   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
83424   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
83425   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
83426   if( (rc&0xff)==SQLITE_ABORT ){
83427     sqlite3_free_table(&res.azResult[1]);
83428     if( res.zErrMsg ){
83429       if( pzErrMsg ){
83430         sqlite3_free(*pzErrMsg);
83431         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
83432       }
83433       sqlite3_free(res.zErrMsg);
83434     }
83435     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
83436     return res.rc;
83437   }
83438   sqlite3_free(res.zErrMsg);
83439   if( rc!=SQLITE_OK ){
83440     sqlite3_free_table(&res.azResult[1]);
83441     return rc;
83442   }
83443   if( res.nAlloc>res.nData ){
83444     char **azNew;
83445     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
83446     if( azNew==0 ){
83447       sqlite3_free_table(&res.azResult[1]);
83448       db->errCode = SQLITE_NOMEM;
83449       return SQLITE_NOMEM;
83450     }
83451     res.azResult = azNew;
83452   }
83453   *pazResult = &res.azResult[1];
83454   if( pnColumn ) *pnColumn = res.nColumn;
83455   if( pnRow ) *pnRow = res.nRow;
83456   return rc;
83457 }
83458
83459 /*
83460 ** This routine frees the space the sqlite3_get_table() malloced.
83461 */
83462 SQLITE_API void sqlite3_free_table(
83463   char **azResult            /* Result returned from from sqlite3_get_table() */
83464 ){
83465   if( azResult ){
83466     int i, n;
83467     azResult--;
83468     assert( azResult!=0 );
83469     n = SQLITE_PTR_TO_INT(azResult[0]);
83470     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
83471     sqlite3_free(azResult);
83472   }
83473 }
83474
83475 #endif /* SQLITE_OMIT_GET_TABLE */
83476
83477 /************** End of table.c ***********************************************/
83478 /************** Begin file trigger.c *****************************************/
83479 /*
83480 **
83481 ** The author disclaims copyright to this source code.  In place of
83482 ** a legal notice, here is a blessing:
83483 **
83484 **    May you do good and not evil.
83485 **    May you find forgiveness for yourself and forgive others.
83486 **    May you share freely, never taking more than you give.
83487 **
83488 *************************************************************************
83489 ** This file contains the implementation for TRIGGERs
83490 */
83491
83492 #ifndef SQLITE_OMIT_TRIGGER
83493 /*
83494 ** Delete a linked list of TriggerStep structures.
83495 */
83496 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
83497   while( pTriggerStep ){
83498     TriggerStep * pTmp = pTriggerStep;
83499     pTriggerStep = pTriggerStep->pNext;
83500
83501     sqlite3ExprDelete(db, pTmp->pWhere);
83502     sqlite3ExprListDelete(db, pTmp->pExprList);
83503     sqlite3SelectDelete(db, pTmp->pSelect);
83504     sqlite3IdListDelete(db, pTmp->pIdList);
83505
83506     sqlite3DbFree(db, pTmp);
83507   }
83508 }
83509
83510 /*
83511 ** Given table pTab, return a list of all the triggers attached to 
83512 ** the table. The list is connected by Trigger.pNext pointers.
83513 **
83514 ** All of the triggers on pTab that are in the same database as pTab
83515 ** are already attached to pTab->pTrigger.  But there might be additional
83516 ** triggers on pTab in the TEMP schema.  This routine prepends all
83517 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
83518 ** and returns the combined list.
83519 **
83520 ** To state it another way:  This routine returns a list of all triggers
83521 ** that fire off of pTab.  The list will include any TEMP triggers on
83522 ** pTab as well as the triggers lised in pTab->pTrigger.
83523 */
83524 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
83525   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
83526   Trigger *pList = 0;                  /* List of triggers to return */
83527
83528   if( pParse->disableTriggers ){
83529     return 0;
83530   }
83531
83532   if( pTmpSchema!=pTab->pSchema ){
83533     HashElem *p;
83534     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
83535       Trigger *pTrig = (Trigger *)sqliteHashData(p);
83536       if( pTrig->pTabSchema==pTab->pSchema
83537        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
83538       ){
83539         pTrig->pNext = (pList ? pList : pTab->pTrigger);
83540         pList = pTrig;
83541       }
83542     }
83543   }
83544
83545   return (pList ? pList : pTab->pTrigger);
83546 }
83547
83548 /*
83549 ** This is called by the parser when it sees a CREATE TRIGGER statement
83550 ** up to the point of the BEGIN before the trigger actions.  A Trigger
83551 ** structure is generated based on the information available and stored
83552 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
83553 ** sqlite3FinishTrigger() function is called to complete the trigger
83554 ** construction process.
83555 */
83556 SQLITE_PRIVATE void sqlite3BeginTrigger(
83557   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
83558   Token *pName1,      /* The name of the trigger */
83559   Token *pName2,      /* The name of the trigger */
83560   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
83561   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
83562   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
83563   SrcList *pTableName,/* The name of the table/view the trigger applies to */
83564   Expr *pWhen,        /* WHEN clause */
83565   int isTemp,         /* True if the TEMPORARY keyword is present */
83566   int noErr           /* Suppress errors if the trigger already exists */
83567 ){
83568   Trigger *pTrigger = 0;  /* The new trigger */
83569   Table *pTab;            /* Table that the trigger fires off of */
83570   char *zName = 0;        /* Name of the trigger */
83571   sqlite3 *db = pParse->db;  /* The database connection */
83572   int iDb;                /* The database to store the trigger in */
83573   Token *pName;           /* The unqualified db name */
83574   DbFixer sFix;           /* State vector for the DB fixer */
83575   int iTabDb;             /* Index of the database holding pTab */
83576
83577   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
83578   assert( pName2!=0 );
83579   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
83580   assert( op>0 && op<0xff );
83581   if( isTemp ){
83582     /* If TEMP was specified, then the trigger name may not be qualified. */
83583     if( pName2->n>0 ){
83584       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
83585       goto trigger_cleanup;
83586     }
83587     iDb = 1;
83588     pName = pName1;
83589   }else{
83590     /* Figure out the db that the the trigger will be created in */
83591     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
83592     if( iDb<0 ){
83593       goto trigger_cleanup;
83594     }
83595   }
83596
83597   /* If the trigger name was unqualified, and the table is a temp table,
83598   ** then set iDb to 1 to create the trigger in the temporary database.
83599   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
83600   ** exist, the error is caught by the block below.
83601   */
83602   if( !pTableName || db->mallocFailed ){
83603     goto trigger_cleanup;
83604   }
83605   pTab = sqlite3SrcListLookup(pParse, pTableName);
83606   if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
83607     iDb = 1;
83608   }
83609
83610   /* Ensure the table name matches database name and that the table exists */
83611   if( db->mallocFailed ) goto trigger_cleanup;
83612   assert( pTableName->nSrc==1 );
83613   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
83614       sqlite3FixSrcList(&sFix, pTableName) ){
83615     goto trigger_cleanup;
83616   }
83617   pTab = sqlite3SrcListLookup(pParse, pTableName);
83618   if( !pTab ){
83619     /* The table does not exist. */
83620     if( db->init.iDb==1 ){
83621       /* Ticket #3810.
83622       ** Normally, whenever a table is dropped, all associated triggers are
83623       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
83624       ** and the table is dropped by a different database connection, the
83625       ** trigger is not visible to the database connection that does the
83626       ** drop so the trigger cannot be dropped.  This results in an
83627       ** "orphaned trigger" - a trigger whose associated table is missing.
83628       */
83629       db->init.orphanTrigger = 1;
83630     }
83631     goto trigger_cleanup;
83632   }
83633   if( IsVirtual(pTab) ){
83634     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
83635     goto trigger_cleanup;
83636   }
83637
83638   /* Check that the trigger name is not reserved and that no trigger of the
83639   ** specified name exists */
83640   zName = sqlite3NameFromToken(db, pName);
83641   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
83642     goto trigger_cleanup;
83643   }
83644   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
83645                       zName, sqlite3Strlen30(zName)) ){
83646     if( !noErr ){
83647       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
83648     }
83649     goto trigger_cleanup;
83650   }
83651
83652   /* Do not create a trigger on a system table */
83653   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
83654     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
83655     pParse->nErr++;
83656     goto trigger_cleanup;
83657   }
83658
83659   /* INSTEAD of triggers are only for views and views only support INSTEAD
83660   ** of triggers.
83661   */
83662   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
83663     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
83664         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
83665     goto trigger_cleanup;
83666   }
83667   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
83668     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
83669         " trigger on table: %S", pTableName, 0);
83670     goto trigger_cleanup;
83671   }
83672   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83673
83674 #ifndef SQLITE_OMIT_AUTHORIZATION
83675   {
83676     int code = SQLITE_CREATE_TRIGGER;
83677     const char *zDb = db->aDb[iTabDb].zName;
83678     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
83679     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
83680     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
83681       goto trigger_cleanup;
83682     }
83683     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
83684       goto trigger_cleanup;
83685     }
83686   }
83687 #endif
83688
83689   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
83690   ** cannot appear on views.  So we might as well translate every
83691   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
83692   ** elsewhere.
83693   */
83694   if (tr_tm == TK_INSTEAD){
83695     tr_tm = TK_BEFORE;
83696   }
83697
83698   /* Build the Trigger object */
83699   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
83700   if( pTrigger==0 ) goto trigger_cleanup;
83701   pTrigger->zName = zName;
83702   zName = 0;
83703   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
83704   pTrigger->pSchema = db->aDb[iDb].pSchema;
83705   pTrigger->pTabSchema = pTab->pSchema;
83706   pTrigger->op = (u8)op;
83707   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
83708   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
83709   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
83710   assert( pParse->pNewTrigger==0 );
83711   pParse->pNewTrigger = pTrigger;
83712
83713 trigger_cleanup:
83714   sqlite3DbFree(db, zName);
83715   sqlite3SrcListDelete(db, pTableName);
83716   sqlite3IdListDelete(db, pColumns);
83717   sqlite3ExprDelete(db, pWhen);
83718   if( !pParse->pNewTrigger ){
83719     sqlite3DeleteTrigger(db, pTrigger);
83720   }else{
83721     assert( pParse->pNewTrigger==pTrigger );
83722   }
83723 }
83724
83725 /*
83726 ** This routine is called after all of the trigger actions have been parsed
83727 ** in order to complete the process of building the trigger.
83728 */
83729 SQLITE_PRIVATE void sqlite3FinishTrigger(
83730   Parse *pParse,          /* Parser context */
83731   TriggerStep *pStepList, /* The triggered program */
83732   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
83733 ){
83734   Trigger *pTrig = pParse->pNewTrigger;    /* Trigger being finished */
83735   char *zName;                             /* Name of trigger */
83736   sqlite3 *db = pParse->db;                /* The database */
83737   DbFixer sFix;
83738   int iDb;                                 /* Database containing the trigger */
83739   Token nameToken;           /* Trigger name for error reporting */
83740
83741   pTrig = pParse->pNewTrigger;
83742   pParse->pNewTrigger = 0;
83743   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
83744   zName = pTrig->zName;
83745   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
83746   pTrig->step_list = pStepList;
83747   while( pStepList ){
83748     pStepList->pTrig = pTrig;
83749     pStepList = pStepList->pNext;
83750   }
83751   nameToken.z = pTrig->zName;
83752   nameToken.n = sqlite3Strlen30(nameToken.z);
83753   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
83754           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
83755     goto triggerfinish_cleanup;
83756   }
83757
83758   /* if we are not initializing, and this trigger is not on a TEMP table, 
83759   ** build the sqlite_master entry
83760   */
83761   if( !db->init.busy ){
83762     Vdbe *v;
83763     char *z;
83764
83765     /* Make an entry in the sqlite_master table */
83766     v = sqlite3GetVdbe(pParse);
83767     if( v==0 ) goto triggerfinish_cleanup;
83768     sqlite3BeginWriteOperation(pParse, 0, iDb);
83769     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
83770     sqlite3NestedParse(pParse,
83771        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
83772        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
83773        pTrig->table, z);
83774     sqlite3DbFree(db, z);
83775     sqlite3ChangeCookie(pParse, iDb);
83776     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
83777         db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
83778     );
83779   }
83780
83781   if( db->init.busy ){
83782     Trigger *pLink = pTrig;
83783     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
83784     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
83785     if( pTrig ){
83786       db->mallocFailed = 1;
83787     }else if( pLink->pSchema==pLink->pTabSchema ){
83788       Table *pTab;
83789       int n = sqlite3Strlen30(pLink->table);
83790       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
83791       assert( pTab!=0 );
83792       pLink->pNext = pTab->pTrigger;
83793       pTab->pTrigger = pLink;
83794     }
83795   }
83796
83797 triggerfinish_cleanup:
83798   sqlite3DeleteTrigger(db, pTrig);
83799   assert( !pParse->pNewTrigger );
83800   sqlite3DeleteTriggerStep(db, pStepList);
83801 }
83802
83803 /*
83804 ** Turn a SELECT statement (that the pSelect parameter points to) into
83805 ** a trigger step.  Return a pointer to a TriggerStep structure.
83806 **
83807 ** The parser calls this routine when it finds a SELECT statement in
83808 ** body of a TRIGGER.  
83809 */
83810 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
83811   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
83812   if( pTriggerStep==0 ) {
83813     sqlite3SelectDelete(db, pSelect);
83814     return 0;
83815   }
83816   pTriggerStep->op = TK_SELECT;
83817   pTriggerStep->pSelect = pSelect;
83818   pTriggerStep->orconf = OE_Default;
83819   return pTriggerStep;
83820 }
83821
83822 /*
83823 ** Allocate space to hold a new trigger step.  The allocated space
83824 ** holds both the TriggerStep object and the TriggerStep.target.z string.
83825 **
83826 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
83827 */
83828 static TriggerStep *triggerStepAllocate(
83829   sqlite3 *db,                /* Database connection */
83830   u8 op,                      /* Trigger opcode */
83831   Token *pName                /* The target name */
83832 ){
83833   TriggerStep *pTriggerStep;
83834
83835   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
83836   if( pTriggerStep ){
83837     char *z = (char*)&pTriggerStep[1];
83838     memcpy(z, pName->z, pName->n);
83839     pTriggerStep->target.z = z;
83840     pTriggerStep->target.n = pName->n;
83841     pTriggerStep->op = op;
83842   }
83843   return pTriggerStep;
83844 }
83845
83846 /*
83847 ** Build a trigger step out of an INSERT statement.  Return a pointer
83848 ** to the new trigger step.
83849 **
83850 ** The parser calls this routine when it sees an INSERT inside the
83851 ** body of a trigger.
83852 */
83853 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
83854   sqlite3 *db,        /* The database connection */
83855   Token *pTableName,  /* Name of the table into which we insert */
83856   IdList *pColumn,    /* List of columns in pTableName to insert into */
83857   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
83858   Select *pSelect,    /* A SELECT statement that supplies values */
83859   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
83860 ){
83861   TriggerStep *pTriggerStep;
83862
83863   assert(pEList == 0 || pSelect == 0);
83864   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
83865
83866   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
83867   if( pTriggerStep ){
83868     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
83869     pTriggerStep->pIdList = pColumn;
83870     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
83871     pTriggerStep->orconf = orconf;
83872   }else{
83873     sqlite3IdListDelete(db, pColumn);
83874   }
83875   sqlite3ExprListDelete(db, pEList);
83876   sqlite3SelectDelete(db, pSelect);
83877
83878   return pTriggerStep;
83879 }
83880
83881 /*
83882 ** Construct a trigger step that implements an UPDATE statement and return
83883 ** a pointer to that trigger step.  The parser calls this routine when it
83884 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
83885 */
83886 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
83887   sqlite3 *db,         /* The database connection */
83888   Token *pTableName,   /* Name of the table to be updated */
83889   ExprList *pEList,    /* The SET clause: list of column and new values */
83890   Expr *pWhere,        /* The WHERE clause */
83891   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
83892 ){
83893   TriggerStep *pTriggerStep;
83894
83895   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
83896   if( pTriggerStep ){
83897     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
83898     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
83899     pTriggerStep->orconf = orconf;
83900   }
83901   sqlite3ExprListDelete(db, pEList);
83902   sqlite3ExprDelete(db, pWhere);
83903   return pTriggerStep;
83904 }
83905
83906 /*
83907 ** Construct a trigger step that implements a DELETE statement and return
83908 ** a pointer to that trigger step.  The parser calls this routine when it
83909 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
83910 */
83911 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
83912   sqlite3 *db,            /* Database connection */
83913   Token *pTableName,      /* The table from which rows are deleted */
83914   Expr *pWhere            /* The WHERE clause */
83915 ){
83916   TriggerStep *pTriggerStep;
83917
83918   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
83919   if( pTriggerStep ){
83920     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
83921     pTriggerStep->orconf = OE_Default;
83922   }
83923   sqlite3ExprDelete(db, pWhere);
83924   return pTriggerStep;
83925 }
83926
83927 /* 
83928 ** Recursively delete a Trigger structure
83929 */
83930 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
83931   if( pTrigger==0 ) return;
83932   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
83933   sqlite3DbFree(db, pTrigger->zName);
83934   sqlite3DbFree(db, pTrigger->table);
83935   sqlite3ExprDelete(db, pTrigger->pWhen);
83936   sqlite3IdListDelete(db, pTrigger->pColumns);
83937   sqlite3DbFree(db, pTrigger);
83938 }
83939
83940 /*
83941 ** This function is called to drop a trigger from the database schema. 
83942 **
83943 ** This may be called directly from the parser and therefore identifies
83944 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
83945 ** same job as this routine except it takes a pointer to the trigger
83946 ** instead of the trigger name.
83947 **/
83948 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
83949   Trigger *pTrigger = 0;
83950   int i;
83951   const char *zDb;
83952   const char *zName;
83953   int nName;
83954   sqlite3 *db = pParse->db;
83955
83956   if( db->mallocFailed ) goto drop_trigger_cleanup;
83957   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83958     goto drop_trigger_cleanup;
83959   }
83960
83961   assert( pName->nSrc==1 );
83962   zDb = pName->a[0].zDatabase;
83963   zName = pName->a[0].zName;
83964   nName = sqlite3Strlen30(zName);
83965   for(i=OMIT_TEMPDB; i<db->nDb; i++){
83966     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
83967     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
83968     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
83969     if( pTrigger ) break;
83970   }
83971   if( !pTrigger ){
83972     if( !noErr ){
83973       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
83974     }
83975     goto drop_trigger_cleanup;
83976   }
83977   sqlite3DropTriggerPtr(pParse, pTrigger);
83978
83979 drop_trigger_cleanup:
83980   sqlite3SrcListDelete(db, pName);
83981 }
83982
83983 /*
83984 ** Return a pointer to the Table structure for the table that a trigger
83985 ** is set on.
83986 */
83987 static Table *tableOfTrigger(Trigger *pTrigger){
83988   int n = sqlite3Strlen30(pTrigger->table);
83989   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
83990 }
83991
83992
83993 /*
83994 ** Drop a trigger given a pointer to that trigger. 
83995 */
83996 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
83997   Table   *pTable;
83998   Vdbe *v;
83999   sqlite3 *db = pParse->db;
84000   int iDb;
84001
84002   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
84003   assert( iDb>=0 && iDb<db->nDb );
84004   pTable = tableOfTrigger(pTrigger);
84005   assert( pTable );
84006   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
84007 #ifndef SQLITE_OMIT_AUTHORIZATION
84008   {
84009     int code = SQLITE_DROP_TRIGGER;
84010     const char *zDb = db->aDb[iDb].zName;
84011     const char *zTab = SCHEMA_TABLE(iDb);
84012     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
84013     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
84014       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
84015       return;
84016     }
84017   }
84018 #endif
84019
84020   /* Generate code to destroy the database record of the trigger.
84021   */
84022   assert( pTable!=0 );
84023   if( (v = sqlite3GetVdbe(pParse))!=0 ){
84024     int base;
84025     static const VdbeOpList dropTrigger[] = {
84026       { OP_Rewind,     0, ADDR(9),  0},
84027       { OP_String8,    0, 1,        0}, /* 1 */
84028       { OP_Column,     0, 1,        2},
84029       { OP_Ne,         2, ADDR(8),  1},
84030       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
84031       { OP_Column,     0, 0,        2},
84032       { OP_Ne,         2, ADDR(8),  1},
84033       { OP_Delete,     0, 0,        0},
84034       { OP_Next,       0, ADDR(1),  0}, /* 8 */
84035     };
84036
84037     sqlite3BeginWriteOperation(pParse, 0, iDb);
84038     sqlite3OpenMasterTable(pParse, iDb);
84039     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
84040     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
84041     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
84042     sqlite3ChangeCookie(pParse, iDb);
84043     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
84044     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
84045     if( pParse->nMem<3 ){
84046       pParse->nMem = 3;
84047     }
84048   }
84049 }
84050
84051 /*
84052 ** Remove a trigger from the hash tables of the sqlite* pointer.
84053 */
84054 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
84055   Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
84056   Trigger *pTrigger;
84057   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
84058   if( ALWAYS(pTrigger) ){
84059     if( pTrigger->pSchema==pTrigger->pTabSchema ){
84060       Table *pTab = tableOfTrigger(pTrigger);
84061       Trigger **pp;
84062       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
84063       *pp = (*pp)->pNext;
84064     }
84065     sqlite3DeleteTrigger(db, pTrigger);
84066     db->flags |= SQLITE_InternChanges;
84067   }
84068 }
84069
84070 /*
84071 ** pEList is the SET clause of an UPDATE statement.  Each entry
84072 ** in pEList is of the format <id>=<expr>.  If any of the entries
84073 ** in pEList have an <id> which matches an identifier in pIdList,
84074 ** then return TRUE.  If pIdList==NULL, then it is considered a
84075 ** wildcard that matches anything.  Likewise if pEList==NULL then
84076 ** it matches anything so always return true.  Return false only
84077 ** if there is no match.
84078 */
84079 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
84080   int e;
84081   if( pIdList==0 || NEVER(pEList==0) ) return 1;
84082   for(e=0; e<pEList->nExpr; e++){
84083     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
84084   }
84085   return 0; 
84086 }
84087
84088 /*
84089 ** Return a list of all triggers on table pTab if there exists at least
84090 ** one trigger that must be fired when an operation of type 'op' is 
84091 ** performed on the table, and, if that operation is an UPDATE, if at
84092 ** least one of the columns in pChanges is being modified.
84093 */
84094 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
84095   Parse *pParse,          /* Parse context */
84096   Table *pTab,            /* The table the contains the triggers */
84097   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
84098   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
84099   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
84100 ){
84101   int mask = 0;
84102   Trigger *pList = sqlite3TriggerList(pParse, pTab);
84103   Trigger *p;
84104   assert( pList==0 || IsVirtual(pTab)==0 );
84105   for(p=pList; p; p=p->pNext){
84106     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
84107       mask |= p->tr_tm;
84108     }
84109   }
84110   if( pMask ){
84111     *pMask = mask;
84112   }
84113   return (mask ? pList : 0);
84114 }
84115
84116 /*
84117 ** Convert the pStep->target token into a SrcList and return a pointer
84118 ** to that SrcList.
84119 **
84120 ** This routine adds a specific database name, if needed, to the target when
84121 ** forming the SrcList.  This prevents a trigger in one database from
84122 ** referring to a target in another database.  An exception is when the
84123 ** trigger is in TEMP in which case it can refer to any other database it
84124 ** wants.
84125 */
84126 static SrcList *targetSrcList(
84127   Parse *pParse,       /* The parsing context */
84128   TriggerStep *pStep   /* The trigger containing the target token */
84129 ){
84130   int iDb;             /* Index of the database to use */
84131   SrcList *pSrc;       /* SrcList to be returned */
84132
84133   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
84134   if( pSrc ){
84135     assert( pSrc->nSrc>0 );
84136     assert( pSrc->a!=0 );
84137     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
84138     if( iDb==0 || iDb>=2 ){
84139       sqlite3 *db = pParse->db;
84140       assert( iDb<pParse->db->nDb );
84141       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
84142     }
84143   }
84144   return pSrc;
84145 }
84146
84147 /*
84148 ** Generate VDBE code for the statements inside the body of a single 
84149 ** trigger.
84150 */
84151 static int codeTriggerProgram(
84152   Parse *pParse,            /* The parser context */
84153   TriggerStep *pStepList,   /* List of statements inside the trigger body */
84154   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
84155 ){
84156   TriggerStep *pStep;
84157   Vdbe *v = pParse->pVdbe;
84158   sqlite3 *db = pParse->db;
84159
84160   assert( pParse->pTriggerTab && pParse->pToplevel );
84161   assert( pStepList );
84162   assert( v!=0 );
84163   for(pStep=pStepList; pStep; pStep=pStep->pNext){
84164     /* Figure out the ON CONFLICT policy that will be used for this step
84165     ** of the trigger program. If the statement that caused this trigger
84166     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
84167     ** the ON CONFLICT policy that was specified as part of the trigger
84168     ** step statement. Example:
84169     **
84170     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
84171     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
84172     **   END;
84173     **
84174     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
84175     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
84176     */
84177     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
84178
84179     switch( pStep->op ){
84180       case TK_UPDATE: {
84181         sqlite3Update(pParse, 
84182           targetSrcList(pParse, pStep),
84183           sqlite3ExprListDup(db, pStep->pExprList, 0), 
84184           sqlite3ExprDup(db, pStep->pWhere, 0), 
84185           pParse->eOrconf
84186         );
84187         break;
84188       }
84189       case TK_INSERT: {
84190         sqlite3Insert(pParse, 
84191           targetSrcList(pParse, pStep),
84192           sqlite3ExprListDup(db, pStep->pExprList, 0), 
84193           sqlite3SelectDup(db, pStep->pSelect, 0), 
84194           sqlite3IdListDup(db, pStep->pIdList), 
84195           pParse->eOrconf
84196         );
84197         break;
84198       }
84199       case TK_DELETE: {
84200         sqlite3DeleteFrom(pParse, 
84201           targetSrcList(pParse, pStep),
84202           sqlite3ExprDup(db, pStep->pWhere, 0)
84203         );
84204         break;
84205       }
84206       default: assert( pStep->op==TK_SELECT ); {
84207         SelectDest sDest;
84208         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
84209         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
84210         sqlite3Select(pParse, pSelect, &sDest);
84211         sqlite3SelectDelete(db, pSelect);
84212         break;
84213       }
84214     } 
84215     if( pStep->op!=TK_SELECT ){
84216       sqlite3VdbeAddOp0(v, OP_ResetCount);
84217     }
84218   }
84219
84220   return 0;
84221 }
84222
84223 #ifdef SQLITE_DEBUG
84224 /*
84225 ** This function is used to add VdbeComment() annotations to a VDBE
84226 ** program. It is not used in production code, only for debugging.
84227 */
84228 static const char *onErrorText(int onError){
84229   switch( onError ){
84230     case OE_Abort:    return "abort";
84231     case OE_Rollback: return "rollback";
84232     case OE_Fail:     return "fail";
84233     case OE_Replace:  return "replace";
84234     case OE_Ignore:   return "ignore";
84235     case OE_Default:  return "default";
84236   }
84237   return "n/a";
84238 }
84239 #endif
84240
84241 /*
84242 ** Parse context structure pFrom has just been used to create a sub-vdbe
84243 ** (trigger program). If an error has occurred, transfer error information
84244 ** from pFrom to pTo.
84245 */
84246 static void transferParseError(Parse *pTo, Parse *pFrom){
84247   assert( pFrom->zErrMsg==0 || pFrom->nErr );
84248   assert( pTo->zErrMsg==0 || pTo->nErr );
84249   if( pTo->nErr==0 ){
84250     pTo->zErrMsg = pFrom->zErrMsg;
84251     pTo->nErr = pFrom->nErr;
84252   }else{
84253     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
84254   }
84255 }
84256
84257 /*
84258 ** Create and populate a new TriggerPrg object with a sub-program 
84259 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
84260 */
84261 static TriggerPrg *codeRowTrigger(
84262   Parse *pParse,       /* Current parse context */
84263   Trigger *pTrigger,   /* Trigger to code */
84264   Table *pTab,         /* The table pTrigger is attached to */
84265   int orconf           /* ON CONFLICT policy to code trigger program with */
84266 ){
84267   Parse *pTop = sqlite3ParseToplevel(pParse);
84268   sqlite3 *db = pParse->db;   /* Database handle */
84269   TriggerPrg *pPrg;           /* Value to return */
84270   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
84271   Vdbe *v;                    /* Temporary VM */
84272   NameContext sNC;            /* Name context for sub-vdbe */
84273   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
84274   Parse *pSubParse;           /* Parse context for sub-vdbe */
84275   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
84276
84277   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
84278
84279   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
84280   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
84281   ** list of the top-level Parse object sooner rather than later.  */
84282   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
84283   if( !pPrg ) return 0;
84284   pPrg->pNext = pTop->pTriggerPrg;
84285   pTop->pTriggerPrg = pPrg;
84286   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
84287   if( !pProgram ) return 0;
84288   pProgram->nRef = 1;
84289   pPrg->pTrigger = pTrigger;
84290   pPrg->orconf = orconf;
84291   pPrg->aColmask[0] = 0xffffffff;
84292   pPrg->aColmask[1] = 0xffffffff;
84293
84294   /* Allocate and populate a new Parse context to use for coding the 
84295   ** trigger sub-program.  */
84296   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
84297   if( !pSubParse ) return 0;
84298   memset(&sNC, 0, sizeof(sNC));
84299   sNC.pParse = pSubParse;
84300   pSubParse->db = db;
84301   pSubParse->pTriggerTab = pTab;
84302   pSubParse->pToplevel = pTop;
84303   pSubParse->zAuthContext = pTrigger->zName;
84304   pSubParse->eTriggerOp = pTrigger->op;
84305
84306   v = sqlite3GetVdbe(pSubParse);
84307   if( v ){
84308     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
84309       pTrigger->zName, onErrorText(orconf),
84310       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
84311         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
84312         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
84313         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
84314       pTab->zName
84315     ));
84316 #ifndef SQLITE_OMIT_TRACE
84317     sqlite3VdbeChangeP4(v, -1, 
84318       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
84319     );
84320 #endif
84321
84322     /* If one was specified, code the WHEN clause. If it evaluates to false
84323     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
84324     ** OP_Halt inserted at the end of the program.  */
84325     if( pTrigger->pWhen ){
84326       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
84327       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
84328        && db->mallocFailed==0 
84329       ){
84330         iEndTrigger = sqlite3VdbeMakeLabel(v);
84331         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
84332       }
84333       sqlite3ExprDelete(db, pWhen);
84334     }
84335
84336     /* Code the trigger program into the sub-vdbe. */
84337     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
84338
84339     /* Insert an OP_Halt at the end of the sub-program. */
84340     if( iEndTrigger ){
84341       sqlite3VdbeResolveLabel(v, iEndTrigger);
84342     }
84343     sqlite3VdbeAddOp0(v, OP_Halt);
84344     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
84345
84346     transferParseError(pParse, pSubParse);
84347     if( db->mallocFailed==0 ){
84348       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
84349     }
84350     pProgram->nMem = pSubParse->nMem;
84351     pProgram->nCsr = pSubParse->nTab;
84352     pProgram->token = (void *)pTrigger;
84353     pPrg->aColmask[0] = pSubParse->oldmask;
84354     pPrg->aColmask[1] = pSubParse->newmask;
84355     sqlite3VdbeDelete(v);
84356   }
84357
84358   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
84359   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
84360   sqlite3StackFree(db, pSubParse);
84361
84362   return pPrg;
84363 }
84364     
84365 /*
84366 ** Return a pointer to a TriggerPrg object containing the sub-program for
84367 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
84368 ** TriggerPrg object exists, a new object is allocated and populated before
84369 ** being returned.
84370 */
84371 static TriggerPrg *getRowTrigger(
84372   Parse *pParse,       /* Current parse context */
84373   Trigger *pTrigger,   /* Trigger to code */
84374   Table *pTab,         /* The table trigger pTrigger is attached to */
84375   int orconf           /* ON CONFLICT algorithm. */
84376 ){
84377   Parse *pRoot = sqlite3ParseToplevel(pParse);
84378   TriggerPrg *pPrg;
84379
84380   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
84381
84382   /* It may be that this trigger has already been coded (or is in the
84383   ** process of being coded). If this is the case, then an entry with
84384   ** a matching TriggerPrg.pTrigger field will be present somewhere
84385   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
84386   for(pPrg=pRoot->pTriggerPrg; 
84387       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
84388       pPrg=pPrg->pNext
84389   );
84390
84391   /* If an existing TriggerPrg could not be located, create a new one. */
84392   if( !pPrg ){
84393     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
84394   }
84395
84396   return pPrg;
84397 }
84398
84399 /*
84400 ** Generate code for the trigger program associated with trigger p on 
84401 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
84402 ** function are the same as those described in the header function for
84403 ** sqlite3CodeRowTrigger()
84404 */
84405 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
84406   Parse *pParse,       /* Parse context */
84407   Trigger *p,          /* Trigger to code */
84408   Table *pTab,         /* The table to code triggers from */
84409   int reg,             /* Reg array containing OLD.* and NEW.* values */
84410   int orconf,          /* ON CONFLICT policy */
84411   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
84412 ){
84413   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
84414   TriggerPrg *pPrg;
84415   pPrg = getRowTrigger(pParse, p, pTab, orconf);
84416   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
84417
84418   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
84419   ** is a pointer to the sub-vdbe containing the trigger program.  */
84420   if( pPrg ){
84421     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
84422     pPrg->pProgram->nRef++;
84423     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
84424     VdbeComment(
84425         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
84426
84427     /* Set the P5 operand of the OP_Program instruction to non-zero if
84428     ** recursive invocation of this trigger program is disallowed. Recursive
84429     ** invocation is disallowed if (a) the sub-program is really a trigger,
84430     ** not a foreign key action, and (b) the flag to enable recursive triggers
84431     ** is clear.  */
84432     sqlite3VdbeChangeP5(v, (u8)(p->zName && !(pParse->db->flags&SQLITE_RecTriggers)));
84433   }
84434 }
84435
84436 /*
84437 ** This is called to code the required FOR EACH ROW triggers for an operation
84438 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
84439 ** is given by the op paramater. The tr_tm parameter determines whether the
84440 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
84441 ** parameter pChanges is passed the list of columns being modified.
84442 **
84443 ** If there are no triggers that fire at the specified time for the specified
84444 ** operation on pTab, this function is a no-op.
84445 **
84446 ** The reg argument is the address of the first in an array of registers 
84447 ** that contain the values substituted for the new.* and old.* references
84448 ** in the trigger program. If N is the number of columns in table pTab
84449 ** (a copy of pTab->nCol), then registers are populated as follows:
84450 **
84451 **   Register       Contains
84452 **   ------------------------------------------------------
84453 **   reg+0          OLD.rowid
84454 **   reg+1          OLD.* value of left-most column of pTab
84455 **   ...            ...
84456 **   reg+N          OLD.* value of right-most column of pTab
84457 **   reg+N+1        NEW.rowid
84458 **   reg+N+2        OLD.* value of left-most column of pTab
84459 **   ...            ...
84460 **   reg+N+N+1      NEW.* value of right-most column of pTab
84461 **
84462 ** For ON DELETE triggers, the registers containing the NEW.* values will
84463 ** never be accessed by the trigger program, so they are not allocated or 
84464 ** populated by the caller (there is no data to populate them with anyway). 
84465 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
84466 ** are never accessed, and so are not allocated by the caller. So, for an
84467 ** ON INSERT trigger, the value passed to this function as parameter reg
84468 ** is not a readable register, although registers (reg+N) through 
84469 ** (reg+N+N+1) are.
84470 **
84471 ** Parameter orconf is the default conflict resolution algorithm for the
84472 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
84473 ** is the instruction that control should jump to if a trigger program
84474 ** raises an IGNORE exception.
84475 */
84476 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
84477   Parse *pParse,       /* Parse context */
84478   Trigger *pTrigger,   /* List of triggers on table pTab */
84479   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
84480   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
84481   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
84482   Table *pTab,         /* The table to code triggers from */
84483   int reg,             /* The first in an array of registers (see above) */
84484   int orconf,          /* ON CONFLICT policy */
84485   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
84486 ){
84487   Trigger *p;          /* Used to iterate through pTrigger list */
84488
84489   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
84490   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
84491   assert( (op==TK_UPDATE)==(pChanges!=0) );
84492
84493   for(p=pTrigger; p; p=p->pNext){
84494
84495     /* Sanity checking:  The schema for the trigger and for the table are
84496     ** always defined.  The trigger must be in the same schema as the table
84497     ** or else it must be a TEMP trigger. */
84498     assert( p->pSchema!=0 );
84499     assert( p->pTabSchema!=0 );
84500     assert( p->pSchema==p->pTabSchema 
84501          || p->pSchema==pParse->db->aDb[1].pSchema );
84502
84503     /* Determine whether we should code this trigger */
84504     if( p->op==op 
84505      && p->tr_tm==tr_tm 
84506      && checkColumnOverlap(p->pColumns, pChanges)
84507     ){
84508       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
84509     }
84510   }
84511 }
84512
84513 /*
84514 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
84515 ** This function returns a 32-bit bitmask indicating which columns of the 
84516 ** old.* or new.* tables actually are used by triggers. This information 
84517 ** may be used by the caller, for example, to avoid having to load the entire
84518 ** old.* record into memory when executing an UPDATE or DELETE command.
84519 **
84520 ** Bit 0 of the returned mask is set if the left-most column of the
84521 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
84522 ** the second leftmost column value is required, and so on. If there
84523 ** are more than 32 columns in the table, and at least one of the columns
84524 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
84525 **
84526 ** It is not possible to determine if the old.rowid or new.rowid column is 
84527 ** accessed by triggers. The caller must always assume that it is.
84528 **
84529 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
84530 ** applies to the old.* table. If 1, the new.* table.
84531 **
84532 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
84533 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
84534 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
84535 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
84536 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
84537 */
84538 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
84539   Parse *pParse,       /* Parse context */
84540   Trigger *pTrigger,   /* List of triggers on table pTab */
84541   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
84542   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
84543   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
84544   Table *pTab,         /* The table to code triggers from */
84545   int orconf           /* Default ON CONFLICT policy for trigger steps */
84546 ){
84547   const int op = pChanges ? TK_UPDATE : TK_DELETE;
84548   u32 mask = 0;
84549   Trigger *p;
84550
84551   assert( isNew==1 || isNew==0 );
84552   for(p=pTrigger; p; p=p->pNext){
84553     if( p->op==op && (tr_tm&p->tr_tm)
84554      && checkColumnOverlap(p->pColumns,pChanges)
84555     ){
84556       TriggerPrg *pPrg;
84557       pPrg = getRowTrigger(pParse, p, pTab, orconf);
84558       if( pPrg ){
84559         mask |= pPrg->aColmask[isNew];
84560       }
84561     }
84562   }
84563
84564   return mask;
84565 }
84566
84567 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
84568
84569 /************** End of trigger.c *********************************************/
84570 /************** Begin file update.c ******************************************/
84571 /*
84572 ** 2001 September 15
84573 **
84574 ** The author disclaims copyright to this source code.  In place of
84575 ** a legal notice, here is a blessing:
84576 **
84577 **    May you do good and not evil.
84578 **    May you find forgiveness for yourself and forgive others.
84579 **    May you share freely, never taking more than you give.
84580 **
84581 *************************************************************************
84582 ** This file contains C code routines that are called by the parser
84583 ** to handle UPDATE statements.
84584 */
84585
84586 #ifndef SQLITE_OMIT_VIRTUALTABLE
84587 /* Forward declaration */
84588 static void updateVirtualTable(
84589   Parse *pParse,       /* The parsing context */
84590   SrcList *pSrc,       /* The virtual table to be modified */
84591   Table *pTab,         /* The virtual table */
84592   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
84593   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
84594   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
84595   Expr *pWhere         /* WHERE clause of the UPDATE statement */
84596 );
84597 #endif /* SQLITE_OMIT_VIRTUALTABLE */
84598
84599 /*
84600 ** The most recently coded instruction was an OP_Column to retrieve the
84601 ** i-th column of table pTab. This routine sets the P4 parameter of the 
84602 ** OP_Column to the default value, if any.
84603 **
84604 ** The default value of a column is specified by a DEFAULT clause in the 
84605 ** column definition. This was either supplied by the user when the table
84606 ** was created, or added later to the table definition by an ALTER TABLE
84607 ** command. If the latter, then the row-records in the table btree on disk
84608 ** may not contain a value for the column and the default value, taken
84609 ** from the P4 parameter of the OP_Column instruction, is returned instead.
84610 ** If the former, then all row-records are guaranteed to include a value
84611 ** for the column and the P4 value is not required.
84612 **
84613 ** Column definitions created by an ALTER TABLE command may only have 
84614 ** literal default values specified: a number, null or a string. (If a more
84615 ** complicated default expression value was provided, it is evaluated 
84616 ** when the ALTER TABLE is executed and one of the literal values written
84617 ** into the sqlite_master table.)
84618 **
84619 ** Therefore, the P4 parameter is only required if the default value for
84620 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
84621 ** function is capable of transforming these types of expressions into
84622 ** sqlite3_value objects.
84623 **
84624 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
84625 ** on register iReg. This is used when an equivalent integer value is 
84626 ** stored in place of an 8-byte floating point value in order to save 
84627 ** space.
84628 */
84629 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
84630   assert( pTab!=0 );
84631   if( !pTab->pSelect ){
84632     sqlite3_value *pValue;
84633     u8 enc = ENC(sqlite3VdbeDb(v));
84634     Column *pCol = &pTab->aCol[i];
84635     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
84636     assert( i<pTab->nCol );
84637     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
84638                          pCol->affinity, &pValue);
84639     if( pValue ){
84640       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
84641     }
84642 #ifndef SQLITE_OMIT_FLOATING_POINT
84643     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
84644       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
84645     }
84646 #endif
84647   }
84648 }
84649
84650 /*
84651 ** Process an UPDATE statement.
84652 **
84653 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
84654 **          \_______/ \________/     \______/       \________________/
84655 *            onError   pTabList      pChanges             pWhere
84656 */
84657 SQLITE_PRIVATE void sqlite3Update(
84658   Parse *pParse,         /* The parser context */
84659   SrcList *pTabList,     /* The table in which we should change things */
84660   ExprList *pChanges,    /* Things to be changed */
84661   Expr *pWhere,          /* The WHERE clause.  May be null */
84662   int onError            /* How to handle constraint errors */
84663 ){
84664   int i, j;              /* Loop counters */
84665   Table *pTab;           /* The table to be updated */
84666   int addr = 0;          /* VDBE instruction address of the start of the loop */
84667   WhereInfo *pWInfo;     /* Information about the WHERE clause */
84668   Vdbe *v;               /* The virtual database engine */
84669   Index *pIdx;           /* For looping over indices */
84670   int nIdx;              /* Number of indices that need updating */
84671   int iCur;              /* VDBE Cursor number of pTab */
84672   sqlite3 *db;           /* The database structure */
84673   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
84674   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
84675                          ** an expression for the i-th column of the table.
84676                          ** aXRef[i]==-1 if the i-th column is not changed. */
84677   int chngRowid;         /* True if the record number is being changed */
84678   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
84679   int openAll = 0;       /* True if all indices need to be opened */
84680   AuthContext sContext;  /* The authorization context */
84681   NameContext sNC;       /* The name-context to resolve expressions in */
84682   int iDb;               /* Database containing the table being updated */
84683   int okOnePass;         /* True for one-pass algorithm without the FIFO */
84684   int hasFK;             /* True if foreign key processing is required */
84685
84686 #ifndef SQLITE_OMIT_TRIGGER
84687   int isView;            /* True when updating a view (INSTEAD OF trigger) */
84688   Trigger *pTrigger;     /* List of triggers on pTab, if required */
84689   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
84690 #endif
84691   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
84692
84693   /* Register Allocations */
84694   int regRowCount = 0;   /* A count of rows changed */
84695   int regOldRowid;       /* The old rowid */
84696   int regNewRowid;       /* The new rowid */
84697   int regNew;
84698   int regOld = 0;
84699   int regRowSet = 0;     /* Rowset of rows to be updated */
84700   int regRec;            /* Register used for new table record to insert */
84701
84702   memset(&sContext, 0, sizeof(sContext));
84703   db = pParse->db;
84704   if( pParse->nErr || db->mallocFailed ){
84705     goto update_cleanup;
84706   }
84707   assert( pTabList->nSrc==1 );
84708
84709   /* Locate the table which we want to update. 
84710   */
84711   pTab = sqlite3SrcListLookup(pParse, pTabList);
84712   if( pTab==0 ) goto update_cleanup;
84713   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84714
84715   /* Figure out if we have any triggers and if the table being
84716   ** updated is a view.
84717   */
84718 #ifndef SQLITE_OMIT_TRIGGER
84719   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
84720   isView = pTab->pSelect!=0;
84721   assert( pTrigger || tmask==0 );
84722 #else
84723 # define pTrigger 0
84724 # define isView 0
84725 # define tmask 0
84726 #endif
84727 #ifdef SQLITE_OMIT_VIEW
84728 # undef isView
84729 # define isView 0
84730 #endif
84731
84732   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
84733     goto update_cleanup;
84734   }
84735   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
84736     goto update_cleanup;
84737   }
84738   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
84739   if( aXRef==0 ) goto update_cleanup;
84740   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
84741
84742   /* Allocate a cursors for the main database table and for all indices.
84743   ** The index cursors might not be used, but if they are used they
84744   ** need to occur right after the database cursor.  So go ahead and
84745   ** allocate enough space, just in case.
84746   */
84747   pTabList->a[0].iCursor = iCur = pParse->nTab++;
84748   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84749     pParse->nTab++;
84750   }
84751
84752   /* Initialize the name-context */
84753   memset(&sNC, 0, sizeof(sNC));
84754   sNC.pParse = pParse;
84755   sNC.pSrcList = pTabList;
84756
84757   /* Resolve the column names in all the expressions of the
84758   ** of the UPDATE statement.  Also find the column index
84759   ** for each column to be updated in the pChanges array.  For each
84760   ** column to be updated, make sure we have authorization to change
84761   ** that column.
84762   */
84763   chngRowid = 0;
84764   for(i=0; i<pChanges->nExpr; i++){
84765     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
84766       goto update_cleanup;
84767     }
84768     for(j=0; j<pTab->nCol; j++){
84769       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
84770         if( j==pTab->iPKey ){
84771           chngRowid = 1;
84772           pRowidExpr = pChanges->a[i].pExpr;
84773         }
84774         aXRef[j] = i;
84775         break;
84776       }
84777     }
84778     if( j>=pTab->nCol ){
84779       if( sqlite3IsRowid(pChanges->a[i].zName) ){
84780         chngRowid = 1;
84781         pRowidExpr = pChanges->a[i].pExpr;
84782       }else{
84783         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
84784         goto update_cleanup;
84785       }
84786     }
84787 #ifndef SQLITE_OMIT_AUTHORIZATION
84788     {
84789       int rc;
84790       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
84791                            pTab->aCol[j].zName, db->aDb[iDb].zName);
84792       if( rc==SQLITE_DENY ){
84793         goto update_cleanup;
84794       }else if( rc==SQLITE_IGNORE ){
84795         aXRef[j] = -1;
84796       }
84797     }
84798 #endif
84799   }
84800
84801   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
84802
84803   /* Allocate memory for the array aRegIdx[].  There is one entry in the
84804   ** array for each index associated with table being updated.  Fill in
84805   ** the value with a register number for indices that are to be used
84806   ** and with zero for unused indices.
84807   */
84808   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
84809   if( nIdx>0 ){
84810     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
84811     if( aRegIdx==0 ) goto update_cleanup;
84812   }
84813   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
84814     int reg;
84815     if( chngRowid ){
84816       reg = ++pParse->nMem;
84817     }else{
84818       reg = 0;
84819       for(i=0; i<pIdx->nColumn; i++){
84820         if( aXRef[pIdx->aiColumn[i]]>=0 ){
84821           reg = ++pParse->nMem;
84822           break;
84823         }
84824       }
84825     }
84826     aRegIdx[j] = reg;
84827   }
84828
84829   /* Begin generating code. */
84830   v = sqlite3GetVdbe(pParse);
84831   if( v==0 ) goto update_cleanup;
84832   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
84833   sqlite3BeginWriteOperation(pParse, 1, iDb);
84834
84835 #ifndef SQLITE_OMIT_VIRTUALTABLE
84836   /* Virtual tables must be handled separately */
84837   if( IsVirtual(pTab) ){
84838     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
84839                        pWhere);
84840     pWhere = 0;
84841     pTabList = 0;
84842     goto update_cleanup;
84843   }
84844 #endif
84845
84846   /* Allocate required registers. */
84847   regOldRowid = regNewRowid = ++pParse->nMem;
84848   if( pTrigger || hasFK ){
84849     regOld = pParse->nMem + 1;
84850     pParse->nMem += pTab->nCol;
84851   }
84852   if( chngRowid || pTrigger || hasFK ){
84853     regNewRowid = ++pParse->nMem;
84854   }
84855   regNew = pParse->nMem + 1;
84856   pParse->nMem += pTab->nCol;
84857   regRec = ++pParse->nMem;
84858
84859   /* Start the view context. */
84860   if( isView ){
84861     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
84862   }
84863
84864   /* If we are trying to update a view, realize that view into
84865   ** a ephemeral table.
84866   */
84867 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
84868   if( isView ){
84869     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
84870   }
84871 #endif
84872
84873   /* Resolve the column names in all the expressions in the
84874   ** WHERE clause.
84875   */
84876   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
84877     goto update_cleanup;
84878   }
84879
84880   /* Begin the database scan
84881   */
84882   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
84883   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
84884   if( pWInfo==0 ) goto update_cleanup;
84885   okOnePass = pWInfo->okOnePass;
84886
84887   /* Remember the rowid of every item to be updated.
84888   */
84889   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
84890   if( !okOnePass ){
84891     regRowSet = ++pParse->nMem;
84892     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
84893   }
84894
84895   /* End the database scan loop.
84896   */
84897   sqlite3WhereEnd(pWInfo);
84898
84899   /* Initialize the count of updated rows
84900   */
84901   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
84902     regRowCount = ++pParse->nMem;
84903     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
84904   }
84905
84906   if( !isView ){
84907     /* 
84908     ** Open every index that needs updating.  Note that if any
84909     ** index could potentially invoke a REPLACE conflict resolution 
84910     ** action, then we need to open all indices because we might need
84911     ** to be deleting some records.
84912     */
84913     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
84914     if( onError==OE_Replace ){
84915       openAll = 1;
84916     }else{
84917       openAll = 0;
84918       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84919         if( pIdx->onError==OE_Replace ){
84920           openAll = 1;
84921           break;
84922         }
84923       }
84924     }
84925     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
84926       if( openAll || aRegIdx[i]>0 ){
84927         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
84928         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
84929                        (char*)pKey, P4_KEYINFO_HANDOFF);
84930         assert( pParse->nTab>iCur+i+1 );
84931       }
84932     }
84933   }
84934
84935   /* Top of the update loop */
84936   if( okOnePass ){
84937     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
84938     addr = sqlite3VdbeAddOp0(v, OP_Goto);
84939     sqlite3VdbeJumpHere(v, a1);
84940   }else{
84941     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
84942   }
84943
84944   /* Make cursor iCur point to the record that is being updated. If
84945   ** this record does not exist for some reason (deleted by a trigger,
84946   ** for example, then jump to the next iteration of the RowSet loop.  */
84947   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
84948
84949   /* If the record number will change, set register regNewRowid to
84950   ** contain the new value. If the record number is not being modified,
84951   ** then regNewRowid is the same register as regOldRowid, which is
84952   ** already populated.  */
84953   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
84954   if( chngRowid ){
84955     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
84956     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
84957   }
84958
84959   /* If there are triggers on this table, populate an array of registers 
84960   ** with the required old.* column data.  */
84961   if( hasFK || pTrigger ){
84962     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
84963     oldmask |= sqlite3TriggerColmask(pParse, 
84964         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
84965     );
84966     for(i=0; i<pTab->nCol; i++){
84967       if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
84968         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regOld+i);
84969         sqlite3ColumnDefault(v, pTab, i, regOld+i);
84970       }else{
84971         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
84972       }
84973     }
84974     if( chngRowid==0 ){
84975       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
84976     }
84977   }
84978
84979   /* Populate the array of registers beginning at regNew with the new
84980   ** row data. This array is used to check constaints, create the new
84981   ** table and index records, and as the values for any new.* references
84982   ** made by triggers.
84983   **
84984   ** If there are one or more BEFORE triggers, then do not populate the
84985   ** registers associated with columns that are (a) not modified by
84986   ** this UPDATE statement and (b) not accessed by new.* references. The
84987   ** values for registers not modified by the UPDATE must be reloaded from 
84988   ** the database after the BEFORE triggers are fired anyway (as the trigger 
84989   ** may have modified them). So not loading those that are not going to
84990   ** be used eliminates some redundant opcodes.
84991   */
84992   newmask = sqlite3TriggerColmask(
84993       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
84994   );
84995   for(i=0; i<pTab->nCol; i++){
84996     if( i==pTab->iPKey ){
84997       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
84998     }else{
84999       j = aXRef[i];
85000       if( j>=0 ){
85001         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
85002       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
85003         /* This branch loads the value of a column that will not be changed 
85004         ** into a register. This is done if there are no BEFORE triggers, or
85005         ** if there are one or more BEFORE triggers that use this value via
85006         ** a new.* reference in a trigger program.
85007         */
85008         testcase( i==31 );
85009         testcase( i==32 );
85010         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
85011         sqlite3ColumnDefault(v, pTab, i, regNew+i);
85012       }
85013     }
85014   }
85015
85016   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
85017   ** verified. One could argue that this is wrong.
85018   */
85019   if( tmask&TRIGGER_BEFORE ){
85020     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
85021     sqlite3TableAffinityStr(v, pTab);
85022     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
85023         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
85024
85025     /* The row-trigger may have deleted the row being updated. In this
85026     ** case, jump to the next row. No updates or AFTER triggers are 
85027     ** required. This behaviour - what happens when the row being updated
85028     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
85029     ** documentation.
85030     */
85031     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
85032
85033     /* If it did not delete it, the row-trigger may still have modified 
85034     ** some of the columns of the row being updated. Load the values for 
85035     ** all columns not modified by the update statement into their 
85036     ** registers in case this has happened.
85037     */
85038     for(i=0; i<pTab->nCol; i++){
85039       if( aXRef[i]<0 && i!=pTab->iPKey ){
85040         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
85041         sqlite3ColumnDefault(v, pTab, i, regNew+i);
85042       }
85043     }
85044   }
85045
85046   if( !isView ){
85047     int j1;                       /* Address of jump instruction */
85048
85049     /* Do constraint checks. */
85050     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
85051         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
85052
85053     /* Do FK constraint checks. */
85054     if( hasFK ){
85055       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
85056     }
85057
85058     /* Delete the index entries associated with the current record.  */
85059     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
85060     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
85061   
85062     /* If changing the record number, delete the old record.  */
85063     if( hasFK || chngRowid ){
85064       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
85065     }
85066     sqlite3VdbeJumpHere(v, j1);
85067
85068     if( hasFK ){
85069       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
85070     }
85071   
85072     /* Insert the new index entries and the new record. */
85073     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
85074
85075     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
85076     ** handle rows (possibly in other tables) that refer via a foreign key
85077     ** to the row just updated. */ 
85078     if( hasFK ){
85079       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
85080     }
85081   }
85082
85083   /* Increment the row counter 
85084   */
85085   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
85086     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
85087   }
85088
85089   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
85090       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
85091
85092   /* Repeat the above with the next record to be updated, until
85093   ** all record selected by the WHERE clause have been updated.
85094   */
85095   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
85096   sqlite3VdbeJumpHere(v, addr);
85097
85098   /* Close all tables */
85099   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
85100     if( openAll || aRegIdx[i]>0 ){
85101       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
85102     }
85103   }
85104   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
85105
85106   /* Update the sqlite_sequence table by storing the content of the
85107   ** maximum rowid counter values recorded while inserting into
85108   ** autoincrement tables.
85109   */
85110   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85111     sqlite3AutoincrementEnd(pParse);
85112   }
85113
85114   /*
85115   ** Return the number of rows that were changed. If this routine is 
85116   ** generating code because of a call to sqlite3NestedParse(), do not
85117   ** invoke the callback function.
85118   */
85119   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
85120     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
85121     sqlite3VdbeSetNumCols(v, 1);
85122     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
85123   }
85124
85125 update_cleanup:
85126   sqlite3AuthContextPop(&sContext);
85127   sqlite3DbFree(db, aRegIdx);
85128   sqlite3DbFree(db, aXRef);
85129   sqlite3SrcListDelete(db, pTabList);
85130   sqlite3ExprListDelete(db, pChanges);
85131   sqlite3ExprDelete(db, pWhere);
85132   return;
85133 }
85134 /* Make sure "isView" and other macros defined above are undefined. Otherwise
85135 ** thely may interfere with compilation of other functions in this file
85136 ** (or in another file, if this file becomes part of the amalgamation).  */
85137 #ifdef isView
85138  #undef isView
85139 #endif
85140 #ifdef pTrigger
85141  #undef pTrigger
85142 #endif
85143
85144 #ifndef SQLITE_OMIT_VIRTUALTABLE
85145 /*
85146 ** Generate code for an UPDATE of a virtual table.
85147 **
85148 ** The strategy is that we create an ephemerial table that contains
85149 ** for each row to be changed:
85150 **
85151 **   (A)  The original rowid of that row.
85152 **   (B)  The revised rowid for the row. (note1)
85153 **   (C)  The content of every column in the row.
85154 **
85155 ** Then we loop over this ephemeral table and for each row in
85156 ** the ephermeral table call VUpdate.
85157 **
85158 ** When finished, drop the ephemeral table.
85159 **
85160 ** (note1) Actually, if we know in advance that (A) is always the same
85161 ** as (B) we only store (A), then duplicate (A) when pulling
85162 ** it out of the ephemeral table before calling VUpdate.
85163 */
85164 static void updateVirtualTable(
85165   Parse *pParse,       /* The parsing context */
85166   SrcList *pSrc,       /* The virtual table to be modified */
85167   Table *pTab,         /* The virtual table */
85168   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
85169   Expr *pRowid,        /* Expression used to recompute the rowid */
85170   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
85171   Expr *pWhere         /* WHERE clause of the UPDATE statement */
85172 ){
85173   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
85174   ExprList *pEList = 0;     /* The result set of the SELECT statement */
85175   Select *pSelect = 0;      /* The SELECT statement */
85176   Expr *pExpr;              /* Temporary expression */
85177   int ephemTab;             /* Table holding the result of the SELECT */
85178   int i;                    /* Loop counter */
85179   int addr;                 /* Address of top of loop */
85180   int iReg;                 /* First register in set passed to OP_VUpdate */
85181   sqlite3 *db = pParse->db; /* Database connection */
85182   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
85183   SelectDest dest;
85184
85185   /* Construct the SELECT statement that will find the new values for
85186   ** all updated rows. 
85187   */
85188   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
85189   if( pRowid ){
85190     pEList = sqlite3ExprListAppend(pParse, pEList,
85191                                    sqlite3ExprDup(db, pRowid, 0));
85192   }
85193   assert( pTab->iPKey<0 );
85194   for(i=0; i<pTab->nCol; i++){
85195     if( aXRef[i]>=0 ){
85196       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
85197     }else{
85198       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
85199     }
85200     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
85201   }
85202   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
85203   
85204   /* Create the ephemeral table into which the update results will
85205   ** be stored.
85206   */
85207   assert( v );
85208   ephemTab = pParse->nTab++;
85209   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
85210
85211   /* fill the ephemeral table 
85212   */
85213   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
85214   sqlite3Select(pParse, pSelect, &dest);
85215
85216   /* Generate code to scan the ephemeral table and call VUpdate. */
85217   iReg = ++pParse->nMem;
85218   pParse->nMem += pTab->nCol+1;
85219   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
85220   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
85221   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
85222   for(i=0; i<pTab->nCol; i++){
85223     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
85224   }
85225   sqlite3VtabMakeWritable(pParse, pTab);
85226   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
85227   sqlite3MayAbort(pParse);
85228   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
85229   sqlite3VdbeJumpHere(v, addr);
85230   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
85231
85232   /* Cleanup */
85233   sqlite3SelectDelete(db, pSelect);  
85234 }
85235 #endif /* SQLITE_OMIT_VIRTUALTABLE */
85236
85237 /************** End of update.c **********************************************/
85238 /************** Begin file vacuum.c ******************************************/
85239 /*
85240 ** 2003 April 6
85241 **
85242 ** The author disclaims copyright to this source code.  In place of
85243 ** a legal notice, here is a blessing:
85244 **
85245 **    May you do good and not evil.
85246 **    May you find forgiveness for yourself and forgive others.
85247 **    May you share freely, never taking more than you give.
85248 **
85249 *************************************************************************
85250 ** This file contains code used to implement the VACUUM command.
85251 **
85252 ** Most of the code in this file may be omitted by defining the
85253 ** SQLITE_OMIT_VACUUM macro.
85254 */
85255
85256 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
85257 /*
85258 ** Execute zSql on database db. Return an error code.
85259 */
85260 static int execSql(sqlite3 *db, const char *zSql){
85261   sqlite3_stmt *pStmt;
85262   VVA_ONLY( int rc; )
85263   if( !zSql ){
85264     return SQLITE_NOMEM;
85265   }
85266   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
85267     return sqlite3_errcode(db);
85268   }
85269   VVA_ONLY( rc = ) sqlite3_step(pStmt);
85270   assert( rc!=SQLITE_ROW );
85271   return sqlite3_finalize(pStmt);
85272 }
85273
85274 /*
85275 ** Execute zSql on database db. The statement returns exactly
85276 ** one column. Execute this as SQL on the same database.
85277 */
85278 static int execExecSql(sqlite3 *db, const char *zSql){
85279   sqlite3_stmt *pStmt;
85280   int rc;
85281
85282   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
85283   if( rc!=SQLITE_OK ) return rc;
85284
85285   while( SQLITE_ROW==sqlite3_step(pStmt) ){
85286     rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
85287     if( rc!=SQLITE_OK ){
85288       sqlite3_finalize(pStmt);
85289       return rc;
85290     }
85291   }
85292
85293   return sqlite3_finalize(pStmt);
85294 }
85295
85296 /*
85297 ** The non-standard VACUUM command is used to clean up the database,
85298 ** collapse free space, etc.  It is modelled after the VACUUM command
85299 ** in PostgreSQL.
85300 **
85301 ** In version 1.0.x of SQLite, the VACUUM command would call
85302 ** gdbm_reorganize() on all the database tables.  But beginning
85303 ** with 2.0.0, SQLite no longer uses GDBM so this command has
85304 ** become a no-op.
85305 */
85306 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
85307   Vdbe *v = sqlite3GetVdbe(pParse);
85308   if( v ){
85309     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
85310   }
85311   return;
85312 }
85313
85314 /*
85315 ** This routine implements the OP_Vacuum opcode of the VDBE.
85316 */
85317 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
85318   int rc = SQLITE_OK;     /* Return code from service routines */
85319   Btree *pMain;           /* The database being vacuumed */
85320   Btree *pTemp;           /* The temporary database we vacuum into */
85321   char *zSql = 0;         /* SQL statements */
85322   int saved_flags;        /* Saved value of the db->flags */
85323   int saved_nChange;      /* Saved value of db->nChange */
85324   int saved_nTotalChange; /* Saved value of db->nTotalChange */
85325   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
85326   Db *pDb = 0;            /* Database to detach at end of vacuum */
85327   int isMemDb;            /* True if vacuuming a :memory: database */
85328   int nRes;
85329
85330   if( !db->autoCommit ){
85331     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
85332     return SQLITE_ERROR;
85333   }
85334
85335   /* Save the current value of the database flags so that it can be 
85336   ** restored before returning. Then set the writable-schema flag, and
85337   ** disable CHECK and foreign key constraints.  */
85338   saved_flags = db->flags;
85339   saved_nChange = db->nChange;
85340   saved_nTotalChange = db->nTotalChange;
85341   saved_xTrace = db->xTrace;
85342   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
85343   db->flags &= ~SQLITE_ForeignKeys;
85344   db->xTrace = 0;
85345
85346   pMain = db->aDb[0].pBt;
85347   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
85348
85349   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
85350   ** can be set to 'off' for this file, as it is not recovered if a crash
85351   ** occurs anyway. The integrity of the database is maintained by a
85352   ** (possibly synchronous) transaction opened on the main database before
85353   ** sqlite3BtreeCopyFile() is called.
85354   **
85355   ** An optimisation would be to use a non-journaled pager.
85356   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
85357   ** that actually made the VACUUM run slower.  Very little journalling
85358   ** actually occurs when doing a vacuum since the vacuum_db is initially
85359   ** empty.  Only the journal header is written.  Apparently it takes more
85360   ** time to parse and run the PRAGMA to turn journalling off than it does
85361   ** to write the journal header file.
85362   */
85363   zSql = "ATTACH '' AS vacuum_db;";
85364   rc = execSql(db, zSql);
85365   if( rc!=SQLITE_OK ) goto end_of_vacuum;
85366   pDb = &db->aDb[db->nDb-1];
85367   assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
85368   pTemp = db->aDb[db->nDb-1].pBt;
85369
85370   /* The call to execSql() to attach the temp database has left the file
85371   ** locked (as there was more than one active statement when the transaction
85372   ** to read the schema was concluded. Unlock it here so that this doesn't
85373   ** cause problems for the call to BtreeSetPageSize() below.  */
85374   sqlite3BtreeCommit(pTemp);
85375
85376   nRes = sqlite3BtreeGetReserve(pMain);
85377
85378   /* A VACUUM cannot change the pagesize of an encrypted database. */
85379 #ifdef SQLITE_HAS_CODEC
85380   if( db->nextPagesize ){
85381     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
85382     int nKey;
85383     char *zKey;
85384     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
85385     if( nKey ) db->nextPagesize = 0;
85386   }
85387 #endif
85388
85389   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
85390    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
85391    || NEVER(db->mallocFailed)
85392   ){
85393     rc = SQLITE_NOMEM;
85394     goto end_of_vacuum;
85395   }
85396   rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
85397   if( rc!=SQLITE_OK ){
85398     goto end_of_vacuum;
85399   }
85400
85401 #ifndef SQLITE_OMIT_AUTOVACUUM
85402   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
85403                                            sqlite3BtreeGetAutoVacuum(pMain));
85404 #endif
85405
85406   /* Begin a transaction */
85407   rc = execSql(db, "BEGIN EXCLUSIVE;");
85408   if( rc!=SQLITE_OK ) goto end_of_vacuum;
85409
85410   /* Query the schema of the main database. Create a mirror schema
85411   ** in the temporary database.
85412   */
85413   rc = execExecSql(db, 
85414       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
85415       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
85416       "   AND rootpage>0"
85417   );
85418   if( rc!=SQLITE_OK ) goto end_of_vacuum;
85419   rc = execExecSql(db, 
85420       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
85421       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
85422   if( rc!=SQLITE_OK ) goto end_of_vacuum;
85423   rc = execExecSql(db, 
85424       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
85425       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
85426   if( rc!=SQLITE_OK ) goto end_of_vacuum;
85427
85428   /* Loop through the tables in the main database. For each, do
85429   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
85430   ** the contents to the temporary database.
85431   */
85432   rc = execExecSql(db, 
85433       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
85434       "|| ' SELECT * FROM main.' || quote(name) || ';'"
85435       "FROM main.sqlite_master "
85436       "WHERE type = 'table' AND name!='sqlite_sequence' "
85437       "  AND rootpage>0"
85438
85439   );
85440   if( rc!=SQLITE_OK ) goto end_of_vacuum;
85441
85442   /* Copy over the sequence table
85443   */
85444   rc = execExecSql(db, 
85445       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
85446       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
85447   );
85448   if( rc!=SQLITE_OK ) goto end_of_vacuum;
85449   rc = execExecSql(db, 
85450       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
85451       "|| ' SELECT * FROM main.' || quote(name) || ';' "
85452       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
85453   );
85454   if( rc!=SQLITE_OK ) goto end_of_vacuum;
85455
85456
85457   /* Copy the triggers, views, and virtual tables from the main database
85458   ** over to the temporary database.  None of these objects has any
85459   ** associated storage, so all we have to do is copy their entries
85460   ** from the SQLITE_MASTER table.
85461   */
85462   rc = execSql(db,
85463       "INSERT INTO vacuum_db.sqlite_master "
85464       "  SELECT type, name, tbl_name, rootpage, sql"
85465       "    FROM main.sqlite_master"
85466       "   WHERE type='view' OR type='trigger'"
85467       "      OR (type='table' AND rootpage=0)"
85468   );
85469   if( rc ) goto end_of_vacuum;
85470
85471   /* At this point, unless the main db was completely empty, there is now a
85472   ** transaction open on the vacuum database, but not on the main database.
85473   ** Open a btree level transaction on the main database. This allows a
85474   ** call to sqlite3BtreeCopyFile(). The main database btree level
85475   ** transaction is then committed, so the SQL level never knows it was
85476   ** opened for writing. This way, the SQL transaction used to create the
85477   ** temporary database never needs to be committed.
85478   */
85479   {
85480     u32 meta;
85481     int i;
85482
85483     /* This array determines which meta meta values are preserved in the
85484     ** vacuum.  Even entries are the meta value number and odd entries
85485     ** are an increment to apply to the meta value after the vacuum.
85486     ** The increment is used to increase the schema cookie so that other
85487     ** connections to the same database will know to reread the schema.
85488     */
85489     static const unsigned char aCopy[] = {
85490        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
85491        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
85492        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
85493        BTREE_USER_VERSION,       0,  /* Preserve the user version */
85494     };
85495
85496     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
85497     assert( 1==sqlite3BtreeIsInTrans(pMain) );
85498
85499     /* Copy Btree meta values */
85500     for(i=0; i<ArraySize(aCopy); i+=2){
85501       /* GetMeta() and UpdateMeta() cannot fail in this context because
85502       ** we already have page 1 loaded into cache and marked dirty. */
85503       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
85504       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
85505       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
85506     }
85507
85508     rc = sqlite3BtreeCopyFile(pMain, pTemp);
85509     if( rc!=SQLITE_OK ) goto end_of_vacuum;
85510     rc = sqlite3BtreeCommit(pTemp);
85511     if( rc!=SQLITE_OK ) goto end_of_vacuum;
85512 #ifndef SQLITE_OMIT_AUTOVACUUM
85513     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
85514 #endif
85515   }
85516
85517   assert( rc==SQLITE_OK );
85518   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
85519
85520 end_of_vacuum:
85521   /* Restore the original value of db->flags */
85522   db->flags = saved_flags;
85523   db->nChange = saved_nChange;
85524   db->nTotalChange = saved_nTotalChange;
85525   db->xTrace = saved_xTrace;
85526
85527   /* Currently there is an SQL level transaction open on the vacuum
85528   ** database. No locks are held on any other files (since the main file
85529   ** was committed at the btree level). So it safe to end the transaction
85530   ** by manually setting the autoCommit flag to true and detaching the
85531   ** vacuum database. The vacuum_db journal file is deleted when the pager
85532   ** is closed by the DETACH.
85533   */
85534   db->autoCommit = 1;
85535
85536   if( pDb ){
85537     sqlite3BtreeClose(pDb->pBt);
85538     pDb->pBt = 0;
85539     pDb->pSchema = 0;
85540   }
85541
85542   sqlite3ResetInternalSchema(db, 0);
85543
85544   return rc;
85545 }
85546 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
85547
85548 /************** End of vacuum.c **********************************************/
85549 /************** Begin file vtab.c ********************************************/
85550 /*
85551 ** 2006 June 10
85552 **
85553 ** The author disclaims copyright to this source code.  In place of
85554 ** a legal notice, here is a blessing:
85555 **
85556 **    May you do good and not evil.
85557 **    May you find forgiveness for yourself and forgive others.
85558 **    May you share freely, never taking more than you give.
85559 **
85560 *************************************************************************
85561 ** This file contains code used to help implement virtual tables.
85562 */
85563 #ifndef SQLITE_OMIT_VIRTUALTABLE
85564
85565 /*
85566 ** The actual function that does the work of creating a new module.
85567 ** This function implements the sqlite3_create_module() and
85568 ** sqlite3_create_module_v2() interfaces.
85569 */
85570 static int createModule(
85571   sqlite3 *db,                    /* Database in which module is registered */
85572   const char *zName,              /* Name assigned to this module */
85573   const sqlite3_module *pModule,  /* The definition of the module */
85574   void *pAux,                     /* Context pointer for xCreate/xConnect */
85575   void (*xDestroy)(void *)        /* Module destructor function */
85576 ){
85577   int rc, nName;
85578   Module *pMod;
85579
85580   sqlite3_mutex_enter(db->mutex);
85581   nName = sqlite3Strlen30(zName);
85582   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
85583   if( pMod ){
85584     Module *pDel;
85585     char *zCopy = (char *)(&pMod[1]);
85586     memcpy(zCopy, zName, nName+1);
85587     pMod->zName = zCopy;
85588     pMod->pModule = pModule;
85589     pMod->pAux = pAux;
85590     pMod->xDestroy = xDestroy;
85591     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
85592     if( pDel && pDel->xDestroy ){
85593       pDel->xDestroy(pDel->pAux);
85594     }
85595     sqlite3DbFree(db, pDel);
85596     if( pDel==pMod ){
85597       db->mallocFailed = 1;
85598     }
85599     sqlite3ResetInternalSchema(db, 0);
85600   }else if( xDestroy ){
85601     xDestroy(pAux);
85602   }
85603   rc = sqlite3ApiExit(db, SQLITE_OK);
85604   sqlite3_mutex_leave(db->mutex);
85605   return rc;
85606 }
85607
85608
85609 /*
85610 ** External API function used to create a new virtual-table module.
85611 */
85612 SQLITE_API int sqlite3_create_module(
85613   sqlite3 *db,                    /* Database in which module is registered */
85614   const char *zName,              /* Name assigned to this module */
85615   const sqlite3_module *pModule,  /* The definition of the module */
85616   void *pAux                      /* Context pointer for xCreate/xConnect */
85617 ){
85618   return createModule(db, zName, pModule, pAux, 0);
85619 }
85620
85621 /*
85622 ** External API function used to create a new virtual-table module.
85623 */
85624 SQLITE_API int sqlite3_create_module_v2(
85625   sqlite3 *db,                    /* Database in which module is registered */
85626   const char *zName,              /* Name assigned to this module */
85627   const sqlite3_module *pModule,  /* The definition of the module */
85628   void *pAux,                     /* Context pointer for xCreate/xConnect */
85629   void (*xDestroy)(void *)        /* Module destructor function */
85630 ){
85631   return createModule(db, zName, pModule, pAux, xDestroy);
85632 }
85633
85634 /*
85635 ** Lock the virtual table so that it cannot be disconnected.
85636 ** Locks nest.  Every lock should have a corresponding unlock.
85637 ** If an unlock is omitted, resources leaks will occur.  
85638 **
85639 ** If a disconnect is attempted while a virtual table is locked,
85640 ** the disconnect is deferred until all locks have been removed.
85641 */
85642 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
85643   pVTab->nRef++;
85644 }
85645
85646
85647 /*
85648 ** pTab is a pointer to a Table structure representing a virtual-table.
85649 ** Return a pointer to the VTable object used by connection db to access 
85650 ** this virtual-table, if one has been created, or NULL otherwise.
85651 */
85652 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
85653   VTable *pVtab;
85654   assert( IsVirtual(pTab) );
85655   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
85656   return pVtab;
85657 }
85658
85659 /*
85660 ** Decrement the ref-count on a virtual table object. When the ref-count
85661 ** reaches zero, call the xDisconnect() method to delete the object.
85662 */
85663 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
85664   sqlite3 *db = pVTab->db;
85665
85666   assert( db );
85667   assert( pVTab->nRef>0 );
85668   assert( sqlite3SafetyCheckOk(db) );
85669
85670   pVTab->nRef--;
85671   if( pVTab->nRef==0 ){
85672     sqlite3_vtab *p = pVTab->pVtab;
85673     if( p ){
85674 #ifdef SQLITE_DEBUG
85675       if( pVTab->db->magic==SQLITE_MAGIC_BUSY ){
85676         (void)sqlite3SafetyOff(db);
85677         p->pModule->xDisconnect(p);
85678         (void)sqlite3SafetyOn(db);
85679       } else
85680 #endif
85681       {
85682         p->pModule->xDisconnect(p);
85683       }
85684     }
85685     sqlite3DbFree(db, pVTab);
85686   }
85687 }
85688
85689 /*
85690 ** Table p is a virtual table. This function moves all elements in the
85691 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
85692 ** database connections to be disconnected at the next opportunity. 
85693 ** Except, if argument db is not NULL, then the entry associated with
85694 ** connection db is left in the p->pVTable list.
85695 */
85696 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
85697   VTable *pRet = 0;
85698   VTable *pVTable = p->pVTable;
85699   p->pVTable = 0;
85700
85701   /* Assert that the mutex (if any) associated with the BtShared database 
85702   ** that contains table p is held by the caller. See header comments 
85703   ** above function sqlite3VtabUnlockList() for an explanation of why
85704   ** this makes it safe to access the sqlite3.pDisconnect list of any
85705   ** database connection that may have an entry in the p->pVTable list.  */
85706   assert( db==0 ||
85707     sqlite3BtreeHoldsMutex(db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].pBt) 
85708   );
85709
85710   while( pVTable ){
85711     sqlite3 *db2 = pVTable->db;
85712     VTable *pNext = pVTable->pNext;
85713     assert( db2 );
85714     if( db2==db ){
85715       pRet = pVTable;
85716       p->pVTable = pRet;
85717       pRet->pNext = 0;
85718     }else{
85719       pVTable->pNext = db2->pDisconnect;
85720       db2->pDisconnect = pVTable;
85721     }
85722     pVTable = pNext;
85723   }
85724
85725   assert( !db || pRet );
85726   return pRet;
85727 }
85728
85729
85730 /*
85731 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
85732 **
85733 ** This function may only be called when the mutexes associated with all
85734 ** shared b-tree databases opened using connection db are held by the 
85735 ** caller. This is done to protect the sqlite3.pDisconnect list. The
85736 ** sqlite3.pDisconnect list is accessed only as follows:
85737 **
85738 **   1) By this function. In this case, all BtShared mutexes and the mutex
85739 **      associated with the database handle itself must be held.
85740 **
85741 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
85742 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
85743 **      associated with the database the virtual table is stored in is held
85744 **      or, if the virtual table is stored in a non-sharable database, then
85745 **      the database handle mutex is held.
85746 **
85747 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
85748 ** by multiple threads. It is thread-safe.
85749 */
85750 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
85751   VTable *p = db->pDisconnect;
85752   db->pDisconnect = 0;
85753
85754   assert( sqlite3BtreeHoldsAllMutexes(db) );
85755   assert( sqlite3_mutex_held(db->mutex) );
85756
85757   if( p ){
85758     sqlite3ExpirePreparedStatements(db);
85759     do {
85760       VTable *pNext = p->pNext;
85761       sqlite3VtabUnlock(p);
85762       p = pNext;
85763     }while( p );
85764   }
85765 }
85766
85767 /*
85768 ** Clear any and all virtual-table information from the Table record.
85769 ** This routine is called, for example, just before deleting the Table
85770 ** record.
85771 **
85772 ** Since it is a virtual-table, the Table structure contains a pointer
85773 ** to the head of a linked list of VTable structures. Each VTable 
85774 ** structure is associated with a single sqlite3* user of the schema.
85775 ** The reference count of the VTable structure associated with database 
85776 ** connection db is decremented immediately (which may lead to the 
85777 ** structure being xDisconnected and free). Any other VTable structures
85778 ** in the list are moved to the sqlite3.pDisconnect list of the associated 
85779 ** database connection.
85780 */
85781 SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
85782   vtabDisconnectAll(0, p);
85783   if( p->azModuleArg ){
85784     int i;
85785     for(i=0; i<p->nModuleArg; i++){
85786       sqlite3DbFree(p->dbMem, p->azModuleArg[i]);
85787     }
85788     sqlite3DbFree(p->dbMem, p->azModuleArg);
85789   }
85790 }
85791
85792 /*
85793 ** Add a new module argument to pTable->azModuleArg[].
85794 ** The string is not copied - the pointer is stored.  The
85795 ** string will be freed automatically when the table is
85796 ** deleted.
85797 */
85798 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
85799   int i = pTable->nModuleArg++;
85800   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
85801   char **azModuleArg;
85802   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
85803   if( azModuleArg==0 ){
85804     int j;
85805     for(j=0; j<i; j++){
85806       sqlite3DbFree(db, pTable->azModuleArg[j]);
85807     }
85808     sqlite3DbFree(db, zArg);
85809     sqlite3DbFree(db, pTable->azModuleArg);
85810     pTable->nModuleArg = 0;
85811   }else{
85812     azModuleArg[i] = zArg;
85813     azModuleArg[i+1] = 0;
85814   }
85815   pTable->azModuleArg = azModuleArg;
85816 }
85817
85818 /*
85819 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
85820 ** statement.  The module name has been parsed, but the optional list
85821 ** of parameters that follow the module name are still pending.
85822 */
85823 SQLITE_PRIVATE void sqlite3VtabBeginParse(
85824   Parse *pParse,        /* Parsing context */
85825   Token *pName1,        /* Name of new table, or database name */
85826   Token *pName2,        /* Name of new table or NULL */
85827   Token *pModuleName    /* Name of the module for the virtual table */
85828 ){
85829   int iDb;              /* The database the table is being created in */
85830   Table *pTable;        /* The new virtual table */
85831   sqlite3 *db;          /* Database connection */
85832
85833   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
85834   pTable = pParse->pNewTable;
85835   if( pTable==0 ) return;
85836   assert( 0==pTable->pIndex );
85837
85838   db = pParse->db;
85839   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
85840   assert( iDb>=0 );
85841
85842   pTable->tabFlags |= TF_Virtual;
85843   pTable->nModuleArg = 0;
85844   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
85845   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
85846   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
85847   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
85848
85849 #ifndef SQLITE_OMIT_AUTHORIZATION
85850   /* Creating a virtual table invokes the authorization callback twice.
85851   ** The first invocation, to obtain permission to INSERT a row into the
85852   ** sqlite_master table, has already been made by sqlite3StartTable().
85853   ** The second call, to obtain permission to create the table, is made now.
85854   */
85855   if( pTable->azModuleArg ){
85856     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
85857             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
85858   }
85859 #endif
85860 }
85861
85862 /*
85863 ** This routine takes the module argument that has been accumulating
85864 ** in pParse->zArg[] and appends it to the list of arguments on the
85865 ** virtual table currently under construction in pParse->pTable.
85866 */
85867 static void addArgumentToVtab(Parse *pParse){
85868   if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
85869     const char *z = (const char*)pParse->sArg.z;
85870     int n = pParse->sArg.n;
85871     sqlite3 *db = pParse->db;
85872     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
85873   }
85874 }
85875
85876 /*
85877 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
85878 ** has been completely parsed.
85879 */
85880 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
85881   Table *pTab = pParse->pNewTable;  /* The table being constructed */
85882   sqlite3 *db = pParse->db;         /* The database connection */
85883
85884   if( pTab==0 ) return;
85885   addArgumentToVtab(pParse);
85886   pParse->sArg.z = 0;
85887   if( pTab->nModuleArg<1 ) return;
85888   
85889   /* If the CREATE VIRTUAL TABLE statement is being entered for the
85890   ** first time (in other words if the virtual table is actually being
85891   ** created now instead of just being read out of sqlite_master) then
85892   ** do additional initialization work and store the statement text
85893   ** in the sqlite_master table.
85894   */
85895   if( !db->init.busy ){
85896     char *zStmt;
85897     char *zWhere;
85898     int iDb;
85899     Vdbe *v;
85900
85901     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
85902     if( pEnd ){
85903       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
85904     }
85905     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
85906
85907     /* A slot for the record has already been allocated in the 
85908     ** SQLITE_MASTER table.  We just need to update that slot with all
85909     ** the information we've collected.  
85910     **
85911     ** The VM register number pParse->regRowid holds the rowid of an
85912     ** entry in the sqlite_master table tht was created for this vtab
85913     ** by sqlite3StartTable().
85914     */
85915     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
85916     sqlite3NestedParse(pParse,
85917       "UPDATE %Q.%s "
85918          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
85919        "WHERE rowid=#%d",
85920       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
85921       pTab->zName,
85922       pTab->zName,
85923       zStmt,
85924       pParse->regRowid
85925     );
85926     sqlite3DbFree(db, zStmt);
85927     v = sqlite3GetVdbe(pParse);
85928     sqlite3ChangeCookie(pParse, iDb);
85929
85930     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
85931     zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
85932     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
85933     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
85934                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
85935   }
85936
85937   /* If we are rereading the sqlite_master table create the in-memory
85938   ** record of the table. The xConnect() method is not called until
85939   ** the first time the virtual table is used in an SQL statement. This
85940   ** allows a schema that contains virtual tables to be loaded before
85941   ** the required virtual table implementations are registered.  */
85942   else {
85943     Table *pOld;
85944     Schema *pSchema = pTab->pSchema;
85945     const char *zName = pTab->zName;
85946     int nName = sqlite3Strlen30(zName);
85947     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
85948     if( pOld ){
85949       db->mallocFailed = 1;
85950       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
85951       return;
85952     }
85953     pSchema->db = pParse->db;
85954     pParse->pNewTable = 0;
85955   }
85956 }
85957
85958 /*
85959 ** The parser calls this routine when it sees the first token
85960 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
85961 */
85962 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
85963   addArgumentToVtab(pParse);
85964   pParse->sArg.z = 0;
85965   pParse->sArg.n = 0;
85966 }
85967
85968 /*
85969 ** The parser calls this routine for each token after the first token
85970 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
85971 */
85972 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
85973   Token *pArg = &pParse->sArg;
85974   if( pArg->z==0 ){
85975     pArg->z = p->z;
85976     pArg->n = p->n;
85977   }else{
85978     assert(pArg->z < p->z);
85979     pArg->n = (int)(&p->z[p->n] - pArg->z);
85980   }
85981 }
85982
85983 /*
85984 ** Invoke a virtual table constructor (either xCreate or xConnect). The
85985 ** pointer to the function to invoke is passed as the fourth parameter
85986 ** to this procedure.
85987 */
85988 static int vtabCallConstructor(
85989   sqlite3 *db, 
85990   Table *pTab,
85991   Module *pMod,
85992   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
85993   char **pzErr
85994 ){
85995   VTable *pVTable;
85996   int rc;
85997   const char *const*azArg = (const char *const*)pTab->azModuleArg;
85998   int nArg = pTab->nModuleArg;
85999   char *zErr = 0;
86000   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
86001
86002   if( !zModuleName ){
86003     return SQLITE_NOMEM;
86004   }
86005
86006   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
86007   if( !pVTable ){
86008     sqlite3DbFree(db, zModuleName);
86009     return SQLITE_NOMEM;
86010   }
86011   pVTable->db = db;
86012   pVTable->pMod = pMod;
86013
86014   assert( !db->pVTab );
86015   assert( xConstruct );
86016   db->pVTab = pTab;
86017
86018   /* Invoke the virtual table constructor */
86019   (void)sqlite3SafetyOff(db);
86020   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
86021   (void)sqlite3SafetyOn(db);
86022   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
86023
86024   if( SQLITE_OK!=rc ){
86025     if( zErr==0 ){
86026       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
86027     }else {
86028       *pzErr = sqlite3MPrintf(db, "%s", zErr);
86029       sqlite3DbFree(db, zErr);
86030     }
86031     sqlite3DbFree(db, pVTable);
86032   }else if( ALWAYS(pVTable->pVtab) ){
86033     /* Justification of ALWAYS():  A correct vtab constructor must allocate
86034     ** the sqlite3_vtab object if successful.  */
86035     pVTable->pVtab->pModule = pMod->pModule;
86036     pVTable->nRef = 1;
86037     if( db->pVTab ){
86038       const char *zFormat = "vtable constructor did not declare schema: %s";
86039       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
86040       sqlite3VtabUnlock(pVTable);
86041       rc = SQLITE_ERROR;
86042     }else{
86043       int iCol;
86044       /* If everything went according to plan, link the new VTable structure
86045       ** into the linked list headed by pTab->pVTable. Then loop through the 
86046       ** columns of the table to see if any of them contain the token "hidden".
86047       ** If so, set the Column.isHidden flag and remove the token from
86048       ** the type string.  */
86049       pVTable->pNext = pTab->pVTable;
86050       pTab->pVTable = pVTable;
86051
86052       for(iCol=0; iCol<pTab->nCol; iCol++){
86053         char *zType = pTab->aCol[iCol].zType;
86054         int nType;
86055         int i = 0;
86056         if( !zType ) continue;
86057         nType = sqlite3Strlen30(zType);
86058         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
86059           for(i=0; i<nType; i++){
86060             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
86061              && (zType[i+7]=='\0' || zType[i+7]==' ')
86062             ){
86063               i++;
86064               break;
86065             }
86066           }
86067         }
86068         if( i<nType ){
86069           int j;
86070           int nDel = 6 + (zType[i+6] ? 1 : 0);
86071           for(j=i; (j+nDel)<=nType; j++){
86072             zType[j] = zType[j+nDel];
86073           }
86074           if( zType[i]=='\0' && i>0 ){
86075             assert(zType[i-1]==' ');
86076             zType[i-1] = '\0';
86077           }
86078           pTab->aCol[iCol].isHidden = 1;
86079         }
86080       }
86081     }
86082   }
86083
86084   sqlite3DbFree(db, zModuleName);
86085   db->pVTab = 0;
86086   return rc;
86087 }
86088
86089 /*
86090 ** This function is invoked by the parser to call the xConnect() method
86091 ** of the virtual table pTab. If an error occurs, an error code is returned 
86092 ** and an error left in pParse.
86093 **
86094 ** This call is a no-op if table pTab is not a virtual table.
86095 */
86096 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
86097   sqlite3 *db = pParse->db;
86098   const char *zMod;
86099   Module *pMod;
86100   int rc;
86101
86102   assert( pTab );
86103   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
86104     return SQLITE_OK;
86105   }
86106
86107   /* Locate the required virtual table module */
86108   zMod = pTab->azModuleArg[0];
86109   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
86110
86111   if( !pMod ){
86112     const char *zModule = pTab->azModuleArg[0];
86113     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
86114     rc = SQLITE_ERROR;
86115   }else{
86116     char *zErr = 0;
86117     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
86118     if( rc!=SQLITE_OK ){
86119       sqlite3ErrorMsg(pParse, "%s", zErr);
86120     }
86121     sqlite3DbFree(db, zErr);
86122   }
86123
86124   return rc;
86125 }
86126
86127 /*
86128 ** Add the virtual table pVTab to the array sqlite3.aVTrans[].
86129 */
86130 static int addToVTrans(sqlite3 *db, VTable *pVTab){
86131   const int ARRAY_INCR = 5;
86132
86133   /* Grow the sqlite3.aVTrans array if required */
86134   if( (db->nVTrans%ARRAY_INCR)==0 ){
86135     VTable **aVTrans;
86136     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
86137     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
86138     if( !aVTrans ){
86139       return SQLITE_NOMEM;
86140     }
86141     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
86142     db->aVTrans = aVTrans;
86143   }
86144
86145   /* Add pVtab to the end of sqlite3.aVTrans */
86146   db->aVTrans[db->nVTrans++] = pVTab;
86147   sqlite3VtabLock(pVTab);
86148   return SQLITE_OK;
86149 }
86150
86151 /*
86152 ** This function is invoked by the vdbe to call the xCreate method
86153 ** of the virtual table named zTab in database iDb. 
86154 **
86155 ** If an error occurs, *pzErr is set to point an an English language
86156 ** description of the error and an SQLITE_XXX error code is returned.
86157 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
86158 */
86159 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
86160   int rc = SQLITE_OK;
86161   Table *pTab;
86162   Module *pMod;
86163   const char *zMod;
86164
86165   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
86166   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
86167
86168   /* Locate the required virtual table module */
86169   zMod = pTab->azModuleArg[0];
86170   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
86171
86172   /* If the module has been registered and includes a Create method, 
86173   ** invoke it now. If the module has not been registered, return an 
86174   ** error. Otherwise, do nothing.
86175   */
86176   if( !pMod ){
86177     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
86178     rc = SQLITE_ERROR;
86179   }else{
86180     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
86181   }
86182
86183   /* Justification of ALWAYS():  The xConstructor method is required to
86184   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
86185   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
86186       rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
86187   }
86188
86189   return rc;
86190 }
86191
86192 /*
86193 ** This function is used to set the schema of a virtual table.  It is only
86194 ** valid to call this function from within the xCreate() or xConnect() of a
86195 ** virtual table module.
86196 */
86197 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
86198   Parse *pParse;
86199
86200   int rc = SQLITE_OK;
86201   Table *pTab;
86202   char *zErr = 0;
86203
86204   sqlite3_mutex_enter(db->mutex);
86205   pTab = db->pVTab;
86206   if( !pTab ){
86207     sqlite3Error(db, SQLITE_MISUSE, 0);
86208     sqlite3_mutex_leave(db->mutex);
86209     return SQLITE_MISUSE;
86210   }
86211   assert( (pTab->tabFlags & TF_Virtual)!=0 );
86212
86213   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
86214   if( pParse==0 ){
86215     rc = SQLITE_NOMEM;
86216   }else{
86217     pParse->declareVtab = 1;
86218     pParse->db = db;
86219   
86220     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
86221      && pParse->pNewTable
86222      && !db->mallocFailed
86223      && !pParse->pNewTable->pSelect
86224      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
86225     ){
86226       if( !pTab->aCol ){
86227         pTab->aCol = pParse->pNewTable->aCol;
86228         pTab->nCol = pParse->pNewTable->nCol;
86229         pParse->pNewTable->nCol = 0;
86230         pParse->pNewTable->aCol = 0;
86231       }
86232       db->pVTab = 0;
86233     }else{
86234       sqlite3Error(db, SQLITE_ERROR, zErr);
86235       sqlite3DbFree(db, zErr);
86236       rc = SQLITE_ERROR;
86237     }
86238     pParse->declareVtab = 0;
86239   
86240     if( pParse->pVdbe ){
86241       sqlite3VdbeFinalize(pParse->pVdbe);
86242     }
86243     sqlite3DeleteTable(pParse->pNewTable);
86244     sqlite3StackFree(db, pParse);
86245   }
86246
86247   assert( (rc&0xff)==rc );
86248   rc = sqlite3ApiExit(db, rc);
86249   sqlite3_mutex_leave(db->mutex);
86250   return rc;
86251 }
86252
86253 /*
86254 ** This function is invoked by the vdbe to call the xDestroy method
86255 ** of the virtual table named zTab in database iDb. This occurs
86256 ** when a DROP TABLE is mentioned.
86257 **
86258 ** This call is a no-op if zTab is not a virtual table.
86259 */
86260 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
86261   int rc = SQLITE_OK;
86262   Table *pTab;
86263
86264   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
86265   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
86266     VTable *p = vtabDisconnectAll(db, pTab);
86267
86268     rc = sqlite3SafetyOff(db);
86269     assert( rc==SQLITE_OK );
86270     rc = p->pMod->pModule->xDestroy(p->pVtab);
86271     (void)sqlite3SafetyOn(db);
86272
86273     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
86274     if( rc==SQLITE_OK ){
86275       assert( pTab->pVTable==p && p->pNext==0 );
86276       p->pVtab = 0;
86277       pTab->pVTable = 0;
86278       sqlite3VtabUnlock(p);
86279     }
86280   }
86281
86282   return rc;
86283 }
86284
86285 /*
86286 ** This function invokes either the xRollback or xCommit method
86287 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
86288 ** called is identified by the second argument, "offset", which is
86289 ** the offset of the method to call in the sqlite3_module structure.
86290 **
86291 ** The array is cleared after invoking the callbacks. 
86292 */
86293 static void callFinaliser(sqlite3 *db, int offset){
86294   int i;
86295   if( db->aVTrans ){
86296     for(i=0; i<db->nVTrans; i++){
86297       VTable *pVTab = db->aVTrans[i];
86298       sqlite3_vtab *p = pVTab->pVtab;
86299       if( p ){
86300         int (*x)(sqlite3_vtab *);
86301         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
86302         if( x ) x(p);
86303       }
86304       sqlite3VtabUnlock(pVTab);
86305     }
86306     sqlite3DbFree(db, db->aVTrans);
86307     db->nVTrans = 0;
86308     db->aVTrans = 0;
86309   }
86310 }
86311
86312 /*
86313 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
86314 ** array. Return the error code for the first error that occurs, or
86315 ** SQLITE_OK if all xSync operations are successful.
86316 **
86317 ** Set *pzErrmsg to point to a buffer that should be released using 
86318 ** sqlite3DbFree() containing an error message, if one is available.
86319 */
86320 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
86321   int i;
86322   int rc = SQLITE_OK;
86323   int rcsafety;
86324   VTable **aVTrans = db->aVTrans;
86325
86326   rc = sqlite3SafetyOff(db);
86327   db->aVTrans = 0;
86328   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
86329     int (*x)(sqlite3_vtab *);
86330     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
86331     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
86332       rc = x(pVtab);
86333       sqlite3DbFree(db, *pzErrmsg);
86334       *pzErrmsg = pVtab->zErrMsg;
86335       pVtab->zErrMsg = 0;
86336     }
86337   }
86338   db->aVTrans = aVTrans;
86339   rcsafety = sqlite3SafetyOn(db);
86340
86341   if( rc==SQLITE_OK ){
86342     rc = rcsafety;
86343   }
86344   return rc;
86345 }
86346
86347 /*
86348 ** Invoke the xRollback method of all virtual tables in the 
86349 ** sqlite3.aVTrans array. Then clear the array itself.
86350 */
86351 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
86352   callFinaliser(db, offsetof(sqlite3_module,xRollback));
86353   return SQLITE_OK;
86354 }
86355
86356 /*
86357 ** Invoke the xCommit method of all virtual tables in the 
86358 ** sqlite3.aVTrans array. Then clear the array itself.
86359 */
86360 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
86361   callFinaliser(db, offsetof(sqlite3_module,xCommit));
86362   return SQLITE_OK;
86363 }
86364
86365 /*
86366 ** If the virtual table pVtab supports the transaction interface
86367 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
86368 ** not currently open, invoke the xBegin method now.
86369 **
86370 ** If the xBegin call is successful, place the sqlite3_vtab pointer
86371 ** in the sqlite3.aVTrans array.
86372 */
86373 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
86374   int rc = SQLITE_OK;
86375   const sqlite3_module *pModule;
86376
86377   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
86378   ** than zero, then this function is being called from within a
86379   ** virtual module xSync() callback. It is illegal to write to 
86380   ** virtual module tables in this case, so return SQLITE_LOCKED.
86381   */
86382   if( sqlite3VtabInSync(db) ){
86383     return SQLITE_LOCKED;
86384   }
86385   if( !pVTab ){
86386     return SQLITE_OK;
86387   } 
86388   pModule = pVTab->pVtab->pModule;
86389
86390   if( pModule->xBegin ){
86391     int i;
86392
86393
86394     /* If pVtab is already in the aVTrans array, return early */
86395     for(i=0; i<db->nVTrans; i++){
86396       if( db->aVTrans[i]==pVTab ){
86397         return SQLITE_OK;
86398       }
86399     }
86400
86401     /* Invoke the xBegin method */
86402     rc = pModule->xBegin(pVTab->pVtab);
86403     if( rc==SQLITE_OK ){
86404       rc = addToVTrans(db, pVTab);
86405     }
86406   }
86407   return rc;
86408 }
86409
86410 /*
86411 ** The first parameter (pDef) is a function implementation.  The
86412 ** second parameter (pExpr) is the first argument to this function.
86413 ** If pExpr is a column in a virtual table, then let the virtual
86414 ** table implementation have an opportunity to overload the function.
86415 **
86416 ** This routine is used to allow virtual table implementations to
86417 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
86418 **
86419 ** Return either the pDef argument (indicating no change) or a 
86420 ** new FuncDef structure that is marked as ephemeral using the
86421 ** SQLITE_FUNC_EPHEM flag.
86422 */
86423 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
86424   sqlite3 *db,    /* Database connection for reporting malloc problems */
86425   FuncDef *pDef,  /* Function to possibly overload */
86426   int nArg,       /* Number of arguments to the function */
86427   Expr *pExpr     /* First argument to the function */
86428 ){
86429   Table *pTab;
86430   sqlite3_vtab *pVtab;
86431   sqlite3_module *pMod;
86432   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
86433   void *pArg = 0;
86434   FuncDef *pNew;
86435   int rc = 0;
86436   char *zLowerName;
86437   unsigned char *z;
86438
86439
86440   /* Check to see the left operand is a column in a virtual table */
86441   if( NEVER(pExpr==0) ) return pDef;
86442   if( pExpr->op!=TK_COLUMN ) return pDef;
86443   pTab = pExpr->pTab;
86444   if( NEVER(pTab==0) ) return pDef;
86445   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
86446   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
86447   assert( pVtab!=0 );
86448   assert( pVtab->pModule!=0 );
86449   pMod = (sqlite3_module *)pVtab->pModule;
86450   if( pMod->xFindFunction==0 ) return pDef;
86451  
86452   /* Call the xFindFunction method on the virtual table implementation
86453   ** to see if the implementation wants to overload this function 
86454   */
86455   zLowerName = sqlite3DbStrDup(db, pDef->zName);
86456   if( zLowerName ){
86457     for(z=(unsigned char*)zLowerName; *z; z++){
86458       *z = sqlite3UpperToLower[*z];
86459     }
86460     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
86461     sqlite3DbFree(db, zLowerName);
86462   }
86463   if( rc==0 ){
86464     return pDef;
86465   }
86466
86467   /* Create a new ephemeral function definition for the overloaded
86468   ** function */
86469   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
86470                              + sqlite3Strlen30(pDef->zName) + 1);
86471   if( pNew==0 ){
86472     return pDef;
86473   }
86474   *pNew = *pDef;
86475   pNew->zName = (char *)&pNew[1];
86476   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
86477   pNew->xFunc = xFunc;
86478   pNew->pUserData = pArg;
86479   pNew->flags |= SQLITE_FUNC_EPHEM;
86480   return pNew;
86481 }
86482
86483 /*
86484 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
86485 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
86486 ** array if it is missing.  If pTab is already in the array, this routine
86487 ** is a no-op.
86488 */
86489 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
86490   Parse *pToplevel = sqlite3ParseToplevel(pParse);
86491   int i, n;
86492   Table **apVtabLock;
86493
86494   assert( IsVirtual(pTab) );
86495   for(i=0; i<pToplevel->nVtabLock; i++){
86496     if( pTab==pToplevel->apVtabLock[i] ) return;
86497   }
86498   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
86499   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
86500   if( apVtabLock ){
86501     pToplevel->apVtabLock = apVtabLock;
86502     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
86503   }else{
86504     pToplevel->db->mallocFailed = 1;
86505   }
86506 }
86507
86508 #endif /* SQLITE_OMIT_VIRTUALTABLE */
86509
86510 /************** End of vtab.c ************************************************/
86511 /************** Begin file where.c *******************************************/
86512 /*
86513 ** 2001 September 15
86514 **
86515 ** The author disclaims copyright to this source code.  In place of
86516 ** a legal notice, here is a blessing:
86517 **
86518 **    May you do good and not evil.
86519 **    May you find forgiveness for yourself and forgive others.
86520 **    May you share freely, never taking more than you give.
86521 **
86522 *************************************************************************
86523 ** This module contains C code that generates VDBE code used to process
86524 ** the WHERE clause of SQL statements.  This module is responsible for
86525 ** generating the code that loops through a table looking for applicable
86526 ** rows.  Indices are selected and used to speed the search when doing
86527 ** so is applicable.  Because this module is responsible for selecting
86528 ** indices, you might also think of this module as the "query optimizer".
86529 */
86530
86531 /*
86532 ** Trace output macros
86533 */
86534 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
86535 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
86536 #endif
86537 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
86538 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
86539 #else
86540 # define WHERETRACE(X)
86541 #endif
86542
86543 /* Forward reference
86544 */
86545 typedef struct WhereClause WhereClause;
86546 typedef struct WhereMaskSet WhereMaskSet;
86547 typedef struct WhereOrInfo WhereOrInfo;
86548 typedef struct WhereAndInfo WhereAndInfo;
86549 typedef struct WhereCost WhereCost;
86550
86551 /*
86552 ** The query generator uses an array of instances of this structure to
86553 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
86554 ** clause subexpression is separated from the others by AND operators,
86555 ** usually, or sometimes subexpressions separated by OR.
86556 **
86557 ** All WhereTerms are collected into a single WhereClause structure.  
86558 ** The following identity holds:
86559 **
86560 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
86561 **
86562 ** When a term is of the form:
86563 **
86564 **              X <op> <expr>
86565 **
86566 ** where X is a column name and <op> is one of certain operators,
86567 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
86568 ** cursor number and column number for X.  WhereTerm.eOperator records
86569 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
86570 ** use of a bitmask encoding for the operator allows us to search
86571 ** quickly for terms that match any of several different operators.
86572 **
86573 ** A WhereTerm might also be two or more subterms connected by OR:
86574 **
86575 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
86576 **
86577 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
86578 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
86579 ** is collected about the
86580 **
86581 ** If a term in the WHERE clause does not match either of the two previous
86582 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
86583 ** to the original subexpression content and wtFlags is set up appropriately
86584 ** but no other fields in the WhereTerm object are meaningful.
86585 **
86586 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
86587 ** but they do so indirectly.  A single WhereMaskSet structure translates
86588 ** cursor number into bits and the translated bit is stored in the prereq
86589 ** fields.  The translation is used in order to maximize the number of
86590 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
86591 ** spread out over the non-negative integers.  For example, the cursor
86592 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
86593 ** translates these sparse cursor numbers into consecutive integers
86594 ** beginning with 0 in order to make the best possible use of the available
86595 ** bits in the Bitmask.  So, in the example above, the cursor numbers
86596 ** would be mapped into integers 0 through 7.
86597 **
86598 ** The number of terms in a join is limited by the number of bits
86599 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
86600 ** is only able to process joins with 64 or fewer tables.
86601 */
86602 typedef struct WhereTerm WhereTerm;
86603 struct WhereTerm {
86604   Expr *pExpr;            /* Pointer to the subexpression that is this term */
86605   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
86606   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
86607   union {
86608     int leftColumn;         /* Column number of X in "X <op> <expr>" */
86609     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
86610     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
86611   } u;
86612   u16 eOperator;          /* A WO_xx value describing <op> */
86613   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
86614   u8 nChild;              /* Number of children that must disable us */
86615   WhereClause *pWC;       /* The clause this term is part of */
86616   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
86617   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
86618 };
86619
86620 /*
86621 ** Allowed values of WhereTerm.wtFlags
86622 */
86623 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
86624 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
86625 #define TERM_CODED      0x04   /* This term is already coded */
86626 #define TERM_COPIED     0x08   /* Has a child */
86627 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
86628 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
86629 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
86630
86631 /*
86632 ** An instance of the following structure holds all information about a
86633 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
86634 */
86635 struct WhereClause {
86636   Parse *pParse;           /* The parser context */
86637   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
86638   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
86639   u8 op;                   /* Split operator.  TK_AND or TK_OR */
86640   int nTerm;               /* Number of terms */
86641   int nSlot;               /* Number of entries in a[] */
86642   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
86643 #if defined(SQLITE_SMALL_STACK)
86644   WhereTerm aStatic[1];    /* Initial static space for a[] */
86645 #else
86646   WhereTerm aStatic[8];    /* Initial static space for a[] */
86647 #endif
86648 };
86649
86650 /*
86651 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
86652 ** a dynamically allocated instance of the following structure.
86653 */
86654 struct WhereOrInfo {
86655   WhereClause wc;          /* Decomposition into subterms */
86656   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
86657 };
86658
86659 /*
86660 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
86661 ** a dynamically allocated instance of the following structure.
86662 */
86663 struct WhereAndInfo {
86664   WhereClause wc;          /* The subexpression broken out */
86665 };
86666
86667 /*
86668 ** An instance of the following structure keeps track of a mapping
86669 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
86670 **
86671 ** The VDBE cursor numbers are small integers contained in 
86672 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
86673 ** clause, the cursor numbers might not begin with 0 and they might
86674 ** contain gaps in the numbering sequence.  But we want to make maximum
86675 ** use of the bits in our bitmasks.  This structure provides a mapping
86676 ** from the sparse cursor numbers into consecutive integers beginning
86677 ** with 0.
86678 **
86679 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
86680 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
86681 **
86682 ** For example, if the WHERE clause expression used these VDBE
86683 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
86684 ** would map those cursor numbers into bits 0 through 5.
86685 **
86686 ** Note that the mapping is not necessarily ordered.  In the example
86687 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
86688 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
86689 ** does not really matter.  What is important is that sparse cursor
86690 ** numbers all get mapped into bit numbers that begin with 0 and contain
86691 ** no gaps.
86692 */
86693 struct WhereMaskSet {
86694   int n;                        /* Number of assigned cursor values */
86695   int ix[BMS];                  /* Cursor assigned to each bit */
86696 };
86697
86698 /*
86699 ** A WhereCost object records a lookup strategy and the estimated
86700 ** cost of pursuing that strategy.
86701 */
86702 struct WhereCost {
86703   WherePlan plan;    /* The lookup strategy */
86704   double rCost;      /* Overall cost of pursuing this search strategy */
86705   double nRow;       /* Estimated number of output rows */
86706   Bitmask used;      /* Bitmask of cursors used by this plan */
86707 };
86708
86709 /*
86710 ** Bitmasks for the operators that indices are able to exploit.  An
86711 ** OR-ed combination of these values can be used when searching for
86712 ** terms in the where clause.
86713 */
86714 #define WO_IN     0x001
86715 #define WO_EQ     0x002
86716 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
86717 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
86718 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
86719 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
86720 #define WO_MATCH  0x040
86721 #define WO_ISNULL 0x080
86722 #define WO_OR     0x100       /* Two or more OR-connected terms */
86723 #define WO_AND    0x200       /* Two or more AND-connected terms */
86724
86725 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
86726 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
86727
86728 /*
86729 ** Value for wsFlags returned by bestIndex() and stored in
86730 ** WhereLevel.wsFlags.  These flags determine which search
86731 ** strategies are appropriate.
86732 **
86733 ** The least significant 12 bits is reserved as a mask for WO_ values above.
86734 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
86735 ** But if the table is the right table of a left join, WhereLevel.wsFlags
86736 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
86737 ** the "op" parameter to findTerm when we are resolving equality constraints.
86738 ** ISNULL constraints will then not be used on the right table of a left
86739 ** join.  Tickets #2177 and #2189.
86740 */
86741 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
86742 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
86743 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
86744 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
86745 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
86746 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
86747 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
86748 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
86749 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
86750 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
86751 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
86752 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
86753 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
86754 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
86755 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
86756 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
86757
86758 /*
86759 ** Initialize a preallocated WhereClause structure.
86760 */
86761 static void whereClauseInit(
86762   WhereClause *pWC,        /* The WhereClause to be initialized */
86763   Parse *pParse,           /* The parsing context */
86764   WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
86765 ){
86766   pWC->pParse = pParse;
86767   pWC->pMaskSet = pMaskSet;
86768   pWC->nTerm = 0;
86769   pWC->nSlot = ArraySize(pWC->aStatic);
86770   pWC->a = pWC->aStatic;
86771   pWC->vmask = 0;
86772 }
86773
86774 /* Forward reference */
86775 static void whereClauseClear(WhereClause*);
86776
86777 /*
86778 ** Deallocate all memory associated with a WhereOrInfo object.
86779 */
86780 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
86781   whereClauseClear(&p->wc);
86782   sqlite3DbFree(db, p);
86783 }
86784
86785 /*
86786 ** Deallocate all memory associated with a WhereAndInfo object.
86787 */
86788 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
86789   whereClauseClear(&p->wc);
86790   sqlite3DbFree(db, p);
86791 }
86792
86793 /*
86794 ** Deallocate a WhereClause structure.  The WhereClause structure
86795 ** itself is not freed.  This routine is the inverse of whereClauseInit().
86796 */
86797 static void whereClauseClear(WhereClause *pWC){
86798   int i;
86799   WhereTerm *a;
86800   sqlite3 *db = pWC->pParse->db;
86801   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
86802     if( a->wtFlags & TERM_DYNAMIC ){
86803       sqlite3ExprDelete(db, a->pExpr);
86804     }
86805     if( a->wtFlags & TERM_ORINFO ){
86806       whereOrInfoDelete(db, a->u.pOrInfo);
86807     }else if( a->wtFlags & TERM_ANDINFO ){
86808       whereAndInfoDelete(db, a->u.pAndInfo);
86809     }
86810   }
86811   if( pWC->a!=pWC->aStatic ){
86812     sqlite3DbFree(db, pWC->a);
86813   }
86814 }
86815
86816 /*
86817 ** Add a single new WhereTerm entry to the WhereClause object pWC.
86818 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
86819 ** The index in pWC->a[] of the new WhereTerm is returned on success.
86820 ** 0 is returned if the new WhereTerm could not be added due to a memory
86821 ** allocation error.  The memory allocation failure will be recorded in
86822 ** the db->mallocFailed flag so that higher-level functions can detect it.
86823 **
86824 ** This routine will increase the size of the pWC->a[] array as necessary.
86825 **
86826 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
86827 ** for freeing the expression p is assumed by the WhereClause object pWC.
86828 ** This is true even if this routine fails to allocate a new WhereTerm.
86829 **
86830 ** WARNING:  This routine might reallocate the space used to store
86831 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
86832 ** calling this routine.  Such pointers may be reinitialized by referencing
86833 ** the pWC->a[] array.
86834 */
86835 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
86836   WhereTerm *pTerm;
86837   int idx;
86838   if( pWC->nTerm>=pWC->nSlot ){
86839     WhereTerm *pOld = pWC->a;
86840     sqlite3 *db = pWC->pParse->db;
86841     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
86842     if( pWC->a==0 ){
86843       if( wtFlags & TERM_DYNAMIC ){
86844         sqlite3ExprDelete(db, p);
86845       }
86846       pWC->a = pOld;
86847       return 0;
86848     }
86849     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
86850     if( pOld!=pWC->aStatic ){
86851       sqlite3DbFree(db, pOld);
86852     }
86853     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
86854   }
86855   pTerm = &pWC->a[idx = pWC->nTerm++];
86856   pTerm->pExpr = p;
86857   pTerm->wtFlags = wtFlags;
86858   pTerm->pWC = pWC;
86859   pTerm->iParent = -1;
86860   return idx;
86861 }
86862
86863 /*
86864 ** This routine identifies subexpressions in the WHERE clause where
86865 ** each subexpression is separated by the AND operator or some other
86866 ** operator specified in the op parameter.  The WhereClause structure
86867 ** is filled with pointers to subexpressions.  For example:
86868 **
86869 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
86870 **           \________/     \_______________/     \________________/
86871 **            slot[0]            slot[1]               slot[2]
86872 **
86873 ** The original WHERE clause in pExpr is unaltered.  All this routine
86874 ** does is make slot[] entries point to substructure within pExpr.
86875 **
86876 ** In the previous sentence and in the diagram, "slot[]" refers to
86877 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
86878 ** all terms of the WHERE clause.
86879 */
86880 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
86881   pWC->op = (u8)op;
86882   if( pExpr==0 ) return;
86883   if( pExpr->op!=op ){
86884     whereClauseInsert(pWC, pExpr, 0);
86885   }else{
86886     whereSplit(pWC, pExpr->pLeft, op);
86887     whereSplit(pWC, pExpr->pRight, op);
86888   }
86889 }
86890
86891 /*
86892 ** Initialize an expression mask set (a WhereMaskSet object)
86893 */
86894 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
86895
86896 /*
86897 ** Return the bitmask for the given cursor number.  Return 0 if
86898 ** iCursor is not in the set.
86899 */
86900 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
86901   int i;
86902   assert( pMaskSet->n<=sizeof(Bitmask)*8 );
86903   for(i=0; i<pMaskSet->n; i++){
86904     if( pMaskSet->ix[i]==iCursor ){
86905       return ((Bitmask)1)<<i;
86906     }
86907   }
86908   return 0;
86909 }
86910
86911 /*
86912 ** Create a new mask for cursor iCursor.
86913 **
86914 ** There is one cursor per table in the FROM clause.  The number of
86915 ** tables in the FROM clause is limited by a test early in the
86916 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
86917 ** array will never overflow.
86918 */
86919 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
86920   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
86921   pMaskSet->ix[pMaskSet->n++] = iCursor;
86922 }
86923
86924 /*
86925 ** This routine walks (recursively) an expression tree and generates
86926 ** a bitmask indicating which tables are used in that expression
86927 ** tree.
86928 **
86929 ** In order for this routine to work, the calling function must have
86930 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
86931 ** the header comment on that routine for additional information.
86932 ** The sqlite3ResolveExprNames() routines looks for column names and
86933 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
86934 ** the VDBE cursor number of the table.  This routine just has to
86935 ** translate the cursor numbers into bitmask values and OR all
86936 ** the bitmasks together.
86937 */
86938 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
86939 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
86940 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
86941   Bitmask mask = 0;
86942   if( p==0 ) return 0;
86943   if( p->op==TK_COLUMN ){
86944     mask = getMask(pMaskSet, p->iTable);
86945     return mask;
86946   }
86947   mask = exprTableUsage(pMaskSet, p->pRight);
86948   mask |= exprTableUsage(pMaskSet, p->pLeft);
86949   if( ExprHasProperty(p, EP_xIsSelect) ){
86950     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
86951   }else{
86952     mask |= exprListTableUsage(pMaskSet, p->x.pList);
86953   }
86954   return mask;
86955 }
86956 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
86957   int i;
86958   Bitmask mask = 0;
86959   if( pList ){
86960     for(i=0; i<pList->nExpr; i++){
86961       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
86962     }
86963   }
86964   return mask;
86965 }
86966 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
86967   Bitmask mask = 0;
86968   while( pS ){
86969     mask |= exprListTableUsage(pMaskSet, pS->pEList);
86970     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
86971     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
86972     mask |= exprTableUsage(pMaskSet, pS->pWhere);
86973     mask |= exprTableUsage(pMaskSet, pS->pHaving);
86974     pS = pS->pPrior;
86975   }
86976   return mask;
86977 }
86978
86979 /*
86980 ** Return TRUE if the given operator is one of the operators that is
86981 ** allowed for an indexable WHERE clause term.  The allowed operators are
86982 ** "=", "<", ">", "<=", ">=", and "IN".
86983 */
86984 static int allowedOp(int op){
86985   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
86986   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
86987   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
86988   assert( TK_GE==TK_EQ+4 );
86989   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
86990 }
86991
86992 /*
86993 ** Swap two objects of type TYPE.
86994 */
86995 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
86996
86997 /*
86998 ** Commute a comparison operator.  Expressions of the form "X op Y"
86999 ** are converted into "Y op X".
87000 **
87001 ** If a collation sequence is associated with either the left or right
87002 ** side of the comparison, it remains associated with the same side after
87003 ** the commutation. So "Y collate NOCASE op X" becomes 
87004 ** "X collate NOCASE op Y". This is because any collation sequence on
87005 ** the left hand side of a comparison overrides any collation sequence 
87006 ** attached to the right. For the same reason the EP_ExpCollate flag
87007 ** is not commuted.
87008 */
87009 static void exprCommute(Parse *pParse, Expr *pExpr){
87010   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
87011   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
87012   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
87013   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
87014   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
87015   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
87016   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
87017   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
87018   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
87019   if( pExpr->op>=TK_GT ){
87020     assert( TK_LT==TK_GT+2 );
87021     assert( TK_GE==TK_LE+2 );
87022     assert( TK_GT>TK_EQ );
87023     assert( TK_GT<TK_LE );
87024     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
87025     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
87026   }
87027 }
87028
87029 /*
87030 ** Translate from TK_xx operator to WO_xx bitmask.
87031 */
87032 static u16 operatorMask(int op){
87033   u16 c;
87034   assert( allowedOp(op) );
87035   if( op==TK_IN ){
87036     c = WO_IN;
87037   }else if( op==TK_ISNULL ){
87038     c = WO_ISNULL;
87039   }else{
87040     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
87041     c = (u16)(WO_EQ<<(op-TK_EQ));
87042   }
87043   assert( op!=TK_ISNULL || c==WO_ISNULL );
87044   assert( op!=TK_IN || c==WO_IN );
87045   assert( op!=TK_EQ || c==WO_EQ );
87046   assert( op!=TK_LT || c==WO_LT );
87047   assert( op!=TK_LE || c==WO_LE );
87048   assert( op!=TK_GT || c==WO_GT );
87049   assert( op!=TK_GE || c==WO_GE );
87050   return c;
87051 }
87052
87053 /*
87054 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
87055 ** where X is a reference to the iColumn of table iCur and <op> is one of
87056 ** the WO_xx operator codes specified by the op parameter.
87057 ** Return a pointer to the term.  Return 0 if not found.
87058 */
87059 static WhereTerm *findTerm(
87060   WhereClause *pWC,     /* The WHERE clause to be searched */
87061   int iCur,             /* Cursor number of LHS */
87062   int iColumn,          /* Column number of LHS */
87063   Bitmask notReady,     /* RHS must not overlap with this mask */
87064   u32 op,               /* Mask of WO_xx values describing operator */
87065   Index *pIdx           /* Must be compatible with this index, if not NULL */
87066 ){
87067   WhereTerm *pTerm;
87068   int k;
87069   assert( iCur>=0 );
87070   op &= WO_ALL;
87071   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
87072     if( pTerm->leftCursor==iCur
87073        && (pTerm->prereqRight & notReady)==0
87074        && pTerm->u.leftColumn==iColumn
87075        && (pTerm->eOperator & op)!=0
87076     ){
87077       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
87078         Expr *pX = pTerm->pExpr;
87079         CollSeq *pColl;
87080         char idxaff;
87081         int j;
87082         Parse *pParse = pWC->pParse;
87083
87084         idxaff = pIdx->pTable->aCol[iColumn].affinity;
87085         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
87086
87087         /* Figure out the collation sequence required from an index for
87088         ** it to be useful for optimising expression pX. Store this
87089         ** value in variable pColl.
87090         */
87091         assert(pX->pLeft);
87092         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
87093         assert(pColl || pParse->nErr);
87094
87095         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
87096           if( NEVER(j>=pIdx->nColumn) ) return 0;
87097         }
87098         if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
87099       }
87100       return pTerm;
87101     }
87102   }
87103   return 0;
87104 }
87105
87106 /* Forward reference */
87107 static void exprAnalyze(SrcList*, WhereClause*, int);
87108
87109 /*
87110 ** Call exprAnalyze on all terms in a WHERE clause.  
87111 **
87112 **
87113 */
87114 static void exprAnalyzeAll(
87115   SrcList *pTabList,       /* the FROM clause */
87116   WhereClause *pWC         /* the WHERE clause to be analyzed */
87117 ){
87118   int i;
87119   for(i=pWC->nTerm-1; i>=0; i--){
87120     exprAnalyze(pTabList, pWC, i);
87121   }
87122 }
87123
87124 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
87125 /*
87126 ** Check to see if the given expression is a LIKE or GLOB operator that
87127 ** can be optimized using inequality constraints.  Return TRUE if it is
87128 ** so and false if not.
87129 **
87130 ** In order for the operator to be optimizible, the RHS must be a string
87131 ** literal that does not begin with a wildcard.  
87132 */
87133 static int isLikeOrGlob(
87134   Parse *pParse,    /* Parsing and code generating context */
87135   Expr *pExpr,      /* Test this expression */
87136   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
87137   int *pisComplete, /* True if the only wildcard is % in the last character */
87138   int *pnoCase      /* True if uppercase is equivalent to lowercase */
87139 ){
87140   const char *z = 0;         /* String on RHS of LIKE operator */
87141   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
87142   ExprList *pList;           /* List of operands to the LIKE operator */
87143   int c;                     /* One character in z[] */
87144   int cnt;                   /* Number of non-wildcard prefix characters */
87145   char wc[3];                /* Wildcard characters */
87146   CollSeq *pColl;            /* Collating sequence for LHS */
87147   sqlite3 *db = pParse->db;  /* Database connection */
87148   sqlite3_value *pVal = 0;
87149   int op;                    /* Opcode of pRight */
87150
87151   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
87152     return 0;
87153   }
87154 #ifdef SQLITE_EBCDIC
87155   if( *pnoCase ) return 0;
87156 #endif
87157   pList = pExpr->x.pList;
87158   pLeft = pList->a[1].pExpr;
87159   if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
87160     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
87161     ** be the name of an indexed column with TEXT affinity. */
87162     return 0;
87163   }
87164   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
87165   pColl = sqlite3ExprCollSeq(pParse, pLeft);
87166   assert( pColl!=0 );  /* Every non-IPK column has a collating sequence */
87167   if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
87168       (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
87169     /* IMP: R-09003-32046 For the GLOB operator, the column must use the
87170     ** default BINARY collating sequence.
87171     ** IMP: R-41408-28306 For the LIKE operator, if case_sensitive_like mode
87172     ** is enabled then the column must use the default BINARY collating
87173     ** sequence, or if case_sensitive_like mode is disabled then the column
87174     ** must use the built-in NOCASE collating sequence.
87175     */
87176     return 0;
87177   }
87178
87179   pRight = pList->a[0].pExpr;
87180   op = pRight->op;
87181   if( op==TK_REGISTER ){
87182     op = pRight->op2;
87183   }
87184   if( op==TK_VARIABLE ){
87185     Vdbe *pReprepare = pParse->pReprepare;
87186     pVal = sqlite3VdbeGetValue(pReprepare, pRight->iColumn, SQLITE_AFF_NONE);
87187     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
87188       z = (char *)sqlite3_value_text(pVal);
87189     }
87190     sqlite3VdbeSetVarmask(pParse->pVdbe, pRight->iColumn);
87191     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
87192   }else if( op==TK_STRING ){
87193     z = pRight->u.zToken;
87194   }
87195   if( z ){
87196     cnt = 0;
87197     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
87198       cnt++;
87199     }
87200     if( cnt!=0 && c!=0 && 255!=(u8)z[cnt-1] ){
87201       Expr *pPrefix;
87202       *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
87203       pPrefix = sqlite3Expr(db, TK_STRING, z);
87204       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
87205       *ppPrefix = pPrefix;
87206       if( op==TK_VARIABLE ){
87207         Vdbe *v = pParse->pVdbe;
87208         sqlite3VdbeSetVarmask(v, pRight->iColumn);
87209         if( *pisComplete && pRight->u.zToken[1] ){
87210           /* If the rhs of the LIKE expression is a variable, and the current
87211           ** value of the variable means there is no need to invoke the LIKE
87212           ** function, then no OP_Variable will be added to the program.
87213           ** This causes problems for the sqlite3_bind_parameter_name()
87214           ** API. To workaround them, add a dummy OP_Variable here.
87215           */ 
87216           int r1 = sqlite3GetTempReg(pParse);
87217           sqlite3ExprCodeTarget(pParse, pRight, r1);
87218           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
87219           sqlite3ReleaseTempReg(pParse, r1);
87220         }
87221       }
87222     }else{
87223       z = 0;
87224     }
87225   }
87226
87227   sqlite3ValueFree(pVal);
87228   return (z!=0);
87229 }
87230 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
87231
87232
87233 #ifndef SQLITE_OMIT_VIRTUALTABLE
87234 /*
87235 ** Check to see if the given expression is of the form
87236 **
87237 **         column MATCH expr
87238 **
87239 ** If it is then return TRUE.  If not, return FALSE.
87240 */
87241 static int isMatchOfColumn(
87242   Expr *pExpr      /* Test this expression */
87243 ){
87244   ExprList *pList;
87245
87246   if( pExpr->op!=TK_FUNCTION ){
87247     return 0;
87248   }
87249   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
87250     return 0;
87251   }
87252   pList = pExpr->x.pList;
87253   if( pList->nExpr!=2 ){
87254     return 0;
87255   }
87256   if( pList->a[1].pExpr->op != TK_COLUMN ){
87257     return 0;
87258   }
87259   return 1;
87260 }
87261 #endif /* SQLITE_OMIT_VIRTUALTABLE */
87262
87263 /*
87264 ** If the pBase expression originated in the ON or USING clause of
87265 ** a join, then transfer the appropriate markings over to derived.
87266 */
87267 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
87268   pDerived->flags |= pBase->flags & EP_FromJoin;
87269   pDerived->iRightJoinTable = pBase->iRightJoinTable;
87270 }
87271
87272 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
87273 /*
87274 ** Analyze a term that consists of two or more OR-connected
87275 ** subterms.  So in:
87276 **
87277 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
87278 **                          ^^^^^^^^^^^^^^^^^^^^
87279 **
87280 ** This routine analyzes terms such as the middle term in the above example.
87281 ** A WhereOrTerm object is computed and attached to the term under
87282 ** analysis, regardless of the outcome of the analysis.  Hence:
87283 **
87284 **     WhereTerm.wtFlags   |=  TERM_ORINFO
87285 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
87286 **
87287 ** The term being analyzed must have two or more of OR-connected subterms.
87288 ** A single subterm might be a set of AND-connected sub-subterms.
87289 ** Examples of terms under analysis:
87290 **
87291 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
87292 **     (B)     x=expr1 OR expr2=x OR x=expr3
87293 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
87294 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
87295 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
87296 **
87297 ** CASE 1:
87298 **
87299 ** If all subterms are of the form T.C=expr for some single column of C
87300 ** a single table T (as shown in example B above) then create a new virtual
87301 ** term that is an equivalent IN expression.  In other words, if the term
87302 ** being analyzed is:
87303 **
87304 **      x = expr1  OR  expr2 = x  OR  x = expr3
87305 **
87306 ** then create a new virtual term like this:
87307 **
87308 **      x IN (expr1,expr2,expr3)
87309 **
87310 ** CASE 2:
87311 **
87312 ** If all subterms are indexable by a single table T, then set
87313 **
87314 **     WhereTerm.eOperator              =  WO_OR
87315 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
87316 **
87317 ** A subterm is "indexable" if it is of the form
87318 ** "T.C <op> <expr>" where C is any column of table T and 
87319 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
87320 ** A subterm is also indexable if it is an AND of two or more
87321 ** subsubterms at least one of which is indexable.  Indexable AND 
87322 ** subterms have their eOperator set to WO_AND and they have
87323 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
87324 **
87325 ** From another point of view, "indexable" means that the subterm could
87326 ** potentially be used with an index if an appropriate index exists.
87327 ** This analysis does not consider whether or not the index exists; that
87328 ** is something the bestIndex() routine will determine.  This analysis
87329 ** only looks at whether subterms appropriate for indexing exist.
87330 **
87331 ** All examples A through E above all satisfy case 2.  But if a term
87332 ** also statisfies case 1 (such as B) we know that the optimizer will
87333 ** always prefer case 1, so in that case we pretend that case 2 is not
87334 ** satisfied.
87335 **
87336 ** It might be the case that multiple tables are indexable.  For example,
87337 ** (E) above is indexable on tables P, Q, and R.
87338 **
87339 ** Terms that satisfy case 2 are candidates for lookup by using
87340 ** separate indices to find rowids for each subterm and composing
87341 ** the union of all rowids using a RowSet object.  This is similar
87342 ** to "bitmap indices" in other database engines.
87343 **
87344 ** OTHERWISE:
87345 **
87346 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
87347 ** zero.  This term is not useful for search.
87348 */
87349 static void exprAnalyzeOrTerm(
87350   SrcList *pSrc,            /* the FROM clause */
87351   WhereClause *pWC,         /* the complete WHERE clause */
87352   int idxTerm               /* Index of the OR-term to be analyzed */
87353 ){
87354   Parse *pParse = pWC->pParse;            /* Parser context */
87355   sqlite3 *db = pParse->db;               /* Database connection */
87356   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
87357   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
87358   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
87359   int i;                                  /* Loop counters */
87360   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
87361   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
87362   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
87363   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
87364   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
87365
87366   /*
87367   ** Break the OR clause into its separate subterms.  The subterms are
87368   ** stored in a WhereClause structure containing within the WhereOrInfo
87369   ** object that is attached to the original OR clause term.
87370   */
87371   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
87372   assert( pExpr->op==TK_OR );
87373   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
87374   if( pOrInfo==0 ) return;
87375   pTerm->wtFlags |= TERM_ORINFO;
87376   pOrWc = &pOrInfo->wc;
87377   whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
87378   whereSplit(pOrWc, pExpr, TK_OR);
87379   exprAnalyzeAll(pSrc, pOrWc);
87380   if( db->mallocFailed ) return;
87381   assert( pOrWc->nTerm>=2 );
87382
87383   /*
87384   ** Compute the set of tables that might satisfy cases 1 or 2.
87385   */
87386   indexable = ~(Bitmask)0;
87387   chngToIN = ~(pWC->vmask);
87388   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
87389     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
87390       WhereAndInfo *pAndInfo;
87391       assert( pOrTerm->eOperator==0 );
87392       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
87393       chngToIN = 0;
87394       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
87395       if( pAndInfo ){
87396         WhereClause *pAndWC;
87397         WhereTerm *pAndTerm;
87398         int j;
87399         Bitmask b = 0;
87400         pOrTerm->u.pAndInfo = pAndInfo;
87401         pOrTerm->wtFlags |= TERM_ANDINFO;
87402         pOrTerm->eOperator = WO_AND;
87403         pAndWC = &pAndInfo->wc;
87404         whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
87405         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
87406         exprAnalyzeAll(pSrc, pAndWC);
87407         testcase( db->mallocFailed );
87408         if( !db->mallocFailed ){
87409           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
87410             assert( pAndTerm->pExpr );
87411             if( allowedOp(pAndTerm->pExpr->op) ){
87412               b |= getMask(pMaskSet, pAndTerm->leftCursor);
87413             }
87414           }
87415         }
87416         indexable &= b;
87417       }
87418     }else if( pOrTerm->wtFlags & TERM_COPIED ){
87419       /* Skip this term for now.  We revisit it when we process the
87420       ** corresponding TERM_VIRTUAL term */
87421     }else{
87422       Bitmask b;
87423       b = getMask(pMaskSet, pOrTerm->leftCursor);
87424       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
87425         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
87426         b |= getMask(pMaskSet, pOther->leftCursor);
87427       }
87428       indexable &= b;
87429       if( pOrTerm->eOperator!=WO_EQ ){
87430         chngToIN = 0;
87431       }else{
87432         chngToIN &= b;
87433       }
87434     }
87435   }
87436
87437   /*
87438   ** Record the set of tables that satisfy case 2.  The set might be
87439   ** empty.
87440   */
87441   pOrInfo->indexable = indexable;
87442   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
87443
87444   /*
87445   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
87446   ** we have to do some additional checking to see if case 1 really
87447   ** is satisfied.
87448   **
87449   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
87450   ** that there is no possibility of transforming the OR clause into an
87451   ** IN operator because one or more terms in the OR clause contain
87452   ** something other than == on a column in the single table.  The 1-bit
87453   ** case means that every term of the OR clause is of the form
87454   ** "table.column=expr" for some single table.  The one bit that is set
87455   ** will correspond to the common table.  We still need to check to make
87456   ** sure the same column is used on all terms.  The 2-bit case is when
87457   ** the all terms are of the form "table1.column=table2.column".  It
87458   ** might be possible to form an IN operator with either table1.column
87459   ** or table2.column as the LHS if either is common to every term of
87460   ** the OR clause.
87461   **
87462   ** Note that terms of the form "table.column1=table.column2" (the
87463   ** same table on both sizes of the ==) cannot be optimized.
87464   */
87465   if( chngToIN ){
87466     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
87467     int iColumn = -1;         /* Column index on lhs of IN operator */
87468     int iCursor = -1;         /* Table cursor common to all terms */
87469     int j = 0;                /* Loop counter */
87470
87471     /* Search for a table and column that appears on one side or the
87472     ** other of the == operator in every subterm.  That table and column
87473     ** will be recorded in iCursor and iColumn.  There might not be any
87474     ** such table and column.  Set okToChngToIN if an appropriate table
87475     ** and column is found but leave okToChngToIN false if not found.
87476     */
87477     for(j=0; j<2 && !okToChngToIN; j++){
87478       pOrTerm = pOrWc->a;
87479       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
87480         assert( pOrTerm->eOperator==WO_EQ );
87481         pOrTerm->wtFlags &= ~TERM_OR_OK;
87482         if( pOrTerm->leftCursor==iCursor ){
87483           /* This is the 2-bit case and we are on the second iteration and
87484           ** current term is from the first iteration.  So skip this term. */
87485           assert( j==1 );
87486           continue;
87487         }
87488         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
87489           /* This term must be of the form t1.a==t2.b where t2 is in the
87490           ** chngToIN set but t1 is not.  This term will be either preceeded
87491           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
87492           ** and use its inversion. */
87493           testcase( pOrTerm->wtFlags & TERM_COPIED );
87494           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
87495           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
87496           continue;
87497         }
87498         iColumn = pOrTerm->u.leftColumn;
87499         iCursor = pOrTerm->leftCursor;
87500         break;
87501       }
87502       if( i<0 ){
87503         /* No candidate table+column was found.  This can only occur
87504         ** on the second iteration */
87505         assert( j==1 );
87506         assert( (chngToIN&(chngToIN-1))==0 );
87507         assert( chngToIN==getMask(pMaskSet, iCursor) );
87508         break;
87509       }
87510       testcase( j==1 );
87511
87512       /* We have found a candidate table and column.  Check to see if that
87513       ** table and column is common to every term in the OR clause */
87514       okToChngToIN = 1;
87515       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
87516         assert( pOrTerm->eOperator==WO_EQ );
87517         if( pOrTerm->leftCursor!=iCursor ){
87518           pOrTerm->wtFlags &= ~TERM_OR_OK;
87519         }else if( pOrTerm->u.leftColumn!=iColumn ){
87520           okToChngToIN = 0;
87521         }else{
87522           int affLeft, affRight;
87523           /* If the right-hand side is also a column, then the affinities
87524           ** of both right and left sides must be such that no type
87525           ** conversions are required on the right.  (Ticket #2249)
87526           */
87527           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
87528           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
87529           if( affRight!=0 && affRight!=affLeft ){
87530             okToChngToIN = 0;
87531           }else{
87532             pOrTerm->wtFlags |= TERM_OR_OK;
87533           }
87534         }
87535       }
87536     }
87537
87538     /* At this point, okToChngToIN is true if original pTerm satisfies
87539     ** case 1.  In that case, construct a new virtual term that is 
87540     ** pTerm converted into an IN operator.
87541     */
87542     if( okToChngToIN ){
87543       Expr *pDup;            /* A transient duplicate expression */
87544       ExprList *pList = 0;   /* The RHS of the IN operator */
87545       Expr *pLeft = 0;       /* The LHS of the IN operator */
87546       Expr *pNew;            /* The complete IN operator */
87547
87548       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
87549         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
87550         assert( pOrTerm->eOperator==WO_EQ );
87551         assert( pOrTerm->leftCursor==iCursor );
87552         assert( pOrTerm->u.leftColumn==iColumn );
87553         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
87554         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
87555         pLeft = pOrTerm->pExpr->pLeft;
87556       }
87557       assert( pLeft!=0 );
87558       pDup = sqlite3ExprDup(db, pLeft, 0);
87559       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
87560       if( pNew ){
87561         int idxNew;
87562         transferJoinMarkings(pNew, pExpr);
87563         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
87564         pNew->x.pList = pList;
87565         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
87566         testcase( idxNew==0 );
87567         exprAnalyze(pSrc, pWC, idxNew);
87568         pTerm = &pWC->a[idxTerm];
87569         pWC->a[idxNew].iParent = idxTerm;
87570         pTerm->nChild = 1;
87571       }else{
87572         sqlite3ExprListDelete(db, pList);
87573       }
87574       pTerm->eOperator = 0;  /* case 1 trumps case 2 */
87575     }
87576   }
87577 }
87578 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
87579
87580
87581 /*
87582 ** The input to this routine is an WhereTerm structure with only the
87583 ** "pExpr" field filled in.  The job of this routine is to analyze the
87584 ** subexpression and populate all the other fields of the WhereTerm
87585 ** structure.
87586 **
87587 ** If the expression is of the form "<expr> <op> X" it gets commuted
87588 ** to the standard form of "X <op> <expr>".
87589 **
87590 ** If the expression is of the form "X <op> Y" where both X and Y are
87591 ** columns, then the original expression is unchanged and a new virtual
87592 ** term of the form "Y <op> X" is added to the WHERE clause and
87593 ** analyzed separately.  The original term is marked with TERM_COPIED
87594 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
87595 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
87596 ** is a commuted copy of a prior term.)  The original term has nChild=1
87597 ** and the copy has idxParent set to the index of the original term.
87598 */
87599 static void exprAnalyze(
87600   SrcList *pSrc,            /* the FROM clause */
87601   WhereClause *pWC,         /* the WHERE clause */
87602   int idxTerm               /* Index of the term to be analyzed */
87603 ){
87604   WhereTerm *pTerm;                /* The term to be analyzed */
87605   WhereMaskSet *pMaskSet;          /* Set of table index masks */
87606   Expr *pExpr;                     /* The expression to be analyzed */
87607   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
87608   Bitmask prereqAll;               /* Prerequesites of pExpr */
87609   Bitmask extraRight = 0;          /* */
87610   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
87611   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
87612   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
87613   int op;                          /* Top-level operator.  pExpr->op */
87614   Parse *pParse = pWC->pParse;     /* Parsing context */
87615   sqlite3 *db = pParse->db;        /* Database connection */
87616
87617   if( db->mallocFailed ){
87618     return;
87619   }
87620   pTerm = &pWC->a[idxTerm];
87621   pMaskSet = pWC->pMaskSet;
87622   pExpr = pTerm->pExpr;
87623   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
87624   op = pExpr->op;
87625   if( op==TK_IN ){
87626     assert( pExpr->pRight==0 );
87627     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
87628       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
87629     }else{
87630       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
87631     }
87632   }else if( op==TK_ISNULL ){
87633     pTerm->prereqRight = 0;
87634   }else{
87635     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
87636   }
87637   prereqAll = exprTableUsage(pMaskSet, pExpr);
87638   if( ExprHasProperty(pExpr, EP_FromJoin) ){
87639     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
87640     prereqAll |= x;
87641     extraRight = x-1;  /* ON clause terms may not be used with an index
87642                        ** on left table of a LEFT JOIN.  Ticket #3015 */
87643   }
87644   pTerm->prereqAll = prereqAll;
87645   pTerm->leftCursor = -1;
87646   pTerm->iParent = -1;
87647   pTerm->eOperator = 0;
87648   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
87649     Expr *pLeft = pExpr->pLeft;
87650     Expr *pRight = pExpr->pRight;
87651     if( pLeft->op==TK_COLUMN ){
87652       pTerm->leftCursor = pLeft->iTable;
87653       pTerm->u.leftColumn = pLeft->iColumn;
87654       pTerm->eOperator = operatorMask(op);
87655     }
87656     if( pRight && pRight->op==TK_COLUMN ){
87657       WhereTerm *pNew;
87658       Expr *pDup;
87659       if( pTerm->leftCursor>=0 ){
87660         int idxNew;
87661         pDup = sqlite3ExprDup(db, pExpr, 0);
87662         if( db->mallocFailed ){
87663           sqlite3ExprDelete(db, pDup);
87664           return;
87665         }
87666         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
87667         if( idxNew==0 ) return;
87668         pNew = &pWC->a[idxNew];
87669         pNew->iParent = idxTerm;
87670         pTerm = &pWC->a[idxTerm];
87671         pTerm->nChild = 1;
87672         pTerm->wtFlags |= TERM_COPIED;
87673       }else{
87674         pDup = pExpr;
87675         pNew = pTerm;
87676       }
87677       exprCommute(pParse, pDup);
87678       pLeft = pDup->pLeft;
87679       pNew->leftCursor = pLeft->iTable;
87680       pNew->u.leftColumn = pLeft->iColumn;
87681       pNew->prereqRight = prereqLeft;
87682       pNew->prereqAll = prereqAll;
87683       pNew->eOperator = operatorMask(pDup->op);
87684     }
87685   }
87686
87687 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
87688   /* If a term is the BETWEEN operator, create two new virtual terms
87689   ** that define the range that the BETWEEN implements.  For example:
87690   **
87691   **      a BETWEEN b AND c
87692   **
87693   ** is converted into:
87694   **
87695   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
87696   **
87697   ** The two new terms are added onto the end of the WhereClause object.
87698   ** The new terms are "dynamic" and are children of the original BETWEEN
87699   ** term.  That means that if the BETWEEN term is coded, the children are
87700   ** skipped.  Or, if the children are satisfied by an index, the original
87701   ** BETWEEN term is skipped.
87702   */
87703   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
87704     ExprList *pList = pExpr->x.pList;
87705     int i;
87706     static const u8 ops[] = {TK_GE, TK_LE};
87707     assert( pList!=0 );
87708     assert( pList->nExpr==2 );
87709     for(i=0; i<2; i++){
87710       Expr *pNewExpr;
87711       int idxNew;
87712       pNewExpr = sqlite3PExpr(pParse, ops[i], 
87713                              sqlite3ExprDup(db, pExpr->pLeft, 0),
87714                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
87715       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
87716       testcase( idxNew==0 );
87717       exprAnalyze(pSrc, pWC, idxNew);
87718       pTerm = &pWC->a[idxTerm];
87719       pWC->a[idxNew].iParent = idxTerm;
87720     }
87721     pTerm->nChild = 2;
87722   }
87723 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
87724
87725 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
87726   /* Analyze a term that is composed of two or more subterms connected by
87727   ** an OR operator.
87728   */
87729   else if( pExpr->op==TK_OR ){
87730     assert( pWC->op==TK_AND );
87731     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
87732     pTerm = &pWC->a[idxTerm];
87733   }
87734 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
87735
87736 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
87737   /* Add constraints to reduce the search space on a LIKE or GLOB
87738   ** operator.
87739   **
87740   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
87741   **
87742   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
87743   **
87744   ** The last character of the prefix "abc" is incremented to form the
87745   ** termination condition "abd".
87746   */
87747   if( pWC->op==TK_AND 
87748    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
87749   ){
87750     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
87751     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
87752     Expr *pNewExpr1;
87753     Expr *pNewExpr2;
87754     int idxNew1;
87755     int idxNew2;
87756
87757     pLeft = pExpr->x.pList->a[1].pExpr;
87758     pStr2 = sqlite3ExprDup(db, pStr1, 0);
87759     if( !db->mallocFailed ){
87760       u8 c, *pC;       /* Last character before the first wildcard */
87761       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
87762       c = *pC;
87763       if( noCase ){
87764         /* The point is to increment the last character before the first
87765         ** wildcard.  But if we increment '@', that will push it into the
87766         ** alphabetic range where case conversions will mess up the 
87767         ** inequality.  To avoid this, make sure to also run the full
87768         ** LIKE on all candidate expressions by clearing the isComplete flag
87769         */
87770         if( c=='A'-1 ) isComplete = 0;
87771
87772         c = sqlite3UpperToLower[c];
87773       }
87774       *pC = c + 1;
87775     }
87776     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft,0),pStr1,0);
87777     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
87778     testcase( idxNew1==0 );
87779     exprAnalyze(pSrc, pWC, idxNew1);
87780     pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft,0),pStr2,0);
87781     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
87782     testcase( idxNew2==0 );
87783     exprAnalyze(pSrc, pWC, idxNew2);
87784     pTerm = &pWC->a[idxTerm];
87785     if( isComplete ){
87786       pWC->a[idxNew1].iParent = idxTerm;
87787       pWC->a[idxNew2].iParent = idxTerm;
87788       pTerm->nChild = 2;
87789     }
87790   }
87791 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
87792
87793 #ifndef SQLITE_OMIT_VIRTUALTABLE
87794   /* Add a WO_MATCH auxiliary term to the constraint set if the
87795   ** current expression is of the form:  column MATCH expr.
87796   ** This information is used by the xBestIndex methods of
87797   ** virtual tables.  The native query optimizer does not attempt
87798   ** to do anything with MATCH functions.
87799   */
87800   if( isMatchOfColumn(pExpr) ){
87801     int idxNew;
87802     Expr *pRight, *pLeft;
87803     WhereTerm *pNewTerm;
87804     Bitmask prereqColumn, prereqExpr;
87805
87806     pRight = pExpr->x.pList->a[0].pExpr;
87807     pLeft = pExpr->x.pList->a[1].pExpr;
87808     prereqExpr = exprTableUsage(pMaskSet, pRight);
87809     prereqColumn = exprTableUsage(pMaskSet, pLeft);
87810     if( (prereqExpr & prereqColumn)==0 ){
87811       Expr *pNewExpr;
87812       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
87813                               0, sqlite3ExprDup(db, pRight, 0), 0);
87814       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
87815       testcase( idxNew==0 );
87816       pNewTerm = &pWC->a[idxNew];
87817       pNewTerm->prereqRight = prereqExpr;
87818       pNewTerm->leftCursor = pLeft->iTable;
87819       pNewTerm->u.leftColumn = pLeft->iColumn;
87820       pNewTerm->eOperator = WO_MATCH;
87821       pNewTerm->iParent = idxTerm;
87822       pTerm = &pWC->a[idxTerm];
87823       pTerm->nChild = 1;
87824       pTerm->wtFlags |= TERM_COPIED;
87825       pNewTerm->prereqAll = pTerm->prereqAll;
87826     }
87827   }
87828 #endif /* SQLITE_OMIT_VIRTUALTABLE */
87829
87830   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
87831   ** an index for tables to the left of the join.
87832   */
87833   pTerm->prereqRight |= extraRight;
87834 }
87835
87836 /*
87837 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
87838 ** a reference to any table other than the iBase table.
87839 */
87840 static int referencesOtherTables(
87841   ExprList *pList,          /* Search expressions in ths list */
87842   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
87843   int iFirst,               /* Be searching with the iFirst-th expression */
87844   int iBase                 /* Ignore references to this table */
87845 ){
87846   Bitmask allowed = ~getMask(pMaskSet, iBase);
87847   while( iFirst<pList->nExpr ){
87848     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
87849       return 1;
87850     }
87851   }
87852   return 0;
87853 }
87854
87855
87856 /*
87857 ** This routine decides if pIdx can be used to satisfy the ORDER BY
87858 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
87859 ** ORDER BY clause, this routine returns 0.
87860 **
87861 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
87862 ** left-most table in the FROM clause of that same SELECT statement and
87863 ** the table has a cursor number of "base".  pIdx is an index on pTab.
87864 **
87865 ** nEqCol is the number of columns of pIdx that are used as equality
87866 ** constraints.  Any of these columns may be missing from the ORDER BY
87867 ** clause and the match can still be a success.
87868 **
87869 ** All terms of the ORDER BY that match against the index must be either
87870 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
87871 ** index do not need to satisfy this constraint.)  The *pbRev value is
87872 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
87873 ** the ORDER BY clause is all ASC.
87874 */
87875 static int isSortingIndex(
87876   Parse *pParse,          /* Parsing context */
87877   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
87878   Index *pIdx,            /* The index we are testing */
87879   int base,               /* Cursor number for the table to be sorted */
87880   ExprList *pOrderBy,     /* The ORDER BY clause */
87881   int nEqCol,             /* Number of index columns with == constraints */
87882   int *pbRev              /* Set to 1 if ORDER BY is DESC */
87883 ){
87884   int i, j;                       /* Loop counters */
87885   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
87886   int nTerm;                      /* Number of ORDER BY terms */
87887   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
87888   sqlite3 *db = pParse->db;
87889
87890   assert( pOrderBy!=0 );
87891   nTerm = pOrderBy->nExpr;
87892   assert( nTerm>0 );
87893
87894   /* Argument pIdx must either point to a 'real' named index structure, 
87895   ** or an index structure allocated on the stack by bestBtreeIndex() to
87896   ** represent the rowid index that is part of every table.  */
87897   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
87898
87899   /* Match terms of the ORDER BY clause against columns of
87900   ** the index.
87901   **
87902   ** Note that indices have pIdx->nColumn regular columns plus
87903   ** one additional column containing the rowid.  The rowid column
87904   ** of the index is also allowed to match against the ORDER BY
87905   ** clause.
87906   */
87907   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
87908     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
87909     CollSeq *pColl;    /* The collating sequence of pExpr */
87910     int termSortOrder; /* Sort order for this term */
87911     int iColumn;       /* The i-th column of the index.  -1 for rowid */
87912     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
87913     const char *zColl; /* Name of the collating sequence for i-th index term */
87914
87915     pExpr = pTerm->pExpr;
87916     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
87917       /* Can not use an index sort on anything that is not a column in the
87918       ** left-most table of the FROM clause */
87919       break;
87920     }
87921     pColl = sqlite3ExprCollSeq(pParse, pExpr);
87922     if( !pColl ){
87923       pColl = db->pDfltColl;
87924     }
87925     if( pIdx->zName && i<pIdx->nColumn ){
87926       iColumn = pIdx->aiColumn[i];
87927       if( iColumn==pIdx->pTable->iPKey ){
87928         iColumn = -1;
87929       }
87930       iSortOrder = pIdx->aSortOrder[i];
87931       zColl = pIdx->azColl[i];
87932     }else{
87933       iColumn = -1;
87934       iSortOrder = 0;
87935       zColl = pColl->zName;
87936     }
87937     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
87938       /* Term j of the ORDER BY clause does not match column i of the index */
87939       if( i<nEqCol ){
87940         /* If an index column that is constrained by == fails to match an
87941         ** ORDER BY term, that is OK.  Just ignore that column of the index
87942         */
87943         continue;
87944       }else if( i==pIdx->nColumn ){
87945         /* Index column i is the rowid.  All other terms match. */
87946         break;
87947       }else{
87948         /* If an index column fails to match and is not constrained by ==
87949         ** then the index cannot satisfy the ORDER BY constraint.
87950         */
87951         return 0;
87952       }
87953     }
87954     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
87955     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
87956     assert( iSortOrder==0 || iSortOrder==1 );
87957     termSortOrder = iSortOrder ^ pTerm->sortOrder;
87958     if( i>nEqCol ){
87959       if( termSortOrder!=sortOrder ){
87960         /* Indices can only be used if all ORDER BY terms past the
87961         ** equality constraints are all either DESC or ASC. */
87962         return 0;
87963       }
87964     }else{
87965       sortOrder = termSortOrder;
87966     }
87967     j++;
87968     pTerm++;
87969     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
87970       /* If the indexed column is the primary key and everything matches
87971       ** so far and none of the ORDER BY terms to the right reference other
87972       ** tables in the join, then we are assured that the index can be used 
87973       ** to sort because the primary key is unique and so none of the other
87974       ** columns will make any difference
87975       */
87976       j = nTerm;
87977     }
87978   }
87979
87980   *pbRev = sortOrder!=0;
87981   if( j>=nTerm ){
87982     /* All terms of the ORDER BY clause are covered by this index so
87983     ** this index can be used for sorting. */
87984     return 1;
87985   }
87986   if( pIdx->onError!=OE_None && i==pIdx->nColumn
87987       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
87988     /* All terms of this index match some prefix of the ORDER BY clause
87989     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
87990     ** clause reference other tables in a join.  If this is all true then
87991     ** the order by clause is superfluous. */
87992     return 1;
87993   }
87994   return 0;
87995 }
87996
87997 /*
87998 ** Prepare a crude estimate of the logarithm of the input value.
87999 ** The results need not be exact.  This is only used for estimating
88000 ** the total cost of performing operations with O(logN) or O(NlogN)
88001 ** complexity.  Because N is just a guess, it is no great tragedy if
88002 ** logN is a little off.
88003 */
88004 static double estLog(double N){
88005   double logN = 1;
88006   double x = 10;
88007   while( N>x ){
88008     logN += 1;
88009     x *= 10;
88010   }
88011   return logN;
88012 }
88013
88014 /*
88015 ** Two routines for printing the content of an sqlite3_index_info
88016 ** structure.  Used for testing and debugging only.  If neither
88017 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
88018 ** are no-ops.
88019 */
88020 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
88021 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
88022   int i;
88023   if( !sqlite3WhereTrace ) return;
88024   for(i=0; i<p->nConstraint; i++){
88025     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
88026        i,
88027        p->aConstraint[i].iColumn,
88028        p->aConstraint[i].iTermOffset,
88029        p->aConstraint[i].op,
88030        p->aConstraint[i].usable);
88031   }
88032   for(i=0; i<p->nOrderBy; i++){
88033     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
88034        i,
88035        p->aOrderBy[i].iColumn,
88036        p->aOrderBy[i].desc);
88037   }
88038 }
88039 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
88040   int i;
88041   if( !sqlite3WhereTrace ) return;
88042   for(i=0; i<p->nConstraint; i++){
88043     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
88044        i,
88045        p->aConstraintUsage[i].argvIndex,
88046        p->aConstraintUsage[i].omit);
88047   }
88048   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
88049   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
88050   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
88051   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
88052 }
88053 #else
88054 #define TRACE_IDX_INPUTS(A)
88055 #define TRACE_IDX_OUTPUTS(A)
88056 #endif
88057
88058 /* 
88059 ** Required because bestIndex() is called by bestOrClauseIndex() 
88060 */
88061 static void bestIndex(
88062     Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*);
88063
88064 /*
88065 ** This routine attempts to find an scanning strategy that can be used 
88066 ** to optimize an 'OR' expression that is part of a WHERE clause. 
88067 **
88068 ** The table associated with FROM clause term pSrc may be either a
88069 ** regular B-Tree table or a virtual table.
88070 */
88071 static void bestOrClauseIndex(
88072   Parse *pParse,              /* The parsing context */
88073   WhereClause *pWC,           /* The WHERE clause */
88074   struct SrcList_item *pSrc,  /* The FROM clause term to search */
88075   Bitmask notReady,           /* Mask of cursors that are not available */
88076   ExprList *pOrderBy,         /* The ORDER BY clause */
88077   WhereCost *pCost            /* Lowest cost query plan */
88078 ){
88079 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
88080   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
88081   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
88082   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
88083   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
88084
88085   /* Search the WHERE clause terms for a usable WO_OR term. */
88086   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
88087     if( pTerm->eOperator==WO_OR 
88088      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
88089      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
88090     ){
88091       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
88092       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
88093       WhereTerm *pOrTerm;
88094       int flags = WHERE_MULTI_OR;
88095       double rTotal = 0;
88096       double nRow = 0;
88097       Bitmask used = 0;
88098
88099       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
88100         WhereCost sTermCost;
88101         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
88102           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
88103         ));
88104         if( pOrTerm->eOperator==WO_AND ){
88105           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
88106           bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
88107         }else if( pOrTerm->leftCursor==iCur ){
88108           WhereClause tempWC;
88109           tempWC.pParse = pWC->pParse;
88110           tempWC.pMaskSet = pWC->pMaskSet;
88111           tempWC.op = TK_AND;
88112           tempWC.a = pOrTerm;
88113           tempWC.nTerm = 1;
88114           bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
88115         }else{
88116           continue;
88117         }
88118         rTotal += sTermCost.rCost;
88119         nRow += sTermCost.nRow;
88120         used |= sTermCost.used;
88121         if( rTotal>=pCost->rCost ) break;
88122       }
88123
88124       /* If there is an ORDER BY clause, increase the scan cost to account 
88125       ** for the cost of the sort. */
88126       if( pOrderBy!=0 ){
88127         rTotal += nRow*estLog(nRow);
88128         WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
88129       }
88130
88131       /* If the cost of scanning using this OR term for optimization is
88132       ** less than the current cost stored in pCost, replace the contents
88133       ** of pCost. */
88134       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
88135       if( rTotal<pCost->rCost ){
88136         pCost->rCost = rTotal;
88137         pCost->nRow = nRow;
88138         pCost->used = used;
88139         pCost->plan.wsFlags = flags;
88140         pCost->plan.u.pTerm = pTerm;
88141       }
88142     }
88143   }
88144 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
88145 }
88146
88147 #ifndef SQLITE_OMIT_VIRTUALTABLE
88148 /*
88149 ** Allocate and populate an sqlite3_index_info structure. It is the 
88150 ** responsibility of the caller to eventually release the structure
88151 ** by passing the pointer returned by this function to sqlite3_free().
88152 */
88153 static sqlite3_index_info *allocateIndexInfo(
88154   Parse *pParse, 
88155   WhereClause *pWC,
88156   struct SrcList_item *pSrc,
88157   ExprList *pOrderBy
88158 ){
88159   int i, j;
88160   int nTerm;
88161   struct sqlite3_index_constraint *pIdxCons;
88162   struct sqlite3_index_orderby *pIdxOrderBy;
88163   struct sqlite3_index_constraint_usage *pUsage;
88164   WhereTerm *pTerm;
88165   int nOrderBy;
88166   sqlite3_index_info *pIdxInfo;
88167
88168   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
88169
88170   /* Count the number of possible WHERE clause constraints referring
88171   ** to this virtual table */
88172   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
88173     if( pTerm->leftCursor != pSrc->iCursor ) continue;
88174     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
88175     testcase( pTerm->eOperator==WO_IN );
88176     testcase( pTerm->eOperator==WO_ISNULL );
88177     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
88178     nTerm++;
88179   }
88180
88181   /* If the ORDER BY clause contains only columns in the current 
88182   ** virtual table then allocate space for the aOrderBy part of
88183   ** the sqlite3_index_info structure.
88184   */
88185   nOrderBy = 0;
88186   if( pOrderBy ){
88187     for(i=0; i<pOrderBy->nExpr; i++){
88188       Expr *pExpr = pOrderBy->a[i].pExpr;
88189       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
88190     }
88191     if( i==pOrderBy->nExpr ){
88192       nOrderBy = pOrderBy->nExpr;
88193     }
88194   }
88195
88196   /* Allocate the sqlite3_index_info structure
88197   */
88198   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
88199                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
88200                            + sizeof(*pIdxOrderBy)*nOrderBy );
88201   if( pIdxInfo==0 ){
88202     sqlite3ErrorMsg(pParse, "out of memory");
88203     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
88204     return 0;
88205   }
88206
88207   /* Initialize the structure.  The sqlite3_index_info structure contains
88208   ** many fields that are declared "const" to prevent xBestIndex from
88209   ** changing them.  We have to do some funky casting in order to
88210   ** initialize those fields.
88211   */
88212   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
88213   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
88214   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
88215   *(int*)&pIdxInfo->nConstraint = nTerm;
88216   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
88217   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
88218   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
88219   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
88220                                                                    pUsage;
88221
88222   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
88223     if( pTerm->leftCursor != pSrc->iCursor ) continue;
88224     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
88225     testcase( pTerm->eOperator==WO_IN );
88226     testcase( pTerm->eOperator==WO_ISNULL );
88227     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
88228     pIdxCons[j].iColumn = pTerm->u.leftColumn;
88229     pIdxCons[j].iTermOffset = i;
88230     pIdxCons[j].op = (u8)pTerm->eOperator;
88231     /* The direct assignment in the previous line is possible only because
88232     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
88233     ** following asserts verify this fact. */
88234     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
88235     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
88236     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
88237     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
88238     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
88239     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
88240     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
88241     j++;
88242   }
88243   for(i=0; i<nOrderBy; i++){
88244     Expr *pExpr = pOrderBy->a[i].pExpr;
88245     pIdxOrderBy[i].iColumn = pExpr->iColumn;
88246     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
88247   }
88248
88249   return pIdxInfo;
88250 }
88251
88252 /*
88253 ** The table object reference passed as the second argument to this function
88254 ** must represent a virtual table. This function invokes the xBestIndex()
88255 ** method of the virtual table with the sqlite3_index_info pointer passed
88256 ** as the argument.
88257 **
88258 ** If an error occurs, pParse is populated with an error message and a
88259 ** non-zero value is returned. Otherwise, 0 is returned and the output
88260 ** part of the sqlite3_index_info structure is left populated.
88261 **
88262 ** Whether or not an error is returned, it is the responsibility of the
88263 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
88264 ** that this is required.
88265 */
88266 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
88267   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
88268   int i;
88269   int rc;
88270
88271   (void)sqlite3SafetyOff(pParse->db);
88272   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
88273   TRACE_IDX_INPUTS(p);
88274   rc = pVtab->pModule->xBestIndex(pVtab, p);
88275   TRACE_IDX_OUTPUTS(p);
88276   (void)sqlite3SafetyOn(pParse->db);
88277
88278   if( rc!=SQLITE_OK ){
88279     if( rc==SQLITE_NOMEM ){
88280       pParse->db->mallocFailed = 1;
88281     }else if( !pVtab->zErrMsg ){
88282       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
88283     }else{
88284       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
88285     }
88286   }
88287   sqlite3DbFree(pParse->db, pVtab->zErrMsg);
88288   pVtab->zErrMsg = 0;
88289
88290   for(i=0; i<p->nConstraint; i++){
88291     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
88292       sqlite3ErrorMsg(pParse, 
88293           "table %s: xBestIndex returned an invalid plan", pTab->zName);
88294     }
88295   }
88296
88297   return pParse->nErr;
88298 }
88299
88300
88301 /*
88302 ** Compute the best index for a virtual table.
88303 **
88304 ** The best index is computed by the xBestIndex method of the virtual
88305 ** table module.  This routine is really just a wrapper that sets up
88306 ** the sqlite3_index_info structure that is used to communicate with
88307 ** xBestIndex.
88308 **
88309 ** In a join, this routine might be called multiple times for the
88310 ** same virtual table.  The sqlite3_index_info structure is created
88311 ** and initialized on the first invocation and reused on all subsequent
88312 ** invocations.  The sqlite3_index_info structure is also used when
88313 ** code is generated to access the virtual table.  The whereInfoDelete() 
88314 ** routine takes care of freeing the sqlite3_index_info structure after
88315 ** everybody has finished with it.
88316 */
88317 static void bestVirtualIndex(
88318   Parse *pParse,                  /* The parsing context */
88319   WhereClause *pWC,               /* The WHERE clause */
88320   struct SrcList_item *pSrc,      /* The FROM clause term to search */
88321   Bitmask notReady,               /* Mask of cursors that are not available */
88322   ExprList *pOrderBy,             /* The order by clause */
88323   WhereCost *pCost,               /* Lowest cost query plan */
88324   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
88325 ){
88326   Table *pTab = pSrc->pTab;
88327   sqlite3_index_info *pIdxInfo;
88328   struct sqlite3_index_constraint *pIdxCons;
88329   struct sqlite3_index_constraint_usage *pUsage;
88330   WhereTerm *pTerm;
88331   int i, j;
88332   int nOrderBy;
88333
88334   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
88335   ** malloc in allocateIndexInfo() fails and this function returns leaving
88336   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
88337   */
88338   memset(pCost, 0, sizeof(*pCost));
88339   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
88340
88341   /* If the sqlite3_index_info structure has not been previously
88342   ** allocated and initialized, then allocate and initialize it now.
88343   */
88344   pIdxInfo = *ppIdxInfo;
88345   if( pIdxInfo==0 ){
88346     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
88347   }
88348   if( pIdxInfo==0 ){
88349     return;
88350   }
88351
88352   /* At this point, the sqlite3_index_info structure that pIdxInfo points
88353   ** to will have been initialized, either during the current invocation or
88354   ** during some prior invocation.  Now we just have to customize the
88355   ** details of pIdxInfo for the current invocation and pass it to
88356   ** xBestIndex.
88357   */
88358
88359   /* The module name must be defined. Also, by this point there must
88360   ** be a pointer to an sqlite3_vtab structure. Otherwise
88361   ** sqlite3ViewGetColumnNames() would have picked up the error. 
88362   */
88363   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
88364   assert( sqlite3GetVTable(pParse->db, pTab) );
88365
88366   /* Set the aConstraint[].usable fields and initialize all 
88367   ** output variables to zero.
88368   **
88369   ** aConstraint[].usable is true for constraints where the right-hand
88370   ** side contains only references to tables to the left of the current
88371   ** table.  In other words, if the constraint is of the form:
88372   **
88373   **           column = expr
88374   **
88375   ** and we are evaluating a join, then the constraint on column is 
88376   ** only valid if all tables referenced in expr occur to the left
88377   ** of the table containing column.
88378   **
88379   ** The aConstraints[] array contains entries for all constraints
88380   ** on the current table.  That way we only have to compute it once
88381   ** even though we might try to pick the best index multiple times.
88382   ** For each attempt at picking an index, the order of tables in the
88383   ** join might be different so we have to recompute the usable flag
88384   ** each time.
88385   */
88386   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
88387   pUsage = pIdxInfo->aConstraintUsage;
88388   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
88389     j = pIdxCons->iTermOffset;
88390     pTerm = &pWC->a[j];
88391     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
88392   }
88393   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
88394   if( pIdxInfo->needToFreeIdxStr ){
88395     sqlite3_free(pIdxInfo->idxStr);
88396   }
88397   pIdxInfo->idxStr = 0;
88398   pIdxInfo->idxNum = 0;
88399   pIdxInfo->needToFreeIdxStr = 0;
88400   pIdxInfo->orderByConsumed = 0;
88401   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
88402   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
88403   nOrderBy = pIdxInfo->nOrderBy;
88404   if( !pOrderBy ){
88405     pIdxInfo->nOrderBy = 0;
88406   }
88407
88408   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
88409     return;
88410   }
88411
88412   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
88413   for(i=0; i<pIdxInfo->nConstraint; i++){
88414     if( pUsage[i].argvIndex>0 ){
88415       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
88416     }
88417   }
88418
88419   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
88420   ** inital value of lowestCost in this loop. If it is, then the
88421   ** (cost<lowestCost) test below will never be true.
88422   ** 
88423   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
88424   ** is defined.
88425   */
88426   if( (SQLITE_BIG_DBL/((double)2))<pIdxInfo->estimatedCost ){
88427     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
88428   }else{
88429     pCost->rCost = pIdxInfo->estimatedCost;
88430   }
88431   pCost->plan.u.pVtabIdx = pIdxInfo;
88432   if( pIdxInfo->orderByConsumed ){
88433     pCost->plan.wsFlags |= WHERE_ORDERBY;
88434   }
88435   pCost->plan.nEq = 0;
88436   pIdxInfo->nOrderBy = nOrderBy;
88437
88438   /* Try to find a more efficient access pattern by using multiple indexes
88439   ** to optimize an OR expression within the WHERE clause. 
88440   */
88441   bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
88442 }
88443 #endif /* SQLITE_OMIT_VIRTUALTABLE */
88444
88445 /*
88446 ** Argument pIdx is a pointer to an index structure that has an array of
88447 ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
88448 ** stored in Index.aSample. The domain of values stored in said column
88449 ** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
88450 ** Region 0 contains all values smaller than the first sample value. Region
88451 ** 1 contains values larger than or equal to the value of the first sample,
88452 ** but smaller than the value of the second. And so on.
88453 **
88454 ** If successful, this function determines which of the regions value 
88455 ** pVal lies in, sets *piRegion to the region index (a value between 0
88456 ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
88457 ** Or, if an OOM occurs while converting text values between encodings,
88458 ** SQLITE_NOMEM is returned and *piRegion is undefined.
88459 */
88460 #ifdef SQLITE_ENABLE_STAT2
88461 static int whereRangeRegion(
88462   Parse *pParse,              /* Database connection */
88463   Index *pIdx,                /* Index to consider domain of */
88464   sqlite3_value *pVal,        /* Value to consider */
88465   int *piRegion               /* OUT: Region of domain in which value lies */
88466 ){
88467   if( ALWAYS(pVal) ){
88468     IndexSample *aSample = pIdx->aSample;
88469     int i = 0;
88470     int eType = sqlite3_value_type(pVal);
88471
88472     if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
88473       double r = sqlite3_value_double(pVal);
88474       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
88475         if( aSample[i].eType==SQLITE_NULL ) continue;
88476         if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
88477       }
88478     }else{ 
88479       sqlite3 *db = pParse->db;
88480       CollSeq *pColl;
88481       const u8 *z;
88482       int n;
88483
88484       /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
88485       assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
88486
88487       if( eType==SQLITE_BLOB ){
88488         z = (const u8 *)sqlite3_value_blob(pVal);
88489         pColl = db->pDfltColl;
88490         assert( pColl->enc==SQLITE_UTF8 );
88491       }else{
88492         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
88493         if( pColl==0 ){
88494           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
88495                           *pIdx->azColl);
88496           return SQLITE_ERROR;
88497         }
88498         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
88499         if( !z ){
88500           return SQLITE_NOMEM;
88501         }
88502         assert( z && pColl && pColl->xCmp );
88503       }
88504       n = sqlite3ValueBytes(pVal, pColl->enc);
88505
88506       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
88507         int r;
88508         int eSampletype = aSample[i].eType;
88509         if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
88510         if( (eSampletype!=eType) ) break;
88511 #ifndef SQLITE_OMIT_UTF16
88512         if( pColl->enc!=SQLITE_UTF8 ){
88513           int nSample;
88514           char *zSample = sqlite3Utf8to16(
88515               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
88516           );
88517           if( !zSample ){
88518             assert( db->mallocFailed );
88519             return SQLITE_NOMEM;
88520           }
88521           r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
88522           sqlite3DbFree(db, zSample);
88523         }else
88524 #endif
88525         {
88526           r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
88527         }
88528         if( r>0 ) break;
88529       }
88530     }
88531
88532     assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
88533     *piRegion = i;
88534   }
88535   return SQLITE_OK;
88536 }
88537 #endif   /* #ifdef SQLITE_ENABLE_STAT2 */
88538
88539 /*
88540 ** If expression pExpr represents a literal value, set *pp to point to
88541 ** an sqlite3_value structure containing the same value, with affinity
88542 ** aff applied to it, before returning. It is the responsibility of the 
88543 ** caller to eventually release this structure by passing it to 
88544 ** sqlite3ValueFree().
88545 **
88546 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
88547 ** is an SQL variable that currently has a non-NULL value bound to it,
88548 ** create an sqlite3_value structure containing this value, again with
88549 ** affinity aff applied to it, instead.
88550 **
88551 ** If neither of the above apply, set *pp to NULL.
88552 **
88553 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
88554 */
88555 #ifdef SQLITE_ENABLE_STAT2
88556 static int valueFromExpr(
88557   Parse *pParse, 
88558   Expr *pExpr, 
88559   u8 aff, 
88560   sqlite3_value **pp
88561 ){
88562   /* The evalConstExpr() function will have already converted any TK_VARIABLE
88563   ** expression involved in an comparison into a TK_REGISTER. */
88564   assert( pExpr->op!=TK_VARIABLE );
88565   if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
88566     int iVar = pExpr->iColumn;
88567     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
88568     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
88569     return SQLITE_OK;
88570   }
88571   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
88572 }
88573 #endif
88574
88575 /*
88576 ** This function is used to estimate the number of rows that will be visited
88577 ** by scanning an index for a range of values. The range may have an upper
88578 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
88579 ** and lower bounds are represented by pLower and pUpper respectively. For
88580 ** example, assuming that index p is on t1(a):
88581 **
88582 **   ... FROM t1 WHERE a > ? AND a < ? ...
88583 **                    |_____|   |_____|
88584 **                       |         |
88585 **                     pLower    pUpper
88586 **
88587 ** If either of the upper or lower bound is not present, then NULL is passed in
88588 ** place of the corresponding WhereTerm.
88589 **
88590 ** The nEq parameter is passed the index of the index column subject to the
88591 ** range constraint. Or, equivalently, the number of equality constraints
88592 ** optimized by the proposed index scan. For example, assuming index p is
88593 ** on t1(a, b), and the SQL query is:
88594 **
88595 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
88596 **
88597 ** then nEq should be passed the value 1 (as the range restricted column,
88598 ** b, is the second left-most column of the index). Or, if the query is:
88599 **
88600 **   ... FROM t1 WHERE a > ? AND a < ? ...
88601 **
88602 ** then nEq should be passed 0.
88603 **
88604 ** The returned value is an integer between 1 and 100, inclusive. A return
88605 ** value of 1 indicates that the proposed range scan is expected to visit
88606 ** approximately 1/100th (1%) of the rows selected by the nEq equality
88607 ** constraints (if any). A return value of 100 indicates that it is expected
88608 ** that the range scan will visit every row (100%) selected by the equality
88609 ** constraints.
88610 **
88611 ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
88612 ** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
88613 ** results in a return of 33 and a range constraint (x>? AND x<?) results
88614 ** in a return of 11.
88615 */
88616 static int whereRangeScanEst(
88617   Parse *pParse,       /* Parsing & code generating context */
88618   Index *p,            /* The index containing the range-compared column; "x" */
88619   int nEq,             /* index into p->aCol[] of the range-compared column */
88620   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
88621   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
88622   int *piEst           /* OUT: Return value */
88623 ){
88624   int rc = SQLITE_OK;
88625
88626 #ifdef SQLITE_ENABLE_STAT2
88627
88628   if( nEq==0 && p->aSample ){
88629     sqlite3_value *pLowerVal = 0;
88630     sqlite3_value *pUpperVal = 0;
88631     int iEst;
88632     int iLower = 0;
88633     int iUpper = SQLITE_INDEX_SAMPLES;
88634     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
88635
88636     if( pLower ){
88637       Expr *pExpr = pLower->pExpr->pRight;
88638       rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
88639     }
88640     if( rc==SQLITE_OK && pUpper ){
88641       Expr *pExpr = pUpper->pExpr->pRight;
88642       rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
88643     }
88644
88645     if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
88646       sqlite3ValueFree(pLowerVal);
88647       sqlite3ValueFree(pUpperVal);
88648       goto range_est_fallback;
88649     }else if( pLowerVal==0 ){
88650       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
88651       if( pLower ) iLower = iUpper/2;
88652     }else if( pUpperVal==0 ){
88653       rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
88654       if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
88655     }else{
88656       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
88657       if( rc==SQLITE_OK ){
88658         rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
88659       }
88660     }
88661
88662     iEst = iUpper - iLower;
88663     testcase( iEst==SQLITE_INDEX_SAMPLES );
88664     assert( iEst<=SQLITE_INDEX_SAMPLES );
88665     if( iEst<1 ){
88666       iEst = 1;
88667     }
88668
88669     sqlite3ValueFree(pLowerVal);
88670     sqlite3ValueFree(pUpperVal);
88671     *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
88672     return rc;
88673   }
88674 range_est_fallback:
88675 #else
88676   UNUSED_PARAMETER(pParse);
88677   UNUSED_PARAMETER(p);
88678   UNUSED_PARAMETER(nEq);
88679 #endif
88680   assert( pLower || pUpper );
88681   if( pLower && pUpper ){
88682     *piEst = 11;
88683   }else{
88684     *piEst = 33;
88685   }
88686   return rc;
88687 }
88688
88689
88690 /*
88691 ** Find the query plan for accessing a particular table.  Write the
88692 ** best query plan and its cost into the WhereCost object supplied as the
88693 ** last parameter.
88694 **
88695 ** The lowest cost plan wins.  The cost is an estimate of the amount of
88696 ** CPU and disk I/O need to process the request using the selected plan.
88697 ** Factors that influence cost include:
88698 **
88699 **    *  The estimated number of rows that will be retrieved.  (The
88700 **       fewer the better.)
88701 **
88702 **    *  Whether or not sorting must occur.
88703 **
88704 **    *  Whether or not there must be separate lookups in the
88705 **       index and in the main table.
88706 **
88707 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
88708 ** the SQL statement, then this function only considers plans using the 
88709 ** named index. If no such plan is found, then the returned cost is
88710 ** SQLITE_BIG_DBL. If a plan is found that uses the named index, 
88711 ** then the cost is calculated in the usual way.
88712 **
88713 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table 
88714 ** in the SELECT statement, then no indexes are considered. However, the 
88715 ** selected plan may still take advantage of the tables built-in rowid
88716 ** index.
88717 */
88718 static void bestBtreeIndex(
88719   Parse *pParse,              /* The parsing context */
88720   WhereClause *pWC,           /* The WHERE clause */
88721   struct SrcList_item *pSrc,  /* The FROM clause term to search */
88722   Bitmask notReady,           /* Mask of cursors that are not available */
88723   ExprList *pOrderBy,         /* The ORDER BY clause */
88724   WhereCost *pCost            /* Lowest cost query plan */
88725 ){
88726   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
88727   Index *pProbe;              /* An index we are evaluating */
88728   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
88729   int eqTermMask;             /* Current mask of valid equality operators */
88730   int idxEqTermMask;          /* Index mask of valid equality operators */
88731   Index sPk;                  /* A fake index object for the primary key */
88732   unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
88733   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
88734   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
88735
88736   /* Initialize the cost to a worst-case value */
88737   memset(pCost, 0, sizeof(*pCost));
88738   pCost->rCost = SQLITE_BIG_DBL;
88739
88740   /* If the pSrc table is the right table of a LEFT JOIN then we may not
88741   ** use an index to satisfy IS NULL constraints on that table.  This is
88742   ** because columns might end up being NULL if the table does not match -
88743   ** a circumstance which the index cannot help us discover.  Ticket #2177.
88744   */
88745   if( pSrc->jointype & JT_LEFT ){
88746     idxEqTermMask = WO_EQ|WO_IN;
88747   }else{
88748     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
88749   }
88750
88751   if( pSrc->pIndex ){
88752     /* An INDEXED BY clause specifies a particular index to use */
88753     pIdx = pProbe = pSrc->pIndex;
88754     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
88755     eqTermMask = idxEqTermMask;
88756   }else{
88757     /* There is no INDEXED BY clause.  Create a fake Index object to
88758     ** represent the primary key */
88759     Index *pFirst;                /* Any other index on the table */
88760     memset(&sPk, 0, sizeof(Index));
88761     sPk.nColumn = 1;
88762     sPk.aiColumn = &aiColumnPk;
88763     sPk.aiRowEst = aiRowEstPk;
88764     aiRowEstPk[1] = 1;
88765     sPk.onError = OE_Replace;
88766     sPk.pTable = pSrc->pTab;
88767     pFirst = pSrc->pTab->pIndex;
88768     if( pSrc->notIndexed==0 ){
88769       sPk.pNext = pFirst;
88770     }
88771     /* The aiRowEstPk[0] is an estimate of the total number of rows in the
88772     ** table.  Get this information from the ANALYZE information if it is
88773     ** available.  If not available, assume the table 1 million rows in size.
88774     */
88775     if( pFirst ){
88776       assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */
88777       aiRowEstPk[0] = pFirst->aiRowEst[0];
88778     }else{
88779       aiRowEstPk[0] = 1000000;
88780     }
88781     pProbe = &sPk;
88782     wsFlagMask = ~(
88783         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
88784     );
88785     eqTermMask = WO_EQ|WO_IN;
88786     pIdx = 0;
88787   }
88788
88789   /* Loop over all indices looking for the best one to use
88790   */
88791   for(; pProbe; pIdx=pProbe=pProbe->pNext){
88792     const unsigned int * const aiRowEst = pProbe->aiRowEst;
88793     double cost;                /* Cost of using pProbe */
88794     double nRow;                /* Estimated number of rows in result set */
88795     int rev;                    /* True to scan in reverse order */
88796     int wsFlags = 0;
88797     Bitmask used = 0;
88798
88799     /* The following variables are populated based on the properties of
88800     ** scan being evaluated. They are then used to determine the expected
88801     ** cost and number of rows returned.
88802     **
88803     **  nEq: 
88804     **    Number of equality terms that can be implemented using the index.
88805     **
88806     **  nInMul:  
88807     **    The "in-multiplier". This is an estimate of how many seek operations 
88808     **    SQLite must perform on the index in question. For example, if the 
88809     **    WHERE clause is:
88810     **
88811     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
88812     **
88813     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
88814     **    set to 9. Given the same schema and either of the following WHERE 
88815     **    clauses:
88816     **
88817     **      WHERE a =  1
88818     **      WHERE a >= 2
88819     **
88820     **    nInMul is set to 1.
88821     **
88822     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
88823     **    the sub-select is assumed to return 25 rows for the purposes of 
88824     **    determining nInMul.
88825     **
88826     **  bInEst:  
88827     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
88828     **    in determining the value of nInMul.
88829     **
88830     **  nBound:
88831     **    An estimate on the amount of the table that must be searched.  A
88832     **    value of 100 means the entire table is searched.  Range constraints
88833     **    might reduce this to a value less than 100 to indicate that only
88834     **    a fraction of the table needs searching.  In the absence of
88835     **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
88836     **    space to 1/3rd its original size.  So an x>? constraint reduces
88837     **    nBound to 33.  Two constraints (x>? AND x<?) reduce nBound to 11.
88838     **
88839     **  bSort:   
88840     **    Boolean. True if there is an ORDER BY clause that will require an 
88841     **    external sort (i.e. scanning the index being evaluated will not 
88842     **    correctly order records).
88843     **
88844     **  bLookup: 
88845     **    Boolean. True if for each index entry visited a lookup on the 
88846     **    corresponding table b-tree is required. This is always false 
88847     **    for the rowid index. For other indexes, it is true unless all the 
88848     **    columns of the table used by the SELECT statement are present in 
88849     **    the index (such an index is sometimes described as a covering index).
88850     **    For example, given the index on (a, b), the second of the following 
88851     **    two queries requires table b-tree lookups, but the first does not.
88852     **
88853     **             SELECT a, b    FROM tbl WHERE a = 1;
88854     **             SELECT a, b, c FROM tbl WHERE a = 1;
88855     */
88856     int nEq;
88857     int bInEst = 0;
88858     int nInMul = 1;
88859     int nBound = 100;
88860     int bSort = 0;
88861     int bLookup = 0;
88862
88863     /* Determine the values of nEq and nInMul */
88864     for(nEq=0; nEq<pProbe->nColumn; nEq++){
88865       WhereTerm *pTerm;           /* A single term of the WHERE clause */
88866       int j = pProbe->aiColumn[nEq];
88867       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
88868       if( pTerm==0 ) break;
88869       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
88870       if( pTerm->eOperator & WO_IN ){
88871         Expr *pExpr = pTerm->pExpr;
88872         wsFlags |= WHERE_COLUMN_IN;
88873         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88874           nInMul *= 25;
88875           bInEst = 1;
88876         }else if( pExpr->x.pList ){
88877           nInMul *= pExpr->x.pList->nExpr + 1;
88878         }
88879       }else if( pTerm->eOperator & WO_ISNULL ){
88880         wsFlags |= WHERE_COLUMN_NULL;
88881       }
88882       used |= pTerm->prereqRight;
88883     }
88884
88885     /* Determine the value of nBound. */
88886     if( nEq<pProbe->nColumn ){
88887       int j = pProbe->aiColumn[nEq];
88888       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
88889         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
88890         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
88891         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &nBound);
88892         if( pTop ){
88893           wsFlags |= WHERE_TOP_LIMIT;
88894           used |= pTop->prereqRight;
88895         }
88896         if( pBtm ){
88897           wsFlags |= WHERE_BTM_LIMIT;
88898           used |= pBtm->prereqRight;
88899         }
88900         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
88901       }
88902     }else if( pProbe->onError!=OE_None ){
88903       testcase( wsFlags & WHERE_COLUMN_IN );
88904       testcase( wsFlags & WHERE_COLUMN_NULL );
88905       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
88906         wsFlags |= WHERE_UNIQUE;
88907       }
88908     }
88909
88910     /* If there is an ORDER BY clause and the index being considered will
88911     ** naturally scan rows in the required order, set the appropriate flags
88912     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
88913     ** will scan rows in a different order, set the bSort variable.  */
88914     if( pOrderBy ){
88915       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
88916         && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
88917       ){
88918         wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
88919         wsFlags |= (rev ? WHERE_REVERSE : 0);
88920       }else{
88921         bSort = 1;
88922       }
88923     }
88924
88925     /* If currently calculating the cost of using an index (not the IPK
88926     ** index), determine if all required column data may be obtained without 
88927     ** seeking to entries in the main table (i.e. if the index is a covering
88928     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
88929     ** wsFlags. Otherwise, set the bLookup variable to true.  */
88930     if( pIdx && wsFlags ){
88931       Bitmask m = pSrc->colUsed;
88932       int j;
88933       for(j=0; j<pIdx->nColumn; j++){
88934         int x = pIdx->aiColumn[j];
88935         if( x<BMS-1 ){
88936           m &= ~(((Bitmask)1)<<x);
88937         }
88938       }
88939       if( m==0 ){
88940         wsFlags |= WHERE_IDX_ONLY;
88941       }else{
88942         bLookup = 1;
88943       }
88944     }
88945
88946     /**** Begin adding up the cost of using this index (Needs improvements)
88947     **
88948     ** Estimate the number of rows of output.  For an IN operator,
88949     ** do not let the estimate exceed half the rows in the table.
88950     */
88951     nRow = (double)(aiRowEst[nEq] * nInMul);
88952     if( bInEst && nRow*2>aiRowEst[0] ){
88953       nRow = aiRowEst[0]/2;
88954       nInMul = (int)(nRow / aiRowEst[nEq]);
88955     }
88956
88957     /* Assume constant cost to access a row and logarithmic cost to
88958     ** do a binary search.  Hence, the initial cost is the number of output
88959     ** rows plus log2(table-size) times the number of binary searches.
88960     */
88961     cost = nRow + nInMul*estLog(aiRowEst[0]);
88962
88963     /* Adjust the number of rows and the cost downward to reflect rows
88964     ** that are excluded by range constraints.
88965     */
88966     nRow = (nRow * (double)nBound) / (double)100;
88967     cost = (cost * (double)nBound) / (double)100;
88968
88969     /* Add in the estimated cost of sorting the result
88970     */
88971     if( bSort ){
88972       cost += cost*estLog(cost);
88973     }
88974
88975     /* If all information can be taken directly from the index, we avoid
88976     ** doing table lookups.  This reduces the cost by half.  (Not really -
88977     ** this needs to be fixed.)
88978     */
88979     if( pIdx && bLookup==0 ){
88980       cost /= (double)2;
88981     }
88982     /**** Cost of using this index has now been computed ****/
88983
88984     WHERETRACE((
88985       "tbl=%s idx=%s nEq=%d nInMul=%d nBound=%d bSort=%d bLookup=%d"
88986       " wsFlags=%d   (nRow=%.2f cost=%.2f)\n",
88987       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
88988       nEq, nInMul, nBound, bSort, bLookup, wsFlags, nRow, cost
88989     ));
88990
88991     /* If this index is the best we have seen so far, then record this
88992     ** index and its cost in the pCost structure.
88993     */
88994     if( (!pIdx || wsFlags) && cost<pCost->rCost ){
88995       pCost->rCost = cost;
88996       pCost->nRow = nRow;
88997       pCost->used = used;
88998       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
88999       pCost->plan.nEq = nEq;
89000       pCost->plan.u.pIdx = pIdx;
89001     }
89002
89003     /* If there was an INDEXED BY clause, then only that one index is
89004     ** considered. */
89005     if( pSrc->pIndex ) break;
89006
89007     /* Reset masks for the next index in the loop */
89008     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
89009     eqTermMask = idxEqTermMask;
89010   }
89011
89012   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
89013   ** is set, then reverse the order that the index will be scanned
89014   ** in. This is used for application testing, to help find cases
89015   ** where application behaviour depends on the (undefined) order that
89016   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
89017   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
89018     pCost->plan.wsFlags |= WHERE_REVERSE;
89019   }
89020
89021   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
89022   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
89023   assert( pSrc->pIndex==0 
89024        || pCost->plan.u.pIdx==0 
89025        || pCost->plan.u.pIdx==pSrc->pIndex 
89026   );
89027
89028   WHERETRACE(("best index is: %s\n", 
89029     (pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
89030   ));
89031   
89032   bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
89033   pCost->plan.wsFlags |= eqTermMask;
89034 }
89035
89036 /*
89037 ** Find the query plan for accessing table pSrc->pTab. Write the
89038 ** best query plan and its cost into the WhereCost object supplied 
89039 ** as the last parameter. This function may calculate the cost of
89040 ** both real and virtual table scans.
89041 */
89042 static void bestIndex(
89043   Parse *pParse,              /* The parsing context */
89044   WhereClause *pWC,           /* The WHERE clause */
89045   struct SrcList_item *pSrc,  /* The FROM clause term to search */
89046   Bitmask notReady,           /* Mask of cursors that are not available */
89047   ExprList *pOrderBy,         /* The ORDER BY clause */
89048   WhereCost *pCost            /* Lowest cost query plan */
89049 ){
89050 #ifndef SQLITE_OMIT_VIRTUALTABLE
89051   if( IsVirtual(pSrc->pTab) ){
89052     sqlite3_index_info *p = 0;
89053     bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p);
89054     if( p->needToFreeIdxStr ){
89055       sqlite3_free(p->idxStr);
89056     }
89057     sqlite3DbFree(pParse->db, p);
89058   }else
89059 #endif
89060   {
89061     bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
89062   }
89063 }
89064
89065 /*
89066 ** Disable a term in the WHERE clause.  Except, do not disable the term
89067 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
89068 ** or USING clause of that join.
89069 **
89070 ** Consider the term t2.z='ok' in the following queries:
89071 **
89072 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
89073 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
89074 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
89075 **
89076 ** The t2.z='ok' is disabled in the in (2) because it originates
89077 ** in the ON clause.  The term is disabled in (3) because it is not part
89078 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
89079 **
89080 ** Disabling a term causes that term to not be tested in the inner loop
89081 ** of the join.  Disabling is an optimization.  When terms are satisfied
89082 ** by indices, we disable them to prevent redundant tests in the inner
89083 ** loop.  We would get the correct results if nothing were ever disabled,
89084 ** but joins might run a little slower.  The trick is to disable as much
89085 ** as we can without disabling too much.  If we disabled in (1), we'd get
89086 ** the wrong answer.  See ticket #813.
89087 */
89088 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
89089   if( pTerm
89090       && ALWAYS((pTerm->wtFlags & TERM_CODED)==0)
89091       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
89092   ){
89093     pTerm->wtFlags |= TERM_CODED;
89094     if( pTerm->iParent>=0 ){
89095       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
89096       if( (--pOther->nChild)==0 ){
89097         disableTerm(pLevel, pOther);
89098       }
89099     }
89100   }
89101 }
89102
89103 /*
89104 ** Code an OP_Affinity opcode to apply the column affinity string zAff
89105 ** to the n registers starting at base. 
89106 **
89107 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
89108 ** beginning and end of zAff are ignored.  If all entries in zAff are
89109 ** SQLITE_AFF_NONE, then no code gets generated.
89110 **
89111 ** This routine makes its own copy of zAff so that the caller is free
89112 ** to modify zAff after this routine returns.
89113 */
89114 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
89115   Vdbe *v = pParse->pVdbe;
89116   if( zAff==0 ){
89117     assert( pParse->db->mallocFailed );
89118     return;
89119   }
89120   assert( v!=0 );
89121
89122   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
89123   ** and end of the affinity string.
89124   */
89125   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
89126     n--;
89127     base++;
89128     zAff++;
89129   }
89130   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
89131     n--;
89132   }
89133
89134   /* Code the OP_Affinity opcode if there is anything left to do. */
89135   if( n>0 ){
89136     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
89137     sqlite3VdbeChangeP4(v, -1, zAff, n);
89138     sqlite3ExprCacheAffinityChange(pParse, base, n);
89139   }
89140 }
89141
89142
89143 /*
89144 ** Generate code for a single equality term of the WHERE clause.  An equality
89145 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
89146 ** coded.
89147 **
89148 ** The current value for the constraint is left in register iReg.
89149 **
89150 ** For a constraint of the form X=expr, the expression is evaluated and its
89151 ** result is left on the stack.  For constraints of the form X IN (...)
89152 ** this routine sets up a loop that will iterate over all values of X.
89153 */
89154 static int codeEqualityTerm(
89155   Parse *pParse,      /* The parsing context */
89156   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
89157   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
89158   int iTarget         /* Attempt to leave results in this register */
89159 ){
89160   Expr *pX = pTerm->pExpr;
89161   Vdbe *v = pParse->pVdbe;
89162   int iReg;                  /* Register holding results */
89163
89164   assert( iTarget>0 );
89165   if( pX->op==TK_EQ ){
89166     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
89167   }else if( pX->op==TK_ISNULL ){
89168     iReg = iTarget;
89169     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
89170 #ifndef SQLITE_OMIT_SUBQUERY
89171   }else{
89172     int eType;
89173     int iTab;
89174     struct InLoop *pIn;
89175
89176     assert( pX->op==TK_IN );
89177     iReg = iTarget;
89178     eType = sqlite3FindInIndex(pParse, pX, 0);
89179     iTab = pX->iTable;
89180     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
89181     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
89182     if( pLevel->u.in.nIn==0 ){
89183       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
89184     }
89185     pLevel->u.in.nIn++;
89186     pLevel->u.in.aInLoop =
89187        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
89188                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
89189     pIn = pLevel->u.in.aInLoop;
89190     if( pIn ){
89191       pIn += pLevel->u.in.nIn - 1;
89192       pIn->iCur = iTab;
89193       if( eType==IN_INDEX_ROWID ){
89194         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
89195       }else{
89196         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
89197       }
89198       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
89199     }else{
89200       pLevel->u.in.nIn = 0;
89201     }
89202 #endif
89203   }
89204   disableTerm(pLevel, pTerm);
89205   return iReg;
89206 }
89207
89208 /*
89209 ** Generate code that will evaluate all == and IN constraints for an
89210 ** index.
89211 **
89212 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
89213 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
89214 ** The index has as many as three equality constraints, but in this
89215 ** example, the third "c" value is an inequality.  So only two 
89216 ** constraints are coded.  This routine will generate code to evaluate
89217 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
89218 ** in consecutive registers and the index of the first register is returned.
89219 **
89220 ** In the example above nEq==2.  But this subroutine works for any value
89221 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
89222 ** The only thing it does is allocate the pLevel->iMem memory cell and
89223 ** compute the affinity string.
89224 **
89225 ** This routine always allocates at least one memory cell and returns
89226 ** the index of that memory cell. The code that
89227 ** calls this routine will use that memory cell to store the termination
89228 ** key value of the loop.  If one or more IN operators appear, then
89229 ** this routine allocates an additional nEq memory cells for internal
89230 ** use.
89231 **
89232 ** Before returning, *pzAff is set to point to a buffer containing a
89233 ** copy of the column affinity string of the index allocated using
89234 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
89235 ** with equality constraints that use NONE affinity are set to
89236 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
89237 **
89238 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
89239 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
89240 **
89241 ** In the example above, the index on t1(a) has TEXT affinity. But since
89242 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
89243 ** no conversion should be attempted before using a t2.b value as part of
89244 ** a key to search the index. Hence the first byte in the returned affinity
89245 ** string in this example would be set to SQLITE_AFF_NONE.
89246 */
89247 static int codeAllEqualityTerms(
89248   Parse *pParse,        /* Parsing context */
89249   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
89250   WhereClause *pWC,     /* The WHERE clause */
89251   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
89252   int nExtraReg,        /* Number of extra registers to allocate */
89253   char **pzAff          /* OUT: Set to point to affinity string */
89254 ){
89255   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
89256   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
89257   Index *pIdx;                  /* The index being used for this loop */
89258   int iCur = pLevel->iTabCur;   /* The cursor of the table */
89259   WhereTerm *pTerm;             /* A single constraint term */
89260   int j;                        /* Loop counter */
89261   int regBase;                  /* Base register */
89262   int nReg;                     /* Number of registers to allocate */
89263   char *zAff;                   /* Affinity string to return */
89264
89265   /* This module is only called on query plans that use an index. */
89266   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
89267   pIdx = pLevel->plan.u.pIdx;
89268
89269   /* Figure out how many memory cells we will need then allocate them.
89270   */
89271   regBase = pParse->nMem + 1;
89272   nReg = pLevel->plan.nEq + nExtraReg;
89273   pParse->nMem += nReg;
89274
89275   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
89276   if( !zAff ){
89277     pParse->db->mallocFailed = 1;
89278   }
89279
89280   /* Evaluate the equality constraints
89281   */
89282   assert( pIdx->nColumn>=nEq );
89283   for(j=0; j<nEq; j++){
89284     int r1;
89285     int k = pIdx->aiColumn[j];
89286     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
89287     if( NEVER(pTerm==0) ) break;
89288     assert( (pTerm->wtFlags & TERM_CODED)==0 );
89289     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
89290     if( r1!=regBase+j ){
89291       if( nReg==1 ){
89292         sqlite3ReleaseTempReg(pParse, regBase);
89293         regBase = r1;
89294       }else{
89295         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
89296       }
89297     }
89298     testcase( pTerm->eOperator & WO_ISNULL );
89299     testcase( pTerm->eOperator & WO_IN );
89300     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
89301       Expr *pRight = pTerm->pExpr->pRight;
89302       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
89303       if( zAff ){
89304         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
89305           zAff[j] = SQLITE_AFF_NONE;
89306         }
89307         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
89308           zAff[j] = SQLITE_AFF_NONE;
89309         }
89310       }
89311     }
89312   }
89313   *pzAff = zAff;
89314   return regBase;
89315 }
89316
89317 /*
89318 ** Generate code for the start of the iLevel-th loop in the WHERE clause
89319 ** implementation described by pWInfo.
89320 */
89321 static Bitmask codeOneLoopStart(
89322   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
89323   int iLevel,          /* Which level of pWInfo->a[] should be coded */
89324   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
89325   Bitmask notReady     /* Which tables are currently available */
89326 ){
89327   int j, k;            /* Loop counters */
89328   int iCur;            /* The VDBE cursor for the table */
89329   int addrNxt;         /* Where to jump to continue with the next IN case */
89330   int omitTable;       /* True if we use the index only */
89331   int bRev;            /* True if we need to scan in reverse order */
89332   WhereLevel *pLevel;  /* The where level to be coded */
89333   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
89334   WhereTerm *pTerm;               /* A WHERE clause term */
89335   Parse *pParse;                  /* Parsing context */
89336   Vdbe *v;                        /* The prepared stmt under constructions */
89337   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
89338   int addrBrk;                    /* Jump here to break out of the loop */
89339   int addrCont;                   /* Jump here to continue with next cycle */
89340   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
89341   int iReleaseReg = 0;      /* Temp register to free before returning */
89342
89343   pParse = pWInfo->pParse;
89344   v = pParse->pVdbe;
89345   pWC = pWInfo->pWC;
89346   pLevel = &pWInfo->a[iLevel];
89347   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
89348   iCur = pTabItem->iCursor;
89349   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
89350   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
89351            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
89352
89353   /* Create labels for the "break" and "continue" instructions
89354   ** for the current loop.  Jump to addrBrk to break out of a loop.
89355   ** Jump to cont to go immediately to the next iteration of the
89356   ** loop.
89357   **
89358   ** When there is an IN operator, we also have a "addrNxt" label that
89359   ** means to continue with the next IN value combination.  When
89360   ** there are no IN operators in the constraints, the "addrNxt" label
89361   ** is the same as "addrBrk".
89362   */
89363   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
89364   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
89365
89366   /* If this is the right table of a LEFT OUTER JOIN, allocate and
89367   ** initialize a memory cell that records if this table matches any
89368   ** row of the left table of the join.
89369   */
89370   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
89371     pLevel->iLeftJoin = ++pParse->nMem;
89372     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
89373     VdbeComment((v, "init LEFT JOIN no-match flag"));
89374   }
89375
89376 #ifndef SQLITE_OMIT_VIRTUALTABLE
89377   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
89378     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
89379     **          to access the data.
89380     */
89381     int iReg;   /* P3 Value for OP_VFilter */
89382     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
89383     int nConstraint = pVtabIdx->nConstraint;
89384     struct sqlite3_index_constraint_usage *aUsage =
89385                                                 pVtabIdx->aConstraintUsage;
89386     const struct sqlite3_index_constraint *aConstraint =
89387                                                 pVtabIdx->aConstraint;
89388
89389     sqlite3ExprCachePush(pParse);
89390     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
89391     for(j=1; j<=nConstraint; j++){
89392       for(k=0; k<nConstraint; k++){
89393         if( aUsage[k].argvIndex==j ){
89394           int iTerm = aConstraint[k].iTermOffset;
89395           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
89396           break;
89397         }
89398       }
89399       if( k==nConstraint ) break;
89400     }
89401     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
89402     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
89403     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
89404                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
89405     pVtabIdx->needToFreeIdxStr = 0;
89406     for(j=0; j<nConstraint; j++){
89407       if( aUsage[j].omit ){
89408         int iTerm = aConstraint[j].iTermOffset;
89409         disableTerm(pLevel, &pWC->a[iTerm]);
89410       }
89411     }
89412     pLevel->op = OP_VNext;
89413     pLevel->p1 = iCur;
89414     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
89415     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
89416     sqlite3ExprCachePop(pParse, 1);
89417   }else
89418 #endif /* SQLITE_OMIT_VIRTUALTABLE */
89419
89420   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
89421     /* Case 1:  We can directly reference a single row using an
89422     **          equality comparison against the ROWID field.  Or
89423     **          we reference multiple rows using a "rowid IN (...)"
89424     **          construct.
89425     */
89426     iReleaseReg = sqlite3GetTempReg(pParse);
89427     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
89428     assert( pTerm!=0 );
89429     assert( pTerm->pExpr!=0 );
89430     assert( pTerm->leftCursor==iCur );
89431     assert( omitTable==0 );
89432     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
89433     addrNxt = pLevel->addrNxt;
89434     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
89435     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
89436     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
89437     VdbeComment((v, "pk"));
89438     pLevel->op = OP_Noop;
89439   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
89440     /* Case 2:  We have an inequality comparison against the ROWID field.
89441     */
89442     int testOp = OP_Noop;
89443     int start;
89444     int memEndValue = 0;
89445     WhereTerm *pStart, *pEnd;
89446
89447     assert( omitTable==0 );
89448     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
89449     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
89450     if( bRev ){
89451       pTerm = pStart;
89452       pStart = pEnd;
89453       pEnd = pTerm;
89454     }
89455     if( pStart ){
89456       Expr *pX;             /* The expression that defines the start bound */
89457       int r1, rTemp;        /* Registers for holding the start boundary */
89458
89459       /* The following constant maps TK_xx codes into corresponding 
89460       ** seek opcodes.  It depends on a particular ordering of TK_xx
89461       */
89462       const u8 aMoveOp[] = {
89463            /* TK_GT */  OP_SeekGt,
89464            /* TK_LE */  OP_SeekLe,
89465            /* TK_LT */  OP_SeekLt,
89466            /* TK_GE */  OP_SeekGe
89467       };
89468       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
89469       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
89470       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
89471
89472       pX = pStart->pExpr;
89473       assert( pX!=0 );
89474       assert( pStart->leftCursor==iCur );
89475       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
89476       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
89477       VdbeComment((v, "pk"));
89478       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
89479       sqlite3ReleaseTempReg(pParse, rTemp);
89480       disableTerm(pLevel, pStart);
89481     }else{
89482       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
89483     }
89484     if( pEnd ){
89485       Expr *pX;
89486       pX = pEnd->pExpr;
89487       assert( pX!=0 );
89488       assert( pEnd->leftCursor==iCur );
89489       memEndValue = ++pParse->nMem;
89490       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
89491       if( pX->op==TK_LT || pX->op==TK_GT ){
89492         testOp = bRev ? OP_Le : OP_Ge;
89493       }else{
89494         testOp = bRev ? OP_Lt : OP_Gt;
89495       }
89496       disableTerm(pLevel, pEnd);
89497     }
89498     start = sqlite3VdbeCurrentAddr(v);
89499     pLevel->op = bRev ? OP_Prev : OP_Next;
89500     pLevel->p1 = iCur;
89501     pLevel->p2 = start;
89502     pLevel->p5 = (pStart==0 && pEnd==0) ?1:0;
89503     if( testOp!=OP_Noop ){
89504       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
89505       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
89506       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
89507       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
89508       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
89509     }
89510   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
89511     /* Case 3: A scan using an index.
89512     **
89513     **         The WHERE clause may contain zero or more equality 
89514     **         terms ("==" or "IN" operators) that refer to the N
89515     **         left-most columns of the index. It may also contain
89516     **         inequality constraints (>, <, >= or <=) on the indexed
89517     **         column that immediately follows the N equalities. Only 
89518     **         the right-most column can be an inequality - the rest must
89519     **         use the "==" and "IN" operators. For example, if the 
89520     **         index is on (x,y,z), then the following clauses are all 
89521     **         optimized:
89522     **
89523     **            x=5
89524     **            x=5 AND y=10
89525     **            x=5 AND y<10
89526     **            x=5 AND y>5 AND y<10
89527     **            x=5 AND y=5 AND z<=10
89528     **
89529     **         The z<10 term of the following cannot be used, only
89530     **         the x=5 term:
89531     **
89532     **            x=5 AND z<10
89533     **
89534     **         N may be zero if there are inequality constraints.
89535     **         If there are no inequality constraints, then N is at
89536     **         least one.
89537     **
89538     **         This case is also used when there are no WHERE clause
89539     **         constraints but an index is selected anyway, in order
89540     **         to force the output order to conform to an ORDER BY.
89541     */  
89542     int aStartOp[] = {
89543       0,
89544       0,
89545       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
89546       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
89547       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
89548       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
89549       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
89550       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
89551     };
89552     int aEndOp[] = {
89553       OP_Noop,             /* 0: (!end_constraints) */
89554       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
89555       OP_IdxLT             /* 2: (end_constraints && bRev) */
89556     };
89557     int nEq = pLevel->plan.nEq;
89558     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
89559     int regBase;                 /* Base register holding constraint values */
89560     int r1;                      /* Temp register */
89561     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
89562     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
89563     int startEq;                 /* True if range start uses ==, >= or <= */
89564     int endEq;                   /* True if range end uses ==, >= or <= */
89565     int start_constraints;       /* Start of range is constrained */
89566     int nConstraint;             /* Number of constraint terms */
89567     Index *pIdx;         /* The index we will be using */
89568     int iIdxCur;         /* The VDBE cursor for the index */
89569     int nExtraReg = 0;   /* Number of extra registers needed */
89570     int op;              /* Instruction opcode */
89571     char *zAff;
89572
89573     pIdx = pLevel->plan.u.pIdx;
89574     iIdxCur = pLevel->iIdxCur;
89575     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
89576
89577     /* If this loop satisfies a sort order (pOrderBy) request that 
89578     ** was passed to this function to implement a "SELECT min(x) ..." 
89579     ** query, then the caller will only allow the loop to run for
89580     ** a single iteration. This means that the first row returned
89581     ** should not have a NULL value stored in 'x'. If column 'x' is
89582     ** the first one after the nEq equality constraints in the index,
89583     ** this requires some special handling.
89584     */
89585     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
89586      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
89587      && (pIdx->nColumn>nEq)
89588     ){
89589       /* assert( pOrderBy->nExpr==1 ); */
89590       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
89591       isMinQuery = 1;
89592       nExtraReg = 1;
89593     }
89594
89595     /* Find any inequality constraint terms for the start and end 
89596     ** of the range. 
89597     */
89598     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
89599       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
89600       nExtraReg = 1;
89601     }
89602     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
89603       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
89604       nExtraReg = 1;
89605     }
89606
89607     /* Generate code to evaluate all constraint terms using == or IN
89608     ** and store the values of those terms in an array of registers
89609     ** starting at regBase.
89610     */
89611     regBase = codeAllEqualityTerms(
89612         pParse, pLevel, pWC, notReady, nExtraReg, &zAff
89613     );
89614     addrNxt = pLevel->addrNxt;
89615
89616     /* If we are doing a reverse order scan on an ascending index, or
89617     ** a forward order scan on a descending index, interchange the 
89618     ** start and end terms (pRangeStart and pRangeEnd).
89619     */
89620     if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
89621       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
89622     }
89623
89624     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
89625     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
89626     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
89627     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
89628     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
89629     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
89630     start_constraints = pRangeStart || nEq>0;
89631
89632     /* Seek the index cursor to the start of the range. */
89633     nConstraint = nEq;
89634     if( pRangeStart ){
89635       Expr *pRight = pRangeStart->pExpr->pRight;
89636       sqlite3ExprCode(pParse, pRight, regBase+nEq);
89637       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
89638       if( zAff ){
89639         if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
89640           /* Since the comparison is to be performed with no conversions
89641           ** applied to the operands, set the affinity to apply to pRight to 
89642           ** SQLITE_AFF_NONE.  */
89643           zAff[nConstraint] = SQLITE_AFF_NONE;
89644         }
89645         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
89646           zAff[nConstraint] = SQLITE_AFF_NONE;
89647         }
89648       }  
89649       nConstraint++;
89650     }else if( isMinQuery ){
89651       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
89652       nConstraint++;
89653       startEq = 0;
89654       start_constraints = 1;
89655     }
89656     codeApplyAffinity(pParse, regBase, nConstraint, zAff);
89657     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
89658     assert( op!=0 );
89659     testcase( op==OP_Rewind );
89660     testcase( op==OP_Last );
89661     testcase( op==OP_SeekGt );
89662     testcase( op==OP_SeekGe );
89663     testcase( op==OP_SeekLe );
89664     testcase( op==OP_SeekLt );
89665     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
89666
89667     /* Load the value for the inequality constraint at the end of the
89668     ** range (if any).
89669     */
89670     nConstraint = nEq;
89671     if( pRangeEnd ){
89672       Expr *pRight = pRangeEnd->pExpr->pRight;
89673       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
89674       sqlite3ExprCode(pParse, pRight, regBase+nEq);
89675       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
89676       if( zAff ){
89677         if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
89678           /* Since the comparison is to be performed with no conversions
89679           ** applied to the operands, set the affinity to apply to pRight to 
89680           ** SQLITE_AFF_NONE.  */
89681           zAff[nConstraint] = SQLITE_AFF_NONE;
89682         }
89683         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
89684           zAff[nConstraint] = SQLITE_AFF_NONE;
89685         }
89686       }  
89687       codeApplyAffinity(pParse, regBase, nEq+1, zAff);
89688       nConstraint++;
89689     }
89690     sqlite3DbFree(pParse->db, zAff);
89691
89692     /* Top of the loop body */
89693     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
89694
89695     /* Check if the index cursor is past the end of the range. */
89696     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
89697     testcase( op==OP_Noop );
89698     testcase( op==OP_IdxGE );
89699     testcase( op==OP_IdxLT );
89700     if( op!=OP_Noop ){
89701       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
89702       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
89703     }
89704
89705     /* If there are inequality constraints, check that the value
89706     ** of the table column that the inequality contrains is not NULL.
89707     ** If it is, jump to the next iteration of the loop.
89708     */
89709     r1 = sqlite3GetTempReg(pParse);
89710     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
89711     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
89712     if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
89713       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
89714       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
89715     }
89716     sqlite3ReleaseTempReg(pParse, r1);
89717
89718     /* Seek the table cursor, if required */
89719     disableTerm(pLevel, pRangeStart);
89720     disableTerm(pLevel, pRangeEnd);
89721     if( !omitTable ){
89722       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
89723       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
89724       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
89725       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
89726     }
89727
89728     /* Record the instruction used to terminate the loop. Disable 
89729     ** WHERE clause terms made redundant by the index range scan.
89730     */
89731     pLevel->op = bRev ? OP_Prev : OP_Next;
89732     pLevel->p1 = iIdxCur;
89733   }else
89734
89735 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
89736   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
89737     /* Case 4:  Two or more separately indexed terms connected by OR
89738     **
89739     ** Example:
89740     **
89741     **   CREATE TABLE t1(a,b,c,d);
89742     **   CREATE INDEX i1 ON t1(a);
89743     **   CREATE INDEX i2 ON t1(b);
89744     **   CREATE INDEX i3 ON t1(c);
89745     **
89746     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
89747     **
89748     ** In the example, there are three indexed terms connected by OR.
89749     ** The top of the loop looks like this:
89750     **
89751     **          Null       1                # Zero the rowset in reg 1
89752     **
89753     ** Then, for each indexed term, the following. The arguments to
89754     ** RowSetTest are such that the rowid of the current row is inserted
89755     ** into the RowSet. If it is already present, control skips the
89756     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
89757     **
89758     **        sqlite3WhereBegin(<term>)
89759     **          RowSetTest                  # Insert rowid into rowset
89760     **          Gosub      2 A
89761     **        sqlite3WhereEnd()
89762     **
89763     ** Following the above, code to terminate the loop. Label A, the target
89764     ** of the Gosub above, jumps to the instruction right after the Goto.
89765     **
89766     **          Null       1                # Zero the rowset in reg 1
89767     **          Goto       B                # The loop is finished.
89768     **
89769     **       A: <loop body>                 # Return data, whatever.
89770     **
89771     **          Return     2                # Jump back to the Gosub
89772     **
89773     **       B: <after the loop>
89774     **
89775     */
89776     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
89777     WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
89778     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
89779
89780     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
89781     int regRowset = 0;                        /* Register for RowSet object */
89782     int regRowid = 0;                         /* Register holding rowid */
89783     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
89784     int iRetInit;                             /* Address of regReturn init */
89785     int untestedTerms = 0;             /* Some terms not completely tested */
89786     int ii;
89787    
89788     pTerm = pLevel->plan.u.pTerm;
89789     assert( pTerm!=0 );
89790     assert( pTerm->eOperator==WO_OR );
89791     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
89792     pOrWc = &pTerm->u.pOrInfo->wc;
89793     pFinal = &pOrWc->a[pOrWc->nTerm-1];
89794     pLevel->op = OP_Return;
89795     pLevel->p1 = regReturn;
89796
89797     /* Set up a new SrcList ni pOrTab containing the table being scanned
89798     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
89799     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
89800     */
89801     if( pWInfo->nLevel>1 ){
89802       int nNotReady;                 /* The number of notReady tables */
89803       struct SrcList_item *origSrc;     /* Original list of tables */
89804       nNotReady = pWInfo->nLevel - iLevel - 1;
89805       pOrTab = sqlite3StackAllocRaw(pParse->db,
89806                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
89807       if( pOrTab==0 ) return notReady;
89808       pOrTab->nAlloc = (i16)(nNotReady + 1);
89809       pOrTab->nSrc = pOrTab->nAlloc;
89810       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
89811       origSrc = pWInfo->pTabList->a;
89812       for(k=1; k<=nNotReady; k++){
89813         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
89814       }
89815     }else{
89816       pOrTab = pWInfo->pTabList;
89817     }
89818
89819     /* Initialize the rowset register to contain NULL. An SQL NULL is 
89820     ** equivalent to an empty rowset.
89821     **
89822     ** Also initialize regReturn to contain the address of the instruction 
89823     ** immediately following the OP_Return at the bottom of the loop. This
89824     ** is required in a few obscure LEFT JOIN cases where control jumps
89825     ** over the top of the loop into the body of it. In this case the 
89826     ** correct response for the end-of-loop code (the OP_Return) is to 
89827     ** fall through to the next instruction, just as an OP_Next does if
89828     ** called on an uninitialized cursor.
89829     */
89830     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
89831       regRowset = ++pParse->nMem;
89832       regRowid = ++pParse->nMem;
89833       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
89834     }
89835     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
89836
89837     for(ii=0; ii<pOrWc->nTerm; ii++){
89838       WhereTerm *pOrTerm = &pOrWc->a[ii];
89839       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
89840         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
89841         /* Loop through table entries that match term pOrTerm. */
89842         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
89843                         WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
89844                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
89845         if( pSubWInfo ){
89846           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
89847             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
89848             int r;
89849             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
89850                                          regRowid);
89851             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
89852                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
89853           }
89854           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
89855
89856           /* The pSubWInfo->untestedTerms flag means that this OR term
89857           ** contained one or more AND term from a notReady table.  The
89858           ** terms from the notReady table could not be tested and will
89859           ** need to be tested later.
89860           */
89861           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
89862
89863           /* Finish the loop through table entries that match term pOrTerm. */
89864           sqlite3WhereEnd(pSubWInfo);
89865         }
89866       }
89867     }
89868     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
89869     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
89870     sqlite3VdbeResolveLabel(v, iLoopBody);
89871
89872     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
89873     if( !untestedTerms ) disableTerm(pLevel, pTerm);
89874   }else
89875 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
89876
89877   {
89878     /* Case 5:  There is no usable index.  We must do a complete
89879     **          scan of the entire table.
89880     */
89881     static const u8 aStep[] = { OP_Next, OP_Prev };
89882     static const u8 aStart[] = { OP_Rewind, OP_Last };
89883     assert( bRev==0 || bRev==1 );
89884     assert( omitTable==0 );
89885     pLevel->op = aStep[bRev];
89886     pLevel->p1 = iCur;
89887     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
89888     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
89889   }
89890   notReady &= ~getMask(pWC->pMaskSet, iCur);
89891
89892   /* Insert code to test every subexpression that can be completely
89893   ** computed using the current set of tables.
89894   */
89895   k = 0;
89896   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
89897     Expr *pE;
89898     testcase( pTerm->wtFlags & TERM_VIRTUAL );
89899     testcase( pTerm->wtFlags & TERM_CODED );
89900     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
89901     if( (pTerm->prereqAll & notReady)!=0 ){
89902       testcase( pWInfo->untestedTerms==0
89903                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
89904       pWInfo->untestedTerms = 1;
89905       continue;
89906     }
89907     pE = pTerm->pExpr;
89908     assert( pE!=0 );
89909     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
89910       continue;
89911     }
89912     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
89913     k = 1;
89914     pTerm->wtFlags |= TERM_CODED;
89915   }
89916
89917   /* For a LEFT OUTER JOIN, generate code that will record the fact that
89918   ** at least one row of the right table has matched the left table.  
89919   */
89920   if( pLevel->iLeftJoin ){
89921     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
89922     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
89923     VdbeComment((v, "record LEFT JOIN hit"));
89924     sqlite3ExprCacheClear(pParse);
89925     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
89926       testcase( pTerm->wtFlags & TERM_VIRTUAL );
89927       testcase( pTerm->wtFlags & TERM_CODED );
89928       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
89929       if( (pTerm->prereqAll & notReady)!=0 ){
89930         assert( pWInfo->untestedTerms );
89931         continue;
89932       }
89933       assert( pTerm->pExpr );
89934       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
89935       pTerm->wtFlags |= TERM_CODED;
89936     }
89937   }
89938   sqlite3ReleaseTempReg(pParse, iReleaseReg);
89939
89940   return notReady;
89941 }
89942
89943 #if defined(SQLITE_TEST)
89944 /*
89945 ** The following variable holds a text description of query plan generated
89946 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
89947 ** overwrites the previous.  This information is used for testing and
89948 ** analysis only.
89949 */
89950 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
89951 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
89952
89953 #endif /* SQLITE_TEST */
89954
89955
89956 /*
89957 ** Free a WhereInfo structure
89958 */
89959 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
89960   if( pWInfo ){
89961     int i;
89962     for(i=0; i<pWInfo->nLevel; i++){
89963       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
89964       if( pInfo ){
89965         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
89966         if( pInfo->needToFreeIdxStr ){
89967           sqlite3_free(pInfo->idxStr);
89968         }
89969         sqlite3DbFree(db, pInfo);
89970       }
89971     }
89972     whereClauseClear(pWInfo->pWC);
89973     sqlite3DbFree(db, pWInfo);
89974   }
89975 }
89976
89977
89978 /*
89979 ** Generate the beginning of the loop used for WHERE clause processing.
89980 ** The return value is a pointer to an opaque structure that contains
89981 ** information needed to terminate the loop.  Later, the calling routine
89982 ** should invoke sqlite3WhereEnd() with the return value of this function
89983 ** in order to complete the WHERE clause processing.
89984 **
89985 ** If an error occurs, this routine returns NULL.
89986 **
89987 ** The basic idea is to do a nested loop, one loop for each table in
89988 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
89989 ** same as a SELECT with only a single table in the FROM clause.)  For
89990 ** example, if the SQL is this:
89991 **
89992 **       SELECT * FROM t1, t2, t3 WHERE ...;
89993 **
89994 ** Then the code generated is conceptually like the following:
89995 **
89996 **      foreach row1 in t1 do       \    Code generated
89997 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
89998 **          foreach row3 in t3 do   /
89999 **            ...
90000 **          end                     \    Code generated
90001 **        end                        |-- by sqlite3WhereEnd()
90002 **      end                         /
90003 **
90004 ** Note that the loops might not be nested in the order in which they
90005 ** appear in the FROM clause if a different order is better able to make
90006 ** use of indices.  Note also that when the IN operator appears in
90007 ** the WHERE clause, it might result in additional nested loops for
90008 ** scanning through all values on the right-hand side of the IN.
90009 **
90010 ** There are Btree cursors associated with each table.  t1 uses cursor
90011 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
90012 ** And so forth.  This routine generates code to open those VDBE cursors
90013 ** and sqlite3WhereEnd() generates the code to close them.
90014 **
90015 ** The code that sqlite3WhereBegin() generates leaves the cursors named
90016 ** in pTabList pointing at their appropriate entries.  The [...] code
90017 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
90018 ** data from the various tables of the loop.
90019 **
90020 ** If the WHERE clause is empty, the foreach loops must each scan their
90021 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
90022 ** the tables have indices and there are terms in the WHERE clause that
90023 ** refer to those indices, a complete table scan can be avoided and the
90024 ** code will run much faster.  Most of the work of this routine is checking
90025 ** to see if there are indices that can be used to speed up the loop.
90026 **
90027 ** Terms of the WHERE clause are also used to limit which rows actually
90028 ** make it to the "..." in the middle of the loop.  After each "foreach",
90029 ** terms of the WHERE clause that use only terms in that loop and outer
90030 ** loops are evaluated and if false a jump is made around all subsequent
90031 ** inner loops (or around the "..." if the test occurs within the inner-
90032 ** most loop)
90033 **
90034 ** OUTER JOINS
90035 **
90036 ** An outer join of tables t1 and t2 is conceptally coded as follows:
90037 **
90038 **    foreach row1 in t1 do
90039 **      flag = 0
90040 **      foreach row2 in t2 do
90041 **        start:
90042 **          ...
90043 **          flag = 1
90044 **      end
90045 **      if flag==0 then
90046 **        move the row2 cursor to a null row
90047 **        goto start
90048 **      fi
90049 **    end
90050 **
90051 ** ORDER BY CLAUSE PROCESSING
90052 **
90053 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
90054 ** if there is one.  If there is no ORDER BY clause or if this routine
90055 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
90056 **
90057 ** If an index can be used so that the natural output order of the table
90058 ** scan is correct for the ORDER BY clause, then that index is used and
90059 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
90060 ** unnecessary sort of the result set if an index appropriate for the
90061 ** ORDER BY clause already exists.
90062 **
90063 ** If the where clause loops cannot be arranged to provide the correct
90064 ** output order, then the *ppOrderBy is unchanged.
90065 */
90066 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
90067   Parse *pParse,        /* The parser context */
90068   SrcList *pTabList,    /* A list of all tables to be scanned */
90069   Expr *pWhere,         /* The WHERE clause */
90070   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
90071   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
90072 ){
90073   int i;                     /* Loop counter */
90074   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
90075   int nTabList;              /* Number of elements in pTabList */
90076   WhereInfo *pWInfo;         /* Will become the return value of this function */
90077   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
90078   Bitmask notReady;          /* Cursors that are not yet positioned */
90079   WhereMaskSet *pMaskSet;    /* The expression mask set */
90080   WhereClause *pWC;               /* Decomposition of the WHERE clause */
90081   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
90082   WhereLevel *pLevel;             /* A single level in the pWInfo list */
90083   int iFrom;                      /* First unused FROM clause element */
90084   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
90085   sqlite3 *db;               /* Database connection */
90086
90087   /* The number of tables in the FROM clause is limited by the number of
90088   ** bits in a Bitmask 
90089   */
90090   if( pTabList->nSrc>BMS ){
90091     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
90092     return 0;
90093   }
90094
90095   /* This function normally generates a nested loop for all tables in 
90096   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
90097   ** only generate code for the first table in pTabList and assume that
90098   ** any cursors associated with subsequent tables are uninitialized.
90099   */
90100   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
90101
90102   /* Allocate and initialize the WhereInfo structure that will become the
90103   ** return value. A single allocation is used to store the WhereInfo
90104   ** struct, the contents of WhereInfo.a[], the WhereClause structure
90105   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
90106   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
90107   ** some architectures. Hence the ROUND8() below.
90108   */
90109   db = pParse->db;
90110   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
90111   pWInfo = sqlite3DbMallocZero(db, 
90112       nByteWInfo + 
90113       sizeof(WhereClause) +
90114       sizeof(WhereMaskSet)
90115   );
90116   if( db->mallocFailed ){
90117     goto whereBeginError;
90118   }
90119   pWInfo->nLevel = nTabList;
90120   pWInfo->pParse = pParse;
90121   pWInfo->pTabList = pTabList;
90122   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
90123   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
90124   pWInfo->wctrlFlags = wctrlFlags;
90125   pMaskSet = (WhereMaskSet*)&pWC[1];
90126
90127   /* Split the WHERE clause into separate subexpressions where each
90128   ** subexpression is separated by an AND operator.
90129   */
90130   initMaskSet(pMaskSet);
90131   whereClauseInit(pWC, pParse, pMaskSet);
90132   sqlite3ExprCodeConstants(pParse, pWhere);
90133   whereSplit(pWC, pWhere, TK_AND);
90134     
90135   /* Special case: a WHERE clause that is constant.  Evaluate the
90136   ** expression and either jump over all of the code or fall thru.
90137   */
90138   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
90139     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
90140     pWhere = 0;
90141   }
90142
90143   /* Assign a bit from the bitmask to every term in the FROM clause.
90144   **
90145   ** When assigning bitmask values to FROM clause cursors, it must be
90146   ** the case that if X is the bitmask for the N-th FROM clause term then
90147   ** the bitmask for all FROM clause terms to the left of the N-th term
90148   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
90149   ** its Expr.iRightJoinTable value to find the bitmask of the right table
90150   ** of the join.  Subtracting one from the right table bitmask gives a
90151   ** bitmask for all tables to the left of the join.  Knowing the bitmask
90152   ** for all tables to the left of a left join is important.  Ticket #3015.
90153   **
90154   ** Configure the WhereClause.vmask variable so that bits that correspond
90155   ** to virtual table cursors are set. This is used to selectively disable 
90156   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 
90157   ** with virtual tables.
90158   **
90159   ** Note that bitmasks are created for all pTabList->nSrc tables in
90160   ** pTabList, not just the first nTabList tables.  nTabList is normally
90161   ** equal to pTabList->nSrc but might be shortened to 1 if the
90162   ** WHERE_ONETABLE_ONLY flag is set.
90163   */
90164   assert( pWC->vmask==0 && pMaskSet->n==0 );
90165   for(i=0; i<pTabList->nSrc; i++){
90166     createMask(pMaskSet, pTabList->a[i].iCursor);
90167 #ifndef SQLITE_OMIT_VIRTUALTABLE
90168     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
90169       pWC->vmask |= ((Bitmask)1 << i);
90170     }
90171 #endif
90172   }
90173 #ifndef NDEBUG
90174   {
90175     Bitmask toTheLeft = 0;
90176     for(i=0; i<pTabList->nSrc; i++){
90177       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
90178       assert( (m-1)==toTheLeft );
90179       toTheLeft |= m;
90180     }
90181   }
90182 #endif
90183
90184   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
90185   ** add new virtual terms onto the end of the WHERE clause.  We do not
90186   ** want to analyze these virtual terms, so start analyzing at the end
90187   ** and work forward so that the added virtual terms are never processed.
90188   */
90189   exprAnalyzeAll(pTabList, pWC);
90190   if( db->mallocFailed ){
90191     goto whereBeginError;
90192   }
90193
90194   /* Chose the best index to use for each table in the FROM clause.
90195   **
90196   ** This loop fills in the following fields:
90197   **
90198   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
90199   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
90200   **   pWInfo->a[].nEq       The number of == and IN constraints
90201   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
90202   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
90203   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
90204   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
90205   **
90206   ** This loop also figures out the nesting order of tables in the FROM
90207   ** clause.
90208   */
90209   notReady = ~(Bitmask)0;
90210   pTabItem = pTabList->a;
90211   pLevel = pWInfo->a;
90212   andFlags = ~0;
90213   WHERETRACE(("*** Optimizer Start ***\n"));
90214   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
90215     WhereCost bestPlan;         /* Most efficient plan seen so far */
90216     Index *pIdx;                /* Index for FROM table at pTabItem */
90217     int j;                      /* For looping over FROM tables */
90218     int bestJ = -1;             /* The value of j */
90219     Bitmask m;                  /* Bitmask value for j or bestJ */
90220     int isOptimal;              /* Iterator for optimal/non-optimal search */
90221
90222     memset(&bestPlan, 0, sizeof(bestPlan));
90223     bestPlan.rCost = SQLITE_BIG_DBL;
90224
90225     /* Loop through the remaining entries in the FROM clause to find the
90226     ** next nested loop. The FROM clause entries may be iterated through
90227     ** either once or twice. 
90228     **
90229     ** The first iteration, which is always performed, searches for the
90230     ** FROM clause entry that permits the lowest-cost, "optimal" scan. In
90231     ** this context an optimal scan is one that uses the same strategy
90232     ** for the given FROM clause entry as would be selected if the entry
90233     ** were used as the innermost nested loop.  In other words, a table
90234     ** is chosen such that the cost of running that table cannot be reduced
90235     ** by waiting for other tables to run first.
90236     **
90237     ** The second iteration is only performed if no optimal scan strategies
90238     ** were found by the first. This iteration is used to search for the
90239     ** lowest cost scan overall.
90240     **
90241     ** Previous versions of SQLite performed only the second iteration -
90242     ** the next outermost loop was always that with the lowest overall
90243     ** cost. However, this meant that SQLite could select the wrong plan
90244     ** for scripts such as the following:
90245     **   
90246     **   CREATE TABLE t1(a, b); 
90247     **   CREATE TABLE t2(c, d);
90248     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
90249     **
90250     ** The best strategy is to iterate through table t1 first. However it
90251     ** is not possible to determine this with a simple greedy algorithm.
90252     ** However, since the cost of a linear scan through table t2 is the same 
90253     ** as the cost of a linear scan through table t1, a simple greedy 
90254     ** algorithm may choose to use t2 for the outer loop, which is a much
90255     ** costlier approach.
90256     */
90257     for(isOptimal=1; isOptimal>=0 && bestJ<0; isOptimal--){
90258       Bitmask mask = (isOptimal ? 0 : notReady);
90259       assert( (nTabList-iFrom)>1 || isOptimal );
90260       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
90261         int doNotReorder;    /* True if this table should not be reordered */
90262         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
90263         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
90264   
90265         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
90266         if( j!=iFrom && doNotReorder ) break;
90267         m = getMask(pMaskSet, pTabItem->iCursor);
90268         if( (m & notReady)==0 ){
90269           if( j==iFrom ) iFrom++;
90270           continue;
90271         }
90272         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
90273   
90274         assert( pTabItem->pTab );
90275 #ifndef SQLITE_OMIT_VIRTUALTABLE
90276         if( IsVirtual(pTabItem->pTab) ){
90277           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
90278           bestVirtualIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost, pp);
90279         }else 
90280 #endif
90281         {
90282           bestBtreeIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost);
90283         }
90284         assert( isOptimal || (sCost.used&notReady)==0 );
90285
90286         if( (sCost.used&notReady)==0
90287          && (j==iFrom || sCost.rCost<bestPlan.rCost) 
90288         ){
90289           bestPlan = sCost;
90290           bestJ = j;
90291         }
90292         if( doNotReorder ) break;
90293       }
90294     }
90295     assert( bestJ>=0 );
90296     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
90297     WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
90298            pLevel-pWInfo->a));
90299     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
90300       *ppOrderBy = 0;
90301     }
90302     andFlags &= bestPlan.plan.wsFlags;
90303     pLevel->plan = bestPlan.plan;
90304     if( bestPlan.plan.wsFlags & WHERE_INDEXED ){
90305       pLevel->iIdxCur = pParse->nTab++;
90306     }else{
90307       pLevel->iIdxCur = -1;
90308     }
90309     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
90310     pLevel->iFrom = (u8)bestJ;
90311
90312     /* Check that if the table scanned by this loop iteration had an
90313     ** INDEXED BY clause attached to it, that the named index is being
90314     ** used for the scan. If not, then query compilation has failed.
90315     ** Return an error.
90316     */
90317     pIdx = pTabList->a[bestJ].pIndex;
90318     if( pIdx ){
90319       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
90320         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
90321         goto whereBeginError;
90322       }else{
90323         /* If an INDEXED BY clause is used, the bestIndex() function is
90324         ** guaranteed to find the index specified in the INDEXED BY clause
90325         ** if it find an index at all. */
90326         assert( bestPlan.plan.u.pIdx==pIdx );
90327       }
90328     }
90329   }
90330   WHERETRACE(("*** Optimizer Finished ***\n"));
90331   if( pParse->nErr || db->mallocFailed ){
90332     goto whereBeginError;
90333   }
90334
90335   /* If the total query only selects a single row, then the ORDER BY
90336   ** clause is irrelevant.
90337   */
90338   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
90339     *ppOrderBy = 0;
90340   }
90341
90342   /* If the caller is an UPDATE or DELETE statement that is requesting
90343   ** to use a one-pass algorithm, determine if this is appropriate.
90344   ** The one-pass algorithm only works if the WHERE clause constraints
90345   ** the statement to update a single row.
90346   */
90347   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
90348   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
90349     pWInfo->okOnePass = 1;
90350     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
90351   }
90352
90353   /* Open all tables in the pTabList and any indices selected for
90354   ** searching those tables.
90355   */
90356   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
90357   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
90358     Table *pTab;     /* Table to open */
90359     int iDb;         /* Index of database containing table/index */
90360
90361 #ifndef SQLITE_OMIT_EXPLAIN
90362     if( pParse->explain==2 ){
90363       char *zMsg;
90364       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
90365       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
90366       if( pItem->zAlias ){
90367         zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
90368       }
90369       if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90370         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
90371            zMsg, pLevel->plan.u.pIdx->zName);
90372       }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
90373         zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
90374       }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
90375         zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
90376       }
90377 #ifndef SQLITE_OMIT_VIRTUALTABLE
90378       else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
90379         sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
90380         zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
90381                     pVtabIdx->idxNum, pVtabIdx->idxStr);
90382       }
90383 #endif
90384       if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
90385         zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
90386       }
90387       sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
90388     }
90389 #endif /* SQLITE_OMIT_EXPLAIN */
90390     pTabItem = &pTabList->a[pLevel->iFrom];
90391     pTab = pTabItem->pTab;
90392     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
90393     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
90394 #ifndef SQLITE_OMIT_VIRTUALTABLE
90395     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
90396       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
90397       int iCur = pTabItem->iCursor;
90398       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
90399     }else
90400 #endif
90401     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
90402          && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
90403       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
90404       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
90405       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
90406         Bitmask b = pTabItem->colUsed;
90407         int n = 0;
90408         for(; b; b=b>>1, n++){}
90409         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
90410                             SQLITE_INT_TO_PTR(n), P4_INT32);
90411         assert( n<=pTab->nCol );
90412       }
90413     }else{
90414       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
90415     }
90416     pLevel->iTabCur = pTabItem->iCursor;
90417     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90418       Index *pIx = pLevel->plan.u.pIdx;
90419       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
90420       int iIdxCur = pLevel->iIdxCur;
90421       assert( pIx->pSchema==pTab->pSchema );
90422       assert( iIdxCur>=0 );
90423       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
90424                         (char*)pKey, P4_KEYINFO_HANDOFF);
90425       VdbeComment((v, "%s", pIx->zName));
90426     }
90427     sqlite3CodeVerifySchema(pParse, iDb);
90428   }
90429   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
90430
90431   /* Generate the code to do the search.  Each iteration of the for
90432   ** loop below generates code for a single nested loop of the VM
90433   ** program.
90434   */
90435   notReady = ~(Bitmask)0;
90436   for(i=0; i<nTabList; i++){
90437     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
90438     pWInfo->iContinue = pWInfo->a[i].addrCont;
90439   }
90440
90441 #ifdef SQLITE_TEST  /* For testing and debugging use only */
90442   /* Record in the query plan information about the current table
90443   ** and the index used to access it (if any).  If the table itself
90444   ** is not used, its name is just '{}'.  If no index is used
90445   ** the index is listed as "{}".  If the primary key is used the
90446   ** index name is '*'.
90447   */
90448   for(i=0; i<nTabList; i++){
90449     char *z;
90450     int n;
90451     pLevel = &pWInfo->a[i];
90452     pTabItem = &pTabList->a[pLevel->iFrom];
90453     z = pTabItem->zAlias;
90454     if( z==0 ) z = pTabItem->pTab->zName;
90455     n = sqlite3Strlen30(z);
90456     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
90457       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
90458         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
90459         nQPlan += 2;
90460       }else{
90461         memcpy(&sqlite3_query_plan[nQPlan], z, n);
90462         nQPlan += n;
90463       }
90464       sqlite3_query_plan[nQPlan++] = ' ';
90465     }
90466     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
90467     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
90468     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
90469       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
90470       nQPlan += 2;
90471     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90472       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
90473       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
90474         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
90475         nQPlan += n;
90476         sqlite3_query_plan[nQPlan++] = ' ';
90477       }
90478     }else{
90479       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
90480       nQPlan += 3;
90481     }
90482   }
90483   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
90484     sqlite3_query_plan[--nQPlan] = 0;
90485   }
90486   sqlite3_query_plan[nQPlan] = 0;
90487   nQPlan = 0;
90488 #endif /* SQLITE_TEST // Testing and debugging use only */
90489
90490   /* Record the continuation address in the WhereInfo structure.  Then
90491   ** clean up and return.
90492   */
90493   return pWInfo;
90494
90495   /* Jump here if malloc fails */
90496 whereBeginError:
90497   whereInfoFree(db, pWInfo);
90498   return 0;
90499 }
90500
90501 /*
90502 ** Generate the end of the WHERE loop.  See comments on 
90503 ** sqlite3WhereBegin() for additional information.
90504 */
90505 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
90506   Parse *pParse = pWInfo->pParse;
90507   Vdbe *v = pParse->pVdbe;
90508   int i;
90509   WhereLevel *pLevel;
90510   SrcList *pTabList = pWInfo->pTabList;
90511   sqlite3 *db = pParse->db;
90512
90513   /* Generate loop termination code.
90514   */
90515   sqlite3ExprCacheClear(pParse);
90516   for(i=pWInfo->nLevel-1; i>=0; i--){
90517     pLevel = &pWInfo->a[i];
90518     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
90519     if( pLevel->op!=OP_Noop ){
90520       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
90521       sqlite3VdbeChangeP5(v, pLevel->p5);
90522     }
90523     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
90524       struct InLoop *pIn;
90525       int j;
90526       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
90527       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
90528         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
90529         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
90530         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
90531       }
90532       sqlite3DbFree(db, pLevel->u.in.aInLoop);
90533     }
90534     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
90535     if( pLevel->iLeftJoin ){
90536       int addr;
90537       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
90538       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
90539            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
90540       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
90541         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
90542       }
90543       if( pLevel->iIdxCur>=0 ){
90544         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
90545       }
90546       if( pLevel->op==OP_Return ){
90547         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
90548       }else{
90549         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
90550       }
90551       sqlite3VdbeJumpHere(v, addr);
90552     }
90553   }
90554
90555   /* The "break" point is here, just past the end of the outer loop.
90556   ** Set it.
90557   */
90558   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
90559
90560   /* Close all of the cursors that were opened by sqlite3WhereBegin.
90561   */
90562   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
90563   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
90564     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
90565     Table *pTab = pTabItem->pTab;
90566     assert( pTab!=0 );
90567     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
90568     if( (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0 ){
90569       if( !pWInfo->okOnePass && (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
90570         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
90571       }
90572       if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90573         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
90574       }
90575     }
90576
90577     /* If this scan uses an index, make code substitutions to read data
90578     ** from the index in preference to the table. Sometimes, this means
90579     ** the table need never be read from. This is a performance boost,
90580     ** as the vdbe level waits until the table is read before actually
90581     ** seeking the table cursor to the record corresponding to the current
90582     ** position in the index.
90583     ** 
90584     ** Calls to the code generator in between sqlite3WhereBegin and
90585     ** sqlite3WhereEnd will have created code that references the table
90586     ** directly.  This loop scans all that code looking for opcodes
90587     ** that reference the table and converts them into opcodes that
90588     ** reference the index.
90589     */
90590     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
90591       int k, j, last;
90592       VdbeOp *pOp;
90593       Index *pIdx = pLevel->plan.u.pIdx;
90594
90595       assert( pIdx!=0 );
90596       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
90597       last = sqlite3VdbeCurrentAddr(v);
90598       for(k=pWInfo->iTop; k<last; k++, pOp++){
90599         if( pOp->p1!=pLevel->iTabCur ) continue;
90600         if( pOp->opcode==OP_Column ){
90601           for(j=0; j<pIdx->nColumn; j++){
90602             if( pOp->p2==pIdx->aiColumn[j] ){
90603               pOp->p2 = j;
90604               pOp->p1 = pLevel->iIdxCur;
90605               break;
90606             }
90607           }
90608           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
90609                || j<pIdx->nColumn );
90610         }else if( pOp->opcode==OP_Rowid ){
90611           pOp->p1 = pLevel->iIdxCur;
90612           pOp->opcode = OP_IdxRowid;
90613         }
90614       }
90615     }
90616   }
90617
90618   /* Final cleanup
90619   */
90620   whereInfoFree(db, pWInfo);
90621   return;
90622 }
90623
90624 /************** End of where.c ***********************************************/
90625 /************** Begin file parse.c *******************************************/
90626 /* Driver template for the LEMON parser generator.
90627 ** The author disclaims copyright to this source code.
90628 **
90629 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
90630 ** The only modifications are the addition of a couple of NEVER()
90631 ** macros to disable tests that are needed in the case of a general
90632 ** LALR(1) grammar but which are always false in the
90633 ** specific grammar used by SQLite.
90634 */
90635 /* First off, code is included that follows the "include" declaration
90636 ** in the input grammar file. */
90637
90638
90639 /*
90640 ** Disable all error recovery processing in the parser push-down
90641 ** automaton.
90642 */
90643 #define YYNOERRORRECOVERY 1
90644
90645 /*
90646 ** Make yytestcase() the same as testcase()
90647 */
90648 #define yytestcase(X) testcase(X)
90649
90650 /*
90651 ** An instance of this structure holds information about the
90652 ** LIMIT clause of a SELECT statement.
90653 */
90654 struct LimitVal {
90655   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
90656   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
90657 };
90658
90659 /*
90660 ** An instance of this structure is used to store the LIKE,
90661 ** GLOB, NOT LIKE, and NOT GLOB operators.
90662 */
90663 struct LikeOp {
90664   Token eOperator;  /* "like" or "glob" or "regexp" */
90665   int not;         /* True if the NOT keyword is present */
90666 };
90667
90668 /*
90669 ** An instance of the following structure describes the event of a
90670 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
90671 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
90672 **
90673 **      UPDATE ON (a,b,c)
90674 **
90675 ** Then the "b" IdList records the list "a,b,c".
90676 */
90677 struct TrigEvent { int a; IdList * b; };
90678
90679 /*
90680 ** An instance of this structure holds the ATTACH key and the key type.
90681 */
90682 struct AttachKey { int type;  Token key; };
90683
90684
90685   /* This is a utility routine used to set the ExprSpan.zStart and
90686   ** ExprSpan.zEnd values of pOut so that the span covers the complete
90687   ** range of text beginning with pStart and going to the end of pEnd.
90688   */
90689   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
90690     pOut->zStart = pStart->z;
90691     pOut->zEnd = &pEnd->z[pEnd->n];
90692   }
90693
90694   /* Construct a new Expr object from a single identifier.  Use the
90695   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
90696   ** that created the expression.
90697   */
90698   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
90699     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
90700     pOut->zStart = pValue->z;
90701     pOut->zEnd = &pValue->z[pValue->n];
90702   }
90703
90704   /* This routine constructs a binary expression node out of two ExprSpan
90705   ** objects and uses the result to populate a new ExprSpan object.
90706   */
90707   static void spanBinaryExpr(
90708     ExprSpan *pOut,     /* Write the result here */
90709     Parse *pParse,      /* The parsing context.  Errors accumulate here */
90710     int op,             /* The binary operation */
90711     ExprSpan *pLeft,    /* The left operand */
90712     ExprSpan *pRight    /* The right operand */
90713   ){
90714     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
90715     pOut->zStart = pLeft->zStart;
90716     pOut->zEnd = pRight->zEnd;
90717   }
90718
90719   /* Construct an expression node for a unary postfix operator
90720   */
90721   static void spanUnaryPostfix(
90722     ExprSpan *pOut,        /* Write the new expression node here */
90723     Parse *pParse,         /* Parsing context to record errors */
90724     int op,                /* The operator */
90725     ExprSpan *pOperand,    /* The operand */
90726     Token *pPostOp         /* The operand token for setting the span */
90727   ){
90728     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
90729     pOut->zStart = pOperand->zStart;
90730     pOut->zEnd = &pPostOp->z[pPostOp->n];
90731   }                           
90732
90733   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
90734   ** unary TK_ISNULL or TK_NOTNULL expression. */
90735   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
90736     sqlite3 *db = pParse->db;
90737     if( db->mallocFailed==0 && pY->op==TK_NULL ){
90738       pA->op = (u8)op;
90739       sqlite3ExprDelete(db, pA->pRight);
90740       pA->pRight = 0;
90741     }
90742   }
90743
90744   /* Construct an expression node for a unary prefix operator
90745   */
90746   static void spanUnaryPrefix(
90747     ExprSpan *pOut,        /* Write the new expression node here */
90748     Parse *pParse,         /* Parsing context to record errors */
90749     int op,                /* The operator */
90750     ExprSpan *pOperand,    /* The operand */
90751     Token *pPreOp         /* The operand token for setting the span */
90752   ){
90753     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
90754     pOut->zStart = pPreOp->z;
90755     pOut->zEnd = pOperand->zEnd;
90756   }
90757 /* Next is all token values, in a form suitable for use by makeheaders.
90758 ** This section will be null unless lemon is run with the -m switch.
90759 */
90760 /* 
90761 ** These constants (all generated automatically by the parser generator)
90762 ** specify the various kinds of tokens (terminals) that the parser
90763 ** understands. 
90764 **
90765 ** Each symbol here is a terminal symbol in the grammar.
90766 */
90767 /* Make sure the INTERFACE macro is defined.
90768 */
90769 #ifndef INTERFACE
90770 # define INTERFACE 1
90771 #endif
90772 /* The next thing included is series of defines which control
90773 ** various aspects of the generated parser.
90774 **    YYCODETYPE         is the data type used for storing terminal
90775 **                       and nonterminal numbers.  "unsigned char" is
90776 **                       used if there are fewer than 250 terminals
90777 **                       and nonterminals.  "int" is used otherwise.
90778 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
90779 **                       to no legal terminal or nonterminal number.  This
90780 **                       number is used to fill in empty slots of the hash 
90781 **                       table.
90782 **    YYFALLBACK         If defined, this indicates that one or more tokens
90783 **                       have fall-back values which should be used if the
90784 **                       original value of the token will not parse.
90785 **    YYACTIONTYPE       is the data type used for storing terminal
90786 **                       and nonterminal numbers.  "unsigned char" is
90787 **                       used if there are fewer than 250 rules and
90788 **                       states combined.  "int" is used otherwise.
90789 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
90790 **                       directly to the parser from the tokenizer.
90791 **    YYMINORTYPE        is the data type used for all minor tokens.
90792 **                       This is typically a union of many types, one of
90793 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
90794 **                       for base tokens is called "yy0".
90795 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
90796 **                       zero the stack is dynamically sized using realloc()
90797 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
90798 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
90799 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
90800 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
90801 **    YYNSTATE           the combined number of states.
90802 **    YYNRULE            the number of rules in the grammar
90803 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
90804 **                       defined, then do no error processing.
90805 */
90806 #define YYCODETYPE unsigned char
90807 #define YYNOCODE 254
90808 #define YYACTIONTYPE unsigned short int
90809 #define YYWILDCARD 67
90810 #define sqlite3ParserTOKENTYPE Token
90811 typedef union {
90812   int yyinit;
90813   sqlite3ParserTOKENTYPE yy0;
90814   Select* yy3;
90815   ExprList* yy14;
90816   SrcList* yy65;
90817   struct LikeOp yy96;
90818   Expr* yy132;
90819   u8 yy186;
90820   int yy328;
90821   ExprSpan yy346;
90822   struct TrigEvent yy378;
90823   IdList* yy408;
90824   struct {int value; int mask;} yy429;
90825   TriggerStep* yy473;
90826   struct LimitVal yy476;
90827 } YYMINORTYPE;
90828 #ifndef YYSTACKDEPTH
90829 #define YYSTACKDEPTH 100
90830 #endif
90831 #define sqlite3ParserARG_SDECL Parse *pParse;
90832 #define sqlite3ParserARG_PDECL ,Parse *pParse
90833 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
90834 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
90835 #define YYNSTATE 631
90836 #define YYNRULE 330
90837 #define YYFALLBACK 1
90838 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
90839 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
90840 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
90841
90842 /* The yyzerominor constant is used to initialize instances of
90843 ** YYMINORTYPE objects to zero. */
90844 static const YYMINORTYPE yyzerominor = { 0 };
90845
90846 /* Define the yytestcase() macro to be a no-op if is not already defined
90847 ** otherwise.
90848 **
90849 ** Applications can choose to define yytestcase() in the %include section
90850 ** to a macro that can assist in verifying code coverage.  For production
90851 ** code the yytestcase() macro should be turned off.  But it is useful
90852 ** for testing.
90853 */
90854 #ifndef yytestcase
90855 # define yytestcase(X)
90856 #endif
90857
90858
90859 /* Next are the tables used to determine what action to take based on the
90860 ** current state and lookahead token.  These tables are used to implement
90861 ** functions that take a state number and lookahead value and return an
90862 ** action integer.  
90863 **
90864 ** Suppose the action integer is N.  Then the action is determined as
90865 ** follows
90866 **
90867 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
90868 **                                      token onto the stack and goto state N.
90869 **
90870 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
90871 **
90872 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
90873 **
90874 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
90875 **
90876 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
90877 **                                      slots in the yy_action[] table.
90878 **
90879 ** The action table is constructed as a single large table named yy_action[].
90880 ** Given state S and lookahead X, the action is computed as
90881 **
90882 **      yy_action[ yy_shift_ofst[S] + X ]
90883 **
90884 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
90885 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
90886 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
90887 ** and that yy_default[S] should be used instead.  
90888 **
90889 ** The formula above is for computing the action when the lookahead is
90890 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
90891 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
90892 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
90893 ** YY_SHIFT_USE_DFLT.
90894 **
90895 ** The following are the tables generated in this section:
90896 **
90897 **  yy_action[]        A single table containing all actions.
90898 **  yy_lookahead[]     A table containing the lookahead for each entry in
90899 **                     yy_action.  Used to detect hash collisions.
90900 **  yy_shift_ofst[]    For each state, the offset into yy_action for
90901 **                     shifting terminals.
90902 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
90903 **                     shifting non-terminals after a reduce.
90904 **  yy_default[]       Default action for each state.
90905 */
90906 #define YY_ACTTAB_COUNT (1543)
90907 static const YYACTIONTYPE yy_action[] = {
90908  /*     0 */   313,   49,  556,   46,  147,  172,  628,  598,   55,   55,
90909  /*    10 */    55,   55,  302,   53,   53,   53,   53,   52,   52,   51,
90910  /*    20 */    51,   51,   50,  238,  603,   66,  624,  623,  604,  598,
90911  /*    30 */   591,  585,   48,   53,   53,   53,   53,   52,   52,   51,
90912  /*    40 */    51,   51,   50,  238,   51,   51,   51,   50,  238,   56,
90913  /*    50 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
90914  /*    60 */    55,   55,  609,   53,   53,   53,   53,   52,   52,   51,
90915  /*    70 */    51,   51,   50,  238,  313,  598,  672,  330,  411,  217,
90916  /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
90917  /*    90 */    50,  238,  330,  414,  621,  620,  166,  598,  673,  382,
90918  /*   100 */   379,  378,  602,   73,  591,  585,  307,  424,  166,   58,
90919  /*   110 */   377,  382,  379,  378,  516,  515,  624,  623,  254,  200,
90920  /*   120 */   199,  198,  377,   56,   57,   47,  583,  582,  584,  584,
90921  /*   130 */    54,   54,   55,   55,   55,   55,  581,   53,   53,   53,
90922  /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  270,
90923  /*   150 */   226,  422,  283,  133,  177,  139,  284,  385,  279,  384,
90924  /*   160 */   169,  197,  251,  282,  253,  226,  411,  275,  440,  167,
90925  /*   170 */   139,  284,  385,  279,  384,  169,  571,  236,  591,  585,
90926  /*   180 */   240,  414,  275,  622,  621,  620,  674,  437,  441,  442,
90927  /*   190 */   602,   88,  352,  266,  439,  268,  438,   56,   57,   47,
90928  /*   200 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
90929  /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
90930  /*   220 */    50,  238,  313,  471,   52,   52,   51,   51,   51,   50,
90931  /*   230 */   238,  234,  166,  491,  567,  382,  379,  378,    1,  440,
90932  /*   240 */   252,  176,  624,  623,  608,   67,  377,  513,  622,  443,
90933  /*   250 */   237,  577,  591,  585,  622,  172,  466,  598,  554,  441,
90934  /*   260 */   340,  409,  526,  580,  580,  349,  596,  553,  194,  482,
90935  /*   270 */   175,   56,   57,   47,  583,  582,  584,  584,   54,   54,
90936  /*   280 */    55,   55,   55,   55,  562,   53,   53,   53,   53,   52,
90937  /*   290 */    52,   51,   51,   51,   50,  238,  313,  594,  594,  594,
90938  /*   300 */   561,  578,  469,   65,  259,  351,  258,  411,  624,  623,
90939  /*   310 */   621,  620,  332,  576,  575,  240,  560,  568,  520,  411,
90940  /*   320 */   341,  237,  414,  624,  623,  598,  591,  585,  542,  519,
90941  /*   330 */   171,  602,   95,   68,  414,  624,  623,  624,  623,   38,
90942  /*   340 */   877,  506,  507,  602,   88,   56,   57,   47,  583,  582,
90943  /*   350 */   584,  584,   54,   54,   55,   55,   55,   55,  532,   53,
90944  /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
90945  /*   370 */   313,  411,  579,  398,  531,  237,  621,  620,  388,  625,
90946  /*   380 */   500,  206,  167,  396,  233,  312,  414,  387,  569,  492,
90947  /*   390 */   216,  621,  620,  566,  622,  602,   74,  533,  210,  491,
90948  /*   400 */   591,  585,  548,  621,  620,  621,  620,  300,  598,  466,
90949  /*   410 */   481,   67,  603,   35,  622,  601,  604,  547,    6,   56,
90950  /*   420 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
90951  /*   430 */    55,   55,  601,   53,   53,   53,   53,   52,   52,   51,
90952  /*   440 */    51,   51,   50,  238,  313,  411,  184,  409,  528,  580,
90953  /*   450 */   580,  551,  962,  186,  419,    2,  353,  259,  351,  258,
90954  /*   460 */   414,  409,  411,  580,  580,   44,  411,  544,  240,  602,
90955  /*   470 */    94,  190,    7,   62,  591,  585,  598,  414,  350,  607,
90956  /*   480 */   493,  414,  409,  317,  580,  580,  602,   95,  496,  565,
90957  /*   490 */   602,   80,  203,   56,   57,   47,  583,  582,  584,  584,
90958  /*   500 */    54,   54,   55,   55,   55,   55,  535,   53,   53,   53,
90959  /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  202,
90960  /*   520 */   564,  293,  511,   49,  562,   46,  147,  411,  394,  183,
90961  /*   530 */   563,  549,  505,  549,  174,  409,  322,  580,  580,   39,
90962  /*   540 */   561,   37,  414,  624,  623,  192,  473,  383,  591,  585,
90963  /*   550 */   474,  602,   80,  601,  504,  544,  560,  364,  402,  210,
90964  /*   560 */   421,  952,  361,  952,  365,  201,  144,   56,   57,   47,
90965  /*   570 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
90966  /*   580 */   559,   53,   53,   53,   53,   52,   52,   51,   51,   51,
90967  /*   590 */    50,  238,  313,  601,  232,  264,  272,  321,  374,  484,
90968  /*   600 */   510,  146,  342,  146,  328,  425,  485,  407,  576,  575,
90969  /*   610 */   622,  621,  620,   49,  168,   46,  147,  353,  546,  491,
90970  /*   620 */   204,  240,  591,  585,  421,  951,  549,  951,  549,  168,
90971  /*   630 */   429,   67,  390,  343,  622,  434,  307,  423,  338,  360,
90972  /*   640 */   391,   56,   57,   47,  583,  582,  584,  584,   54,   54,
90973  /*   650 */    55,   55,   55,   55,  601,   53,   53,   53,   53,   52,
90974  /*   660 */    52,   51,   51,   51,   50,  238,  313,   34,  318,  425,
90975  /*   670 */   237,   21,  359,  273,  411,  167,  411,  276,  411,  540,
90976  /*   680 */   411,  422,   13,  318,  619,  618,  617,  622,  275,  414,
90977  /*   690 */   336,  414,  622,  414,  622,  414,  591,  585,  602,   69,
90978  /*   700 */   602,   97,  602,  100,  602,   98,  631,  629,  334,  475,
90979  /*   710 */   475,  367,  319,  148,  327,   56,   57,   47,  583,  582,
90980  /*   720 */   584,  584,   54,   54,   55,   55,   55,   55,  411,   53,
90981  /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
90982  /*   740 */   313,  411,  331,  414,  411,   49,  276,   46,  147,  569,
90983  /*   750 */   406,  216,  602,  106,  573,  573,  414,  354,  524,  414,
90984  /*   760 */   411,  622,  411,  224,    4,  602,  104,  605,  602,  108,
90985  /*   770 */   591,  585,  622,   20,  375,  414,  167,  414,  215,  144,
90986  /*   780 */   470,  239,  167,  225,  602,  109,  602,  134,   18,   56,
90987  /*   790 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
90988  /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
90989  /*   810 */    51,   51,   50,  238,  313,  411,  276,  414,   12,  459,
90990  /*   820 */   276,  171,  411,   16,  223,  189,  602,  135,  354,  170,
90991  /*   830 */   414,  622,  630,    2,  411,  622,  540,  414,  143,  602,
90992  /*   840 */    61,  359,  132,  622,  591,  585,  602,  105,  458,  414,
90993  /*   850 */    23,  622,  446,  326,   23,  538,  622,  325,  602,  103,
90994  /*   860 */   427,  530,  309,   56,   57,   47,  583,  582,  584,  584,
90995  /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
90996  /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
90997  /*   890 */   264,  414,  411,  276,  359,  219,  157,  214,  357,  366,
90998  /*   900 */   602,   96,  522,  521,  414,  622,  358,  414,  622,  622,
90999  /*   910 */   411,  613,  612,  602,  102,  142,  602,   77,  591,  585,
91000  /*   920 */   529,  540,  231,  426,  308,  414,  622,  622,  468,  521,
91001  /*   930 */   324,  601,  257,  263,  602,   99,  622,   56,   45,   47,
91002  /*   940 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
91003  /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
91004  /*   960 */    50,  238,  313,  264,  264,  414,  411,  213,  209,  544,
91005  /*   970 */   544,  207,  611,   28,  602,  138,   50,  238,  622,  622,
91006  /*   980 */   381,  414,  503,  140,  323,  222,  274,  622,  590,  589,
91007  /*   990 */   602,  137,  591,  585,  629,  334,  606,   30,  622,  571,
91008  /*  1000 */   236,  601,  601,  130,  496,  601,  453,  451,  288,  286,
91009  /*  1010 */   587,  586,   57,   47,  583,  582,  584,  584,   54,   54,
91010  /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
91011  /*  1030 */    52,   51,   51,   51,   50,  238,  313,  588,  411,  414,
91012  /*  1040 */   411,  264,  410,  129,  595,  400,   27,  376,  602,  136,
91013  /*  1050 */   128,  165,  479,  414,  282,  414,  622,  622,  411,  622,
91014  /*  1060 */   622,  411,  602,   76,  602,   93,  591,  585,  188,  372,
91015  /*  1070 */   368,  125,  476,  414,  261,  160,  414,  171,  124,  472,
91016  /*  1080 */   123,   15,  602,   92,  450,  602,   75,   47,  583,  582,
91017  /*  1090 */   584,  584,   54,   54,   55,   55,   55,   55,  464,   53,
91018  /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
91019  /*  1110 */    43,  405,  264,    3,  558,  264,  545,  415,  623,  159,
91020  /*  1120 */   541,  158,  539,  278,   25,  461,  121,  622,  408,  622,
91021  /*  1130 */   622,  622,   24,   43,  405,  622,    3,  622,  622,  120,
91022  /*  1140 */   415,  623,   11,  456,  411,  156,  452,  403,  509,  277,
91023  /*  1150 */   118,  408,  489,  113,  205,  449,  271,  567,  221,  414,
91024  /*  1160 */   269,  267,  155,  622,  622,  111,  411,  622,  602,   95,
91025  /*  1170 */   403,  622,  411,  110,   10,  622,  622,   40,   41,  534,
91026  /*  1180 */   567,  414,   64,  264,   42,  413,  412,  414,  601,  596,
91027  /*  1190 */   602,   91,  445,  436,  150,  435,  602,   90,  622,  265,
91028  /*  1200 */    40,   41,  337,  242,  411,  191,  333,   42,  413,  412,
91029  /*  1210 */   398,  420,  596,  316,  622,  399,  260,  107,  230,  414,
91030  /*  1220 */   594,  594,  594,  593,  592,   14,  220,  411,  602,  101,
91031  /*  1230 */   240,  622,   43,  405,  362,    3,  149,  315,  626,  415,
91032  /*  1240 */   623,  127,  414,  594,  594,  594,  593,  592,   14,  622,
91033  /*  1250 */   408,  602,   89,  411,  181,   33,  405,  463,    3,  411,
91034  /*  1260 */   264,  462,  415,  623,  616,  615,  614,  355,  414,  403,
91035  /*  1270 */   417,  416,  622,  408,  414,  622,  622,  602,   87,  567,
91036  /*  1280 */   418,  627,  622,  602,   86,    8,  241,  180,  126,  255,
91037  /*  1290 */   600,  178,  403,  240,  208,  455,  395,  294,  444,   40,
91038  /*  1300 */    41,  297,  567,  248,  622,  296,   42,  413,  412,  247,
91039  /*  1310 */   622,  596,  244,  622,   30,   60,   31,  243,  430,  624,
91040  /*  1320 */   623,  292,   40,   41,  622,  295,  145,  622,  601,   42,
91041  /*  1330 */   413,  412,  622,  622,  596,  393,  622,  397,  599,   59,
91042  /*  1340 */   235,  622,  594,  594,  594,  593,  592,   14,  218,  291,
91043  /*  1350 */   622,   36,  344,  305,  304,  303,  179,  301,  411,  567,
91044  /*  1360 */   454,  557,  173,  185,  622,  594,  594,  594,  593,  592,
91045  /*  1370 */    14,  411,   29,  414,  151,  289,  246,  523,  411,  196,
91046  /*  1380 */   195,  335,  602,   85,  411,  245,  414,  526,  392,  543,
91047  /*  1390 */   411,  596,  287,  414,  285,  602,   72,  537,  153,  414,
91048  /*  1400 */   466,  411,  602,   71,  154,  414,  411,  152,  602,   84,
91049  /*  1410 */   386,  536,  329,  411,  602,   83,  414,  518,  280,  411,
91050  /*  1420 */   513,  414,  594,  594,  594,  602,   82,  517,  414,  311,
91051  /*  1430 */   602,   81,  411,  514,  414,  512,  131,  602,   70,  229,
91052  /*  1440 */   228,  227,  494,  602,   17,  411,  488,  414,  259,  346,
91053  /*  1450 */   249,  389,  487,  486,  314,  164,  602,   79,  310,  240,
91054  /*  1460 */   414,  373,  480,  163,  262,  371,  414,  162,  369,  602,
91055  /*  1470 */    78,  212,  478,   26,  477,  602,    9,  161,  467,  363,
91056  /*  1480 */   141,  122,  339,  187,  119,  457,  348,  117,  347,  116,
91057  /*  1490 */   115,  114,  448,  112,  182,  320,   22,  433,   19,  432,
91058  /*  1500 */   431,   63,  428,  610,  193,  298,  597,  574,  572,  404,
91059  /*  1510 */   555,  552,  290,  281,  510,  499,  498,  497,  495,  380,
91060  /*  1520 */   356,  460,  256,  250,  345,  447,  306,    5,  570,  550,
91061  /*  1530 */   299,  211,  370,  401,  550,  508,  502,  501,  490,  527,
91062  /*  1540 */   525,  483,  238,
91063 };
91064 static const YYCODETYPE yy_lookahead[] = {
91065  /*     0 */    19,  222,  223,  224,  225,   24,    1,   26,   77,   78,
91066  /*    10 */    79,   80,   15,   82,   83,   84,   85,   86,   87,   88,
91067  /*    20 */    89,   90,   91,   92,  113,   22,   26,   27,  117,   26,
91068  /*    30 */    49,   50,   81,   82,   83,   84,   85,   86,   87,   88,
91069  /*    40 */    89,   90,   91,   92,   88,   89,   90,   91,   92,   68,
91070  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
91071  /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
91072  /*    70 */    89,   90,   91,   92,   19,   94,  118,   19,  150,   22,
91073  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91074  /*    90 */    91,   92,   19,  165,   94,   95,   96,   94,  118,   99,
91075  /*   100 */   100,  101,  174,  175,   49,   50,   22,   23,   96,   54,
91076  /*   110 */   110,   99,  100,  101,    7,    8,   26,   27,   16,  105,
91077  /*   120 */   106,  107,  110,   68,   69,   70,   71,   72,   73,   74,
91078  /*   130 */    75,   76,   77,   78,   79,   80,  113,   82,   83,   84,
91079  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   16,
91080  /*   150 */    92,   67,   98,   24,   96,   97,   98,   99,  100,  101,
91081  /*   160 */   102,   25,   60,  109,   62,   92,  150,  109,  150,   25,
91082  /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
91083  /*   180 */   116,  165,  109,  165,   94,   95,  118,   97,  170,  171,
91084  /*   190 */   174,  175,  128,   60,  104,   62,  106,   68,   69,   70,
91085  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
91086  /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91087  /*   220 */    91,   92,   19,   21,   86,   87,   88,   89,   90,   91,
91088  /*   230 */    92,  215,   96,  150,   66,   99,  100,  101,   22,  150,
91089  /*   240 */   138,  118,   26,   27,  161,  162,  110,  103,  165,  231,
91090  /*   250 */   232,   23,   49,   50,  165,   24,   57,   26,   32,  170,
91091  /*   260 */   171,  112,   94,  114,  115,   63,   98,   41,  185,  186,
91092  /*   270 */   118,   68,   69,   70,   71,   72,   73,   74,   75,   76,
91093  /*   280 */    77,   78,   79,   80,   12,   82,   83,   84,   85,   86,
91094  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
91095  /*   300 */    28,   23,  100,   25,  105,  106,  107,  150,   26,   27,
91096  /*   310 */    94,   95,  169,  170,  171,  116,   44,   23,   46,  150,
91097  /*   320 */   231,  232,  165,   26,   27,   94,   49,   50,   23,   57,
91098  /*   330 */    25,  174,  175,   22,  165,   26,   27,   26,   27,  136,
91099  /*   340 */   138,   97,   98,  174,  175,   68,   69,   70,   71,   72,
91100  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
91101  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
91102  /*   370 */    19,  150,   23,  216,   23,  232,   94,   95,  221,  150,
91103  /*   380 */    23,  160,   25,  214,  215,  163,  165,   88,  166,  167,
91104  /*   390 */   168,   94,   95,   23,  165,  174,  175,   88,  160,  150,
91105  /*   400 */    49,   50,  120,   94,   95,   94,   95,  158,   26,   57,
91106  /*   410 */   161,  162,  113,  136,  165,  194,  117,  120,   22,   68,
91107  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
91108  /*   430 */    79,   80,  194,   82,   83,   84,   85,   86,   87,   88,
91109  /*   440 */    89,   90,   91,   92,   19,  150,   23,  112,   23,  114,
91110  /*   450 */   115,   25,  142,  143,  144,  145,  218,  105,  106,  107,
91111  /*   460 */   165,  112,  150,  114,  115,   22,  150,  166,  116,  174,
91112  /*   470 */   175,   22,   76,  235,   49,   50,   94,  165,  240,  172,
91113  /*   480 */   173,  165,  112,  155,  114,  115,  174,  175,  181,   11,
91114  /*   490 */   174,  175,   22,   68,   69,   70,   71,   72,   73,   74,
91115  /*   500 */    75,   76,   77,   78,   79,   80,  205,   82,   83,   84,
91116  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  160,
91117  /*   520 */    23,  226,   23,  222,   12,  224,  225,  150,  216,   23,
91118  /*   530 */    23,   25,   36,   25,   25,  112,  220,  114,  115,  135,
91119  /*   540 */    28,  137,  165,   26,   27,  119,   30,   51,   49,   50,
91120  /*   550 */    34,  174,  175,  194,   58,  166,   44,  229,   46,  160,
91121  /*   560 */    22,   23,  234,   25,   48,  206,  207,   68,   69,   70,
91122  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
91123  /*   580 */    23,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91124  /*   590 */    91,   92,   19,  194,  205,  150,   23,  220,   19,  181,
91125  /*   600 */   182,   95,   97,   95,  108,   67,  188,  169,  170,  171,
91126  /*   610 */   165,   94,   95,  222,   50,  224,  225,  218,  120,  150,
91127  /*   620 */   160,  116,   49,   50,   22,   23,  120,   25,  120,   50,
91128  /*   630 */   161,  162,   19,  128,  165,  244,   22,   23,  193,  240,
91129  /*   640 */    27,   68,   69,   70,   71,   72,   73,   74,   75,   76,
91130  /*   650 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
91131  /*   660 */    87,   88,   89,   90,   91,   92,   19,   25,  104,   67,
91132  /*   670 */   232,   24,  150,   23,  150,   25,  150,  150,  150,  150,
91133  /*   680 */   150,   67,   25,  104,    7,    8,    9,  165,  109,  165,
91134  /*   690 */   245,  165,  165,  165,  165,  165,   49,   50,  174,  175,
91135  /*   700 */   174,  175,  174,  175,  174,  175,    0,    1,    2,  105,
91136  /*   710 */   106,  107,  248,  249,  187,   68,   69,   70,   71,   72,
91137  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
91138  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
91139  /*   740 */    19,  150,  213,  165,  150,  222,  150,  224,  225,  166,
91140  /*   750 */   167,  168,  174,  175,  129,  130,  165,  150,  165,  165,
91141  /*   760 */   150,  165,  150,  241,   35,  174,  175,  174,  174,  175,
91142  /*   770 */    49,   50,  165,   52,   23,  165,   25,  165,  206,  207,
91143  /*   780 */    23,  197,   25,  187,  174,  175,  174,  175,  204,   68,
91144  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
91145  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
91146  /*   810 */    89,   90,   91,   92,   19,  150,  150,  165,   35,   23,
91147  /*   820 */   150,   25,  150,   22,  217,   24,  174,  175,  150,   35,
91148  /*   830 */   165,  165,  144,  145,  150,  165,  150,  165,  118,  174,
91149  /*   840 */   175,  150,   22,  165,   49,   50,  174,  175,   23,  165,
91150  /*   850 */    25,  165,   23,  187,   25,   27,  165,  187,  174,  175,
91151  /*   860 */    23,   23,   25,   68,   69,   70,   71,   72,   73,   74,
91152  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
91153  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
91154  /*   890 */   150,  165,  150,  150,  150,  217,   25,  160,   19,  213,
91155  /*   900 */   174,  175,  190,  191,  165,  165,   27,  165,  165,  165,
91156  /*   910 */   150,  150,  150,  174,  175,   39,  174,  175,   49,   50,
91157  /*   920 */    23,  150,   52,  250,  251,  165,  165,  165,  190,  191,
91158  /*   930 */   187,  194,  241,  193,  174,  175,  165,   68,   69,   70,
91159  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
91160  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91161  /*   960 */    91,   92,   19,  150,  150,  165,  150,  160,  160,  166,
91162  /*   970 */   166,  160,  150,   22,  174,  175,   91,   92,  165,  165,
91163  /*   980 */    52,  165,   29,  150,  213,  241,   23,  165,   49,   50,
91164  /*   990 */   174,  175,   49,   50,    1,    2,  173,  126,  165,   86,
91165  /*  1000 */    87,  194,  194,   22,  181,  194,  193,  193,  205,  205,
91166  /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
91167  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
91168  /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
91169  /*  1040 */   150,  150,  150,   22,  150,  150,   22,   52,  174,  175,
91170  /*  1050 */    22,  102,   20,  165,  109,  165,  165,  165,  150,  165,
91171  /*  1060 */   165,  150,  174,  175,  174,  175,   49,   50,   24,   19,
91172  /*  1070 */    43,  104,   59,  165,  138,  104,  165,   25,   53,   53,
91173  /*  1080 */    22,    5,  174,  175,  193,  174,  175,   70,   71,   72,
91174  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,    1,   82,
91175  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
91176  /*  1110 */    19,   20,  150,   22,  150,  150,  150,   26,   27,  118,
91177  /*  1120 */   150,   35,  150,  150,   76,   27,  108,  165,   37,  165,
91178  /*  1130 */   165,  165,   76,   19,   20,  165,   22,  165,  165,  127,
91179  /*  1140 */    26,   27,   22,    1,  150,   16,   20,   56,  150,  150,
91180  /*  1150 */   119,   37,  150,  119,  160,  193,  150,   66,  193,  165,
91181  /*  1160 */   150,  150,  121,  165,  165,  108,  150,  165,  174,  175,
91182  /*  1170 */    56,  165,  150,  127,   22,  165,  165,   86,   87,   88,
91183  /*  1180 */    66,  165,   16,  150,   93,   94,   95,  165,  194,   98,
91184  /*  1190 */   174,  175,  128,   23,   15,   23,  174,  175,  165,  150,
91185  /*  1200 */    86,   87,   65,  140,  150,   22,    3,   93,   94,   95,
91186  /*  1210 */   216,    4,   98,  252,  165,  221,  150,  164,  180,  165,
91187  /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
91188  /*  1230 */   116,  165,   19,   20,  150,   22,  249,  252,  149,   26,
91189  /*  1240 */    27,  180,  165,  129,  130,  131,  132,  133,  134,  165,
91190  /*  1250 */    37,  174,  175,  150,    6,   19,   20,  150,   22,  150,
91191  /*  1260 */   150,  150,   26,   27,  149,  149,   13,  150,  165,   56,
91192  /*  1270 */   149,  159,  165,   37,  165,  165,  165,  174,  175,   66,
91193  /*  1280 */   146,  147,  165,  174,  175,   25,  152,  151,  154,  150,
91194  /*  1290 */   194,  151,   56,  116,  160,  150,  123,  202,  150,   86,
91195  /*  1300 */    87,  199,   66,  193,  165,  200,   93,   94,   95,  150,
91196  /*  1310 */   165,   98,  150,  165,  126,   22,  124,  150,  150,   26,
91197  /*  1320 */    27,  150,   86,   87,  165,  201,  150,  165,  194,   93,
91198  /*  1330 */    94,   95,  165,  165,   98,  150,  165,  122,  203,  125,
91199  /*  1340 */   227,  165,  129,  130,  131,  132,  133,  134,    5,  150,
91200  /*  1350 */   165,  135,  218,   10,   11,   12,   13,   14,  150,   66,
91201  /*  1360 */    17,  157,  118,  157,  165,  129,  130,  131,  132,  133,
91202  /*  1370 */   134,  150,  104,  165,   31,  210,   33,  176,  150,   86,
91203  /*  1380 */    87,  247,  174,  175,  150,   42,  165,   94,  121,  211,
91204  /*  1390 */   150,   98,  210,  165,  210,  174,  175,  211,   55,  165,
91205  /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
91206  /*  1410 */   104,  211,   47,  150,  174,  175,  165,  176,  176,  150,
91207  /*  1420 */   103,  165,  129,  130,  131,  174,  175,  184,  165,  179,
91208  /*  1430 */   174,  175,  150,  178,  165,  176,   22,  174,  175,  230,
91209  /*  1440 */    92,  230,  184,  174,  175,  150,  176,  165,  105,  106,
91210  /*  1450 */   107,  150,  176,  176,  111,  156,  174,  175,  179,  116,
91211  /*  1460 */   165,   18,  157,  156,  238,  157,  165,  156,   45,  174,
91212  /*  1470 */   175,  157,  157,  135,  239,  174,  175,  156,  189,  157,
91213  /*  1480 */    68,  189,  139,  219,   22,  199,  157,  192,   18,  192,
91214  /*  1490 */   192,  192,  199,  189,  219,  157,  243,   40,  243,  157,
91215  /*  1500 */   157,  246,   38,  153,  196,  198,  166,  233,  233,  228,
91216  /*  1510 */   177,  177,  209,  177,  182,  177,  166,  177,  166,  178,
91217  /*  1520 */   242,  199,  242,  209,  209,  199,  148,  196,  166,  208,
91218  /*  1530 */   195,  236,  237,  191,  208,  183,  183,  183,  186,  174,
91219  /*  1540 */   174,  186,   92,
91220 };
91221 #define YY_SHIFT_USE_DFLT (-90)
91222 #define YY_SHIFT_COUNT (418)
91223 #define YY_SHIFT_MIN   (-89)
91224 #define YY_SHIFT_MAX   (1470)
91225 static const short yy_shift_ofst[] = {
91226  /*     0 */   993, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
91227  /*    10 */  1213, 1213, 1213, 1213, 1213,  352,  517,  721, 1091, 1213,
91228  /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
91229  /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
91230  /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
91231  /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
91232  /*    60 */  1213,  -49,  199,  517,  517,  913,  913,  382, 1177,   55,
91233  /*    70 */   647,  573,  499,  425,  351,  277,  203,  129,  795,  795,
91234  /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
91235  /*    90 */   795,  795,  795,  795,  795,  795,  869,  795,  943, 1017,
91236  /*   100 */  1017,  -69,  -69,  -69,  -69,   -1,   -1,   58,  138,  -44,
91237  /*   110 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91238  /*   120 */   517,  517,  517,  517,  517,  517,  202,  579,  517,  517,
91239  /*   130 */   517,  517,  517,  382,  885, 1450,  -90,  -90,  -90, 1293,
91240  /*   140 */    73,  272,  272,  309,  311,  297,  282,  216,  602,  538,
91241  /*   150 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91242  /*   160 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91243  /*   170 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91244  /*   180 */   517,  517,  505,  231,  231,  231,  706,   64, 1177, 1177,
91245  /*   190 */  1177,  -90,  -90,  -90,  136,  168,  168,   12,  496,  496,
91246  /*   200 */   496,  506,  423,  512,  370,  349,  335,  149,  149,  149,
91247  /*   210 */   149,  604,  516,  149,  149,  508,    3,  299,  677,  871,
91248  /*   220 */   613,  613,  879,  871,  879,  144,  382,  226,  382,  226,
91249  /*   230 */   564,  226,  613,  226,  226,  404,  625,  625,  382,  426,
91250  /*   240 */   -89,  801, 1464, 1244, 1244, 1457, 1457, 1244, 1462, 1412,
91251  /*   250 */  1188, 1470, 1470, 1470, 1470, 1244, 1188, 1462, 1412, 1412,
91252  /*   260 */  1244, 1443, 1338, 1423, 1244, 1244, 1443, 1244, 1443, 1244,
91253  /*   270 */  1443, 1414, 1306, 1306, 1306, 1365, 1348, 1348, 1414, 1306,
91254  /*   280 */  1317, 1306, 1365, 1306, 1306, 1267, 1268, 1267, 1268, 1267,
91255  /*   290 */  1268, 1244, 1244, 1216, 1214, 1215, 1192, 1173, 1188, 1177,
91256  /*   300 */  1260, 1253, 1253, 1248, 1248, 1248, 1248,  -90,  -90,  -90,
91257  /*   310 */   -90,  -90,  -90,  939,  102,  614,   84,  133,   14,  837,
91258  /*   320 */   396,  829,  825,  796,  757,  751,  650,  357,  244,  107,
91259  /*   330 */    54,  305,  278, 1207, 1203, 1183, 1063, 1179, 1137, 1166,
91260  /*   340 */  1172, 1170, 1064, 1152, 1046, 1057, 1034, 1126, 1041, 1129,
91261  /*   350 */  1142, 1031, 1120, 1012, 1056, 1048, 1018, 1098, 1086, 1001,
91262  /*   360 */  1097, 1076, 1058,  971,  936, 1026, 1052, 1025, 1013, 1027,
91263  /*   370 */   967, 1044, 1032, 1050,  945,  949, 1028,  995, 1024, 1021,
91264  /*   380 */   963,  981,  928,  953,  951,  870,  876,  897,  838,  720,
91265  /*   390 */   828,  794,  820,  498,  642,  783,  657,  729,  642,  557,
91266  /*   400 */   507,  509,  497,  470,  478,  449,  294,  228,  443,   23,
91267  /*   410 */   152,  123,   68,  -20,  -42,   57,   39,   -3,    5,
91268 };
91269 #define YY_REDUCE_USE_DFLT (-222)
91270 #define YY_REDUCE_COUNT (312)
91271 #define YY_REDUCE_MIN   (-221)
91272 #define YY_REDUCE_MAX   (1378)
91273 static const short yy_reduce_ofst[] = {
91274  /*     0 */   310,  994, 1134,  221,  169,  157,   89,   18,   83,  301,
91275  /*    10 */   377,  316,  312,   16,  295,  238,  249,  391, 1301, 1295,
91276  /*    20 */  1282, 1269, 1263, 1256, 1251, 1240, 1234, 1228, 1221, 1208,
91277  /*    30 */  1109, 1103, 1077, 1054, 1022, 1016,  911,  908,  890,  888,
91278  /*    40 */   874,  816,  800,  760,  742,  739,  726,  684,  672,  665,
91279  /*    50 */   652,  612,  610,  594,  591,  578,  530,  528,  526,  524,
91280  /*    60 */   -72, -221,  399,  469,  445,  438,  143,  222,  359,  523,
91281  /*    70 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
91282  /*    80 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
91283  /*    90 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
91284  /*   100 */   523,  523,  523,  523,  523,  523,  523,  307,  523,  523,
91285  /*   110 */  1110,  678, 1033,  965,  962,  891,  814,  813,  744,  771,
91286  /*   120 */   691,  607,  522,  743,  686,  740,  328,  418,  670,  666,
91287  /*   130 */   596,  527,  529,  583,  523,  523,  523,  523,  523,  593,
91288  /*   140 */   823,  738,  712,  892, 1199, 1185, 1176, 1171,  673,  673,
91289  /*   150 */  1168, 1167, 1162, 1159, 1148, 1145, 1139, 1117, 1111, 1107,
91290  /*   160 */  1084, 1066, 1049, 1011, 1010, 1006, 1002,  999,  998,  973,
91291  /*   170 */   972,  970,  966,  964,  895,  894,  892,  833,  822,  762,
91292  /*   180 */   761,  229,  811,  804,  803,  389,  688,  808,  807,  737,
91293  /*   190 */   460,  464,  572,  584, 1355, 1366, 1365, 1352, 1354, 1353,
91294  /*   200 */  1352, 1326, 1335, 1342, 1335, 1335, 1335, 1335, 1335, 1335,
91295  /*   210 */  1335, 1295, 1295, 1335, 1335, 1321, 1362, 1331, 1378, 1326,
91296  /*   220 */  1315, 1314, 1280, 1322, 1278, 1341, 1352, 1340, 1350, 1338,
91297  /*   230 */  1332, 1336, 1303, 1334, 1333, 1281, 1275, 1274, 1340, 1307,
91298  /*   240 */  1308, 1350, 1255, 1343, 1342, 1255, 1253, 1338, 1275, 1304,
91299  /*   250 */  1293, 1299, 1298, 1297, 1295, 1329, 1286, 1264, 1292, 1289,
91300  /*   260 */  1322, 1321, 1235, 1226, 1315, 1314, 1311, 1308, 1307, 1305,
91301  /*   270 */  1299, 1279, 1277, 1276, 1270, 1258, 1211, 1209, 1250, 1259,
91302  /*   280 */  1255, 1242, 1243, 1241, 1201, 1200, 1184, 1186, 1182, 1178,
91303  /*   290 */  1165, 1206, 1204, 1113, 1135, 1095, 1124, 1105, 1102, 1096,
91304  /*   300 */  1112, 1140, 1136, 1121, 1116, 1115, 1089,  985,  961,  987,
91305  /*   310 */  1061, 1038, 1053,
91306 };
91307 static const YYACTIONTYPE yy_default[] = {
91308  /*     0 */   636,  872,  961,  961,  961,  872,  901,  901,  961,  760,
91309  /*    10 */   961,  961,  961,  961,  870,  961,  961,  935,  961,  961,
91310  /*    20 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91311  /*    30 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91312  /*    40 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91313  /*    50 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91314  /*    60 */   961,  844,  961,  961,  961,  901,  901,  675,  764,  795,
91315  /*    70 */   961,  961,  961,  961,  961,  961,  961,  961,  934,  936,
91316  /*    80 */   810,  809,  803,  802,  914,  775,  800,  793,  786,  797,
91317  /*    90 */   873,  866,  867,  865,  869,  874,  961,  796,  832,  850,
91318  /*   100 */   831,  849,  856,  848,  834,  843,  833,  667,  835,  836,
91319  /*   110 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91320  /*   120 */   961,  961,  961,  961,  961,  961,  662,  729,  961,  961,
91321  /*   130 */   961,  961,  961,  961,  837,  838,  853,  852,  851,  961,
91322  /*   140 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91323  /*   150 */   961,  941,  939,  961,  885,  961,  961,  961,  961,  961,
91324  /*   160 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91325  /*   170 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91326  /*   180 */   961,  642,  961,  760,  760,  760,  636,  961,  961,  961,
91327  /*   190 */   961,  953,  764,  754,  720,  961,  961,  961,  961,  961,
91328  /*   200 */   961,  961,  961,  961,  961,  961,  961,  805,  743,  924,
91329  /*   210 */   926,  961,  907,  741,  664,  762,  677,  752,  644,  799,
91330  /*   220 */   777,  777,  919,  799,  919,  701,  961,  789,  961,  789,
91331  /*   230 */   698,  789,  777,  789,  789,  868,  961,  961,  961,  761,
91332  /*   240 */   752,  961,  946,  768,  768,  938,  938,  768,  811,  733,
91333  /*   250 */   799,  740,  740,  740,  740,  768,  799,  811,  733,  733,
91334  /*   260 */   768,  659,  913,  911,  768,  768,  659,  768,  659,  768,
91335  /*   270 */   659,  878,  731,  731,  731,  716,  882,  882,  878,  731,
91336  /*   280 */   701,  731,  716,  731,  731,  781,  776,  781,  776,  781,
91337  /*   290 */   776,  768,  768,  961,  794,  782,  792,  790,  799,  961,
91338  /*   300 */   719,  652,  652,  641,  641,  641,  641,  958,  958,  953,
91339  /*   310 */   703,  703,  685,  961,  961,  961,  961,  961,  961,  961,
91340  /*   320 */   887,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91341  /*   330 */   961,  961,  961,  961,  637,  948,  961,  961,  945,  961,
91342  /*   340 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91343  /*   350 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  917,
91344  /*   360 */   961,  961,  961,  961,  961,  961,  910,  909,  961,  961,
91345  /*   370 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91346  /*   380 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91347  /*   390 */   961,  961,  961,  961,  791,  961,  783,  961,  871,  961,
91348  /*   400 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  746,
91349  /*   410 */   820,  961,  819,  823,  818,  669,  961,  650,  961,  633,
91350  /*   420 */   638,  957,  960,  959,  956,  955,  954,  949,  947,  944,
91351  /*   430 */   943,  942,  940,  937,  933,  891,  889,  896,  895,  894,
91352  /*   440 */   893,  892,  890,  888,  886,  806,  804,  801,  798,  932,
91353  /*   450 */   884,  742,  739,  738,  658,  950,  916,  925,  923,  812,
91354  /*   460 */   922,  921,  920,  918,  915,  902,  808,  807,  734,  876,
91355  /*   470 */   875,  661,  906,  905,  904,  908,  912,  903,  770,  660,
91356  /*   480 */   657,  666,  723,  722,  730,  728,  727,  726,  725,  724,
91357  /*   490 */   721,  668,  676,  687,  715,  700,  699,  881,  883,  880,
91358  /*   500 */   879,  708,  707,  713,  712,  711,  710,  709,  706,  705,
91359  /*   510 */   704,  697,  696,  702,  695,  718,  717,  714,  694,  737,
91360  /*   520 */   736,  735,  732,  693,  692,  691,  823,  690,  689,  829,
91361  /*   530 */   828,  816,  860,  757,  756,  755,  767,  766,  779,  778,
91362  /*   540 */   814,  813,  780,  765,  759,  758,  774,  773,  772,  771,
91363  /*   550 */   763,  753,  785,  788,  787,  784,  845,  862,  769,  859,
91364  /*   560 */   931,  930,  929,  928,  927,  864,  863,  830,  827,  680,
91365  /*   570 */   681,  900,  898,  899,  897,  683,  682,  679,  678,  861,
91366  /*   580 */   748,  747,  857,  854,  846,  841,  858,  855,  847,  842,
91367  /*   590 */   840,  839,  825,  824,  822,  821,  817,  826,  671,  749,
91368  /*   600 */   745,  744,  815,  751,  750,  688,  686,  684,  665,  663,
91369  /*   610 */   656,  654,  653,  655,  651,  649,  648,  647,  646,  645,
91370  /*   620 */   674,  673,  672,  670,  669,  643,  640,  639,  635,  634,
91371  /*   630 */   632,
91372 };
91373
91374 /* The next table maps tokens into fallback tokens.  If a construct
91375 ** like the following:
91376 ** 
91377 **      %fallback ID X Y Z.
91378 **
91379 ** appears in the grammar, then ID becomes a fallback token for X, Y,
91380 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
91381 ** but it does not parse, the type of the token is changed to ID and
91382 ** the parse is retried before an error is thrown.
91383 */
91384 #ifdef YYFALLBACK
91385 static const YYCODETYPE yyFallback[] = {
91386     0,  /*          $ => nothing */
91387     0,  /*       SEMI => nothing */
91388    26,  /*    EXPLAIN => ID */
91389    26,  /*      QUERY => ID */
91390    26,  /*       PLAN => ID */
91391    26,  /*      BEGIN => ID */
91392     0,  /* TRANSACTION => nothing */
91393    26,  /*   DEFERRED => ID */
91394    26,  /*  IMMEDIATE => ID */
91395    26,  /*  EXCLUSIVE => ID */
91396     0,  /*     COMMIT => nothing */
91397    26,  /*        END => ID */
91398    26,  /*   ROLLBACK => ID */
91399    26,  /*  SAVEPOINT => ID */
91400    26,  /*    RELEASE => ID */
91401     0,  /*         TO => nothing */
91402     0,  /*      TABLE => nothing */
91403     0,  /*     CREATE => nothing */
91404    26,  /*         IF => ID */
91405     0,  /*        NOT => nothing */
91406     0,  /*     EXISTS => nothing */
91407    26,  /*       TEMP => ID */
91408     0,  /*         LP => nothing */
91409     0,  /*         RP => nothing */
91410     0,  /*         AS => nothing */
91411     0,  /*      COMMA => nothing */
91412     0,  /*         ID => nothing */
91413     0,  /*    INDEXED => nothing */
91414    26,  /*      ABORT => ID */
91415    26,  /*     ACTION => ID */
91416    26,  /*      AFTER => ID */
91417    26,  /*    ANALYZE => ID */
91418    26,  /*        ASC => ID */
91419    26,  /*     ATTACH => ID */
91420    26,  /*     BEFORE => ID */
91421    26,  /*         BY => ID */
91422    26,  /*    CASCADE => ID */
91423    26,  /*       CAST => ID */
91424    26,  /*   COLUMNKW => ID */
91425    26,  /*   CONFLICT => ID */
91426    26,  /*   DATABASE => ID */
91427    26,  /*       DESC => ID */
91428    26,  /*     DETACH => ID */
91429    26,  /*       EACH => ID */
91430    26,  /*       FAIL => ID */
91431    26,  /*        FOR => ID */
91432    26,  /*     IGNORE => ID */
91433    26,  /*  INITIALLY => ID */
91434    26,  /*    INSTEAD => ID */
91435    26,  /*    LIKE_KW => ID */
91436    26,  /*      MATCH => ID */
91437    26,  /*         NO => ID */
91438    26,  /*        KEY => ID */
91439    26,  /*         OF => ID */
91440    26,  /*     OFFSET => ID */
91441    26,  /*     PRAGMA => ID */
91442    26,  /*      RAISE => ID */
91443    26,  /*    REPLACE => ID */
91444    26,  /*   RESTRICT => ID */
91445    26,  /*        ROW => ID */
91446    26,  /*    TRIGGER => ID */
91447    26,  /*     VACUUM => ID */
91448    26,  /*       VIEW => ID */
91449    26,  /*    VIRTUAL => ID */
91450    26,  /*    REINDEX => ID */
91451    26,  /*     RENAME => ID */
91452    26,  /*   CTIME_KW => ID */
91453 };
91454 #endif /* YYFALLBACK */
91455
91456 /* The following structure represents a single element of the
91457 ** parser's stack.  Information stored includes:
91458 **
91459 **   +  The state number for the parser at this level of the stack.
91460 **
91461 **   +  The value of the token stored at this level of the stack.
91462 **      (In other words, the "major" token.)
91463 **
91464 **   +  The semantic value stored at this level of the stack.  This is
91465 **      the information used by the action routines in the grammar.
91466 **      It is sometimes called the "minor" token.
91467 */
91468 struct yyStackEntry {
91469   YYACTIONTYPE stateno;  /* The state-number */
91470   YYCODETYPE major;      /* The major token value.  This is the code
91471                          ** number for the token at this stack level */
91472   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
91473                          ** is the value of the token  */
91474 };
91475 typedef struct yyStackEntry yyStackEntry;
91476
91477 /* The state of the parser is completely contained in an instance of
91478 ** the following structure */
91479 struct yyParser {
91480   int yyidx;                    /* Index of top element in stack */
91481 #ifdef YYTRACKMAXSTACKDEPTH
91482   int yyidxMax;                 /* Maximum value of yyidx */
91483 #endif
91484   int yyerrcnt;                 /* Shifts left before out of the error */
91485   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
91486 #if YYSTACKDEPTH<=0
91487   int yystksz;                  /* Current side of the stack */
91488   yyStackEntry *yystack;        /* The parser's stack */
91489 #else
91490   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
91491 #endif
91492 };
91493 typedef struct yyParser yyParser;
91494
91495 #ifndef NDEBUG
91496 static FILE *yyTraceFILE = 0;
91497 static char *yyTracePrompt = 0;
91498 #endif /* NDEBUG */
91499
91500 #ifndef NDEBUG
91501 /* 
91502 ** Turn parser tracing on by giving a stream to which to write the trace
91503 ** and a prompt to preface each trace message.  Tracing is turned off
91504 ** by making either argument NULL 
91505 **
91506 ** Inputs:
91507 ** <ul>
91508 ** <li> A FILE* to which trace output should be written.
91509 **      If NULL, then tracing is turned off.
91510 ** <li> A prefix string written at the beginning of every
91511 **      line of trace output.  If NULL, then tracing is
91512 **      turned off.
91513 ** </ul>
91514 **
91515 ** Outputs:
91516 ** None.
91517 */
91518 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
91519   yyTraceFILE = TraceFILE;
91520   yyTracePrompt = zTracePrompt;
91521   if( yyTraceFILE==0 ) yyTracePrompt = 0;
91522   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
91523 }
91524 #endif /* NDEBUG */
91525
91526 #ifndef NDEBUG
91527 /* For tracing shifts, the names of all terminals and nonterminals
91528 ** are required.  The following table supplies these names */
91529 static const char *const yyTokenName[] = { 
91530   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
91531   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
91532   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
91533   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
91534   "TABLE",         "CREATE",        "IF",            "NOT",         
91535   "EXISTS",        "TEMP",          "LP",            "RP",          
91536   "AS",            "COMMA",         "ID",            "INDEXED",     
91537   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
91538   "ASC",           "ATTACH",        "BEFORE",        "BY",          
91539   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
91540   "DATABASE",      "DESC",          "DETACH",        "EACH",        
91541   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
91542   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
91543   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
91544   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
91545   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
91546   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
91547   "OR",            "AND",           "IS",            "BETWEEN",     
91548   "IN",            "ISNULL",        "NOTNULL",       "NE",          
91549   "EQ",            "GT",            "LE",            "LT",          
91550   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
91551   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
91552   "STAR",          "SLASH",         "REM",           "CONCAT",      
91553   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
91554   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
91555   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
91556   "ON",            "INSERT",        "DELETE",        "UPDATE",      
91557   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
91558   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
91559   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
91560   "JOIN",          "USING",         "ORDER",         "GROUP",       
91561   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
91562   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
91563   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
91564   "THEN",          "ELSE",          "INDEX",         "ALTER",       
91565   "ADD",           "error",         "input",         "cmdlist",     
91566   "ecmd",          "explain",       "cmdx",          "cmd",         
91567   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
91568   "create_table",  "create_table_args",  "createkw",      "temp",        
91569   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
91570   "select",        "column",        "columnid",      "type",        
91571   "carglist",      "id",            "ids",           "typetoken",   
91572   "typename",      "signed",        "plus_num",      "minus_num",   
91573   "carg",          "ccons",         "term",          "expr",        
91574   "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
91575   "refargs",       "defer_subclause",  "refarg",        "refact",      
91576   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",     
91577   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
91578   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
91579   "distinct",      "selcollist",    "from",          "where_opt",   
91580   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
91581   "sclp",          "as",            "seltablist",    "stl_prefix",  
91582   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
91583   "joinop2",       "inscollist",    "sortlist",      "sortitem",    
91584   "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
91585   "itemlist",      "exprlist",      "likeop",        "escape",      
91586   "between_op",    "in_op",         "case_operand",  "case_exprlist",
91587   "case_else",     "uniqueflag",    "collate",       "nmnum",       
91588   "plus_opt",      "number",        "trigger_decl",  "trigger_cmd_list",
91589   "trigger_time",  "trigger_event",  "foreach_clause",  "when_clause", 
91590   "trigger_cmd",   "trnm",          "tridxby",       "database_kw_opt",
91591   "key_opt",       "add_column_fullname",  "kwcolumn_opt",  "create_vtab", 
91592   "vtabarglist",   "vtabarg",       "vtabargtoken",  "lp",          
91593   "anylist",     
91594 };
91595 #endif /* NDEBUG */
91596
91597 #ifndef NDEBUG
91598 /* For tracing reduce actions, the names of all rules are required.
91599 */
91600 static const char *const yyRuleName[] = {
91601  /*   0 */ "input ::= cmdlist",
91602  /*   1 */ "cmdlist ::= cmdlist ecmd",
91603  /*   2 */ "cmdlist ::= ecmd",
91604  /*   3 */ "ecmd ::= SEMI",
91605  /*   4 */ "ecmd ::= explain cmdx SEMI",
91606  /*   5 */ "explain ::=",
91607  /*   6 */ "explain ::= EXPLAIN",
91608  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
91609  /*   8 */ "cmdx ::= cmd",
91610  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
91611  /*  10 */ "trans_opt ::=",
91612  /*  11 */ "trans_opt ::= TRANSACTION",
91613  /*  12 */ "trans_opt ::= TRANSACTION nm",
91614  /*  13 */ "transtype ::=",
91615  /*  14 */ "transtype ::= DEFERRED",
91616  /*  15 */ "transtype ::= IMMEDIATE",
91617  /*  16 */ "transtype ::= EXCLUSIVE",
91618  /*  17 */ "cmd ::= COMMIT trans_opt",
91619  /*  18 */ "cmd ::= END trans_opt",
91620  /*  19 */ "cmd ::= ROLLBACK trans_opt",
91621  /*  20 */ "savepoint_opt ::= SAVEPOINT",
91622  /*  21 */ "savepoint_opt ::=",
91623  /*  22 */ "cmd ::= SAVEPOINT nm",
91624  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
91625  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
91626  /*  25 */ "cmd ::= create_table create_table_args",
91627  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
91628  /*  27 */ "createkw ::= CREATE",
91629  /*  28 */ "ifnotexists ::=",
91630  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
91631  /*  30 */ "temp ::= TEMP",
91632  /*  31 */ "temp ::=",
91633  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
91634  /*  33 */ "create_table_args ::= AS select",
91635  /*  34 */ "columnlist ::= columnlist COMMA column",
91636  /*  35 */ "columnlist ::= column",
91637  /*  36 */ "column ::= columnid type carglist",
91638  /*  37 */ "columnid ::= nm",
91639  /*  38 */ "id ::= ID",
91640  /*  39 */ "id ::= INDEXED",
91641  /*  40 */ "ids ::= ID|STRING",
91642  /*  41 */ "nm ::= id",
91643  /*  42 */ "nm ::= STRING",
91644  /*  43 */ "nm ::= JOIN_KW",
91645  /*  44 */ "type ::=",
91646  /*  45 */ "type ::= typetoken",
91647  /*  46 */ "typetoken ::= typename",
91648  /*  47 */ "typetoken ::= typename LP signed RP",
91649  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
91650  /*  49 */ "typename ::= ids",
91651  /*  50 */ "typename ::= typename ids",
91652  /*  51 */ "signed ::= plus_num",
91653  /*  52 */ "signed ::= minus_num",
91654  /*  53 */ "carglist ::= carglist carg",
91655  /*  54 */ "carglist ::=",
91656  /*  55 */ "carg ::= CONSTRAINT nm ccons",
91657  /*  56 */ "carg ::= ccons",
91658  /*  57 */ "ccons ::= DEFAULT term",
91659  /*  58 */ "ccons ::= DEFAULT LP expr RP",
91660  /*  59 */ "ccons ::= DEFAULT PLUS term",
91661  /*  60 */ "ccons ::= DEFAULT MINUS term",
91662  /*  61 */ "ccons ::= DEFAULT id",
91663  /*  62 */ "ccons ::= NULL onconf",
91664  /*  63 */ "ccons ::= NOT NULL onconf",
91665  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
91666  /*  65 */ "ccons ::= UNIQUE onconf",
91667  /*  66 */ "ccons ::= CHECK LP expr RP",
91668  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
91669  /*  68 */ "ccons ::= defer_subclause",
91670  /*  69 */ "ccons ::= COLLATE ids",
91671  /*  70 */ "autoinc ::=",
91672  /*  71 */ "autoinc ::= AUTOINCR",
91673  /*  72 */ "refargs ::=",
91674  /*  73 */ "refargs ::= refargs refarg",
91675  /*  74 */ "refarg ::= MATCH nm",
91676  /*  75 */ "refarg ::= ON INSERT refact",
91677  /*  76 */ "refarg ::= ON DELETE refact",
91678  /*  77 */ "refarg ::= ON UPDATE refact",
91679  /*  78 */ "refact ::= SET NULL",
91680  /*  79 */ "refact ::= SET DEFAULT",
91681  /*  80 */ "refact ::= CASCADE",
91682  /*  81 */ "refact ::= RESTRICT",
91683  /*  82 */ "refact ::= NO ACTION",
91684  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
91685  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
91686  /*  85 */ "init_deferred_pred_opt ::=",
91687  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
91688  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
91689  /*  88 */ "conslist_opt ::=",
91690  /*  89 */ "conslist_opt ::= COMMA conslist",
91691  /*  90 */ "conslist ::= conslist COMMA tcons",
91692  /*  91 */ "conslist ::= conslist tcons",
91693  /*  92 */ "conslist ::= tcons",
91694  /*  93 */ "tcons ::= CONSTRAINT nm",
91695  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
91696  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
91697  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
91698  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
91699  /*  98 */ "defer_subclause_opt ::=",
91700  /*  99 */ "defer_subclause_opt ::= defer_subclause",
91701  /* 100 */ "onconf ::=",
91702  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
91703  /* 102 */ "orconf ::=",
91704  /* 103 */ "orconf ::= OR resolvetype",
91705  /* 104 */ "resolvetype ::= raisetype",
91706  /* 105 */ "resolvetype ::= IGNORE",
91707  /* 106 */ "resolvetype ::= REPLACE",
91708  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
91709  /* 108 */ "ifexists ::= IF EXISTS",
91710  /* 109 */ "ifexists ::=",
91711  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
91712  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
91713  /* 112 */ "cmd ::= select",
91714  /* 113 */ "select ::= oneselect",
91715  /* 114 */ "select ::= select multiselect_op oneselect",
91716  /* 115 */ "multiselect_op ::= UNION",
91717  /* 116 */ "multiselect_op ::= UNION ALL",
91718  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
91719  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
91720  /* 119 */ "distinct ::= DISTINCT",
91721  /* 120 */ "distinct ::= ALL",
91722  /* 121 */ "distinct ::=",
91723  /* 122 */ "sclp ::= selcollist COMMA",
91724  /* 123 */ "sclp ::=",
91725  /* 124 */ "selcollist ::= sclp expr as",
91726  /* 125 */ "selcollist ::= sclp STAR",
91727  /* 126 */ "selcollist ::= sclp nm DOT STAR",
91728  /* 127 */ "as ::= AS nm",
91729  /* 128 */ "as ::= ids",
91730  /* 129 */ "as ::=",
91731  /* 130 */ "from ::=",
91732  /* 131 */ "from ::= FROM seltablist",
91733  /* 132 */ "stl_prefix ::= seltablist joinop",
91734  /* 133 */ "stl_prefix ::=",
91735  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
91736  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
91737  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
91738  /* 137 */ "dbnm ::=",
91739  /* 138 */ "dbnm ::= DOT nm",
91740  /* 139 */ "fullname ::= nm dbnm",
91741  /* 140 */ "joinop ::= COMMA|JOIN",
91742  /* 141 */ "joinop ::= JOIN_KW JOIN",
91743  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
91744  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
91745  /* 144 */ "on_opt ::= ON expr",
91746  /* 145 */ "on_opt ::=",
91747  /* 146 */ "indexed_opt ::=",
91748  /* 147 */ "indexed_opt ::= INDEXED BY nm",
91749  /* 148 */ "indexed_opt ::= NOT INDEXED",
91750  /* 149 */ "using_opt ::= USING LP inscollist RP",
91751  /* 150 */ "using_opt ::=",
91752  /* 151 */ "orderby_opt ::=",
91753  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
91754  /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
91755  /* 154 */ "sortlist ::= sortitem sortorder",
91756  /* 155 */ "sortitem ::= expr",
91757  /* 156 */ "sortorder ::= ASC",
91758  /* 157 */ "sortorder ::= DESC",
91759  /* 158 */ "sortorder ::=",
91760  /* 159 */ "groupby_opt ::=",
91761  /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
91762  /* 161 */ "having_opt ::=",
91763  /* 162 */ "having_opt ::= HAVING expr",
91764  /* 163 */ "limit_opt ::=",
91765  /* 164 */ "limit_opt ::= LIMIT expr",
91766  /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
91767  /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
91768  /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
91769  /* 168 */ "where_opt ::=",
91770  /* 169 */ "where_opt ::= WHERE expr",
91771  /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
91772  /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
91773  /* 172 */ "setlist ::= nm EQ expr",
91774  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
91775  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
91776  /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
91777  /* 176 */ "insert_cmd ::= INSERT orconf",
91778  /* 177 */ "insert_cmd ::= REPLACE",
91779  /* 178 */ "itemlist ::= itemlist COMMA expr",
91780  /* 179 */ "itemlist ::= expr",
91781  /* 180 */ "inscollist_opt ::=",
91782  /* 181 */ "inscollist_opt ::= LP inscollist RP",
91783  /* 182 */ "inscollist ::= inscollist COMMA nm",
91784  /* 183 */ "inscollist ::= nm",
91785  /* 184 */ "expr ::= term",
91786  /* 185 */ "expr ::= LP expr RP",
91787  /* 186 */ "term ::= NULL",
91788  /* 187 */ "expr ::= id",
91789  /* 188 */ "expr ::= JOIN_KW",
91790  /* 189 */ "expr ::= nm DOT nm",
91791  /* 190 */ "expr ::= nm DOT nm DOT nm",
91792  /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
91793  /* 192 */ "term ::= STRING",
91794  /* 193 */ "expr ::= REGISTER",
91795  /* 194 */ "expr ::= VARIABLE",
91796  /* 195 */ "expr ::= expr COLLATE ids",
91797  /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
91798  /* 197 */ "expr ::= ID LP distinct exprlist RP",
91799  /* 198 */ "expr ::= ID LP STAR RP",
91800  /* 199 */ "term ::= CTIME_KW",
91801  /* 200 */ "expr ::= expr AND expr",
91802  /* 201 */ "expr ::= expr OR expr",
91803  /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
91804  /* 203 */ "expr ::= expr EQ|NE expr",
91805  /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
91806  /* 205 */ "expr ::= expr PLUS|MINUS expr",
91807  /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
91808  /* 207 */ "expr ::= expr CONCAT expr",
91809  /* 208 */ "likeop ::= LIKE_KW",
91810  /* 209 */ "likeop ::= NOT LIKE_KW",
91811  /* 210 */ "likeop ::= MATCH",
91812  /* 211 */ "likeop ::= NOT MATCH",
91813  /* 212 */ "escape ::= ESCAPE expr",
91814  /* 213 */ "escape ::=",
91815  /* 214 */ "expr ::= expr likeop expr escape",
91816  /* 215 */ "expr ::= expr ISNULL|NOTNULL",
91817  /* 216 */ "expr ::= expr NOT NULL",
91818  /* 217 */ "expr ::= expr IS expr",
91819  /* 218 */ "expr ::= expr IS NOT expr",
91820  /* 219 */ "expr ::= NOT expr",
91821  /* 220 */ "expr ::= BITNOT expr",
91822  /* 221 */ "expr ::= MINUS expr",
91823  /* 222 */ "expr ::= PLUS expr",
91824  /* 223 */ "between_op ::= BETWEEN",
91825  /* 224 */ "between_op ::= NOT BETWEEN",
91826  /* 225 */ "expr ::= expr between_op expr AND expr",
91827  /* 226 */ "in_op ::= IN",
91828  /* 227 */ "in_op ::= NOT IN",
91829  /* 228 */ "expr ::= expr in_op LP exprlist RP",
91830  /* 229 */ "expr ::= LP select RP",
91831  /* 230 */ "expr ::= expr in_op LP select RP",
91832  /* 231 */ "expr ::= expr in_op nm dbnm",
91833  /* 232 */ "expr ::= EXISTS LP select RP",
91834  /* 233 */ "expr ::= CASE case_operand case_exprlist case_else END",
91835  /* 234 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
91836  /* 235 */ "case_exprlist ::= WHEN expr THEN expr",
91837  /* 236 */ "case_else ::= ELSE expr",
91838  /* 237 */ "case_else ::=",
91839  /* 238 */ "case_operand ::= expr",
91840  /* 239 */ "case_operand ::=",
91841  /* 240 */ "exprlist ::= nexprlist",
91842  /* 241 */ "exprlist ::=",
91843  /* 242 */ "nexprlist ::= nexprlist COMMA expr",
91844  /* 243 */ "nexprlist ::= expr",
91845  /* 244 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
91846  /* 245 */ "uniqueflag ::= UNIQUE",
91847  /* 246 */ "uniqueflag ::=",
91848  /* 247 */ "idxlist_opt ::=",
91849  /* 248 */ "idxlist_opt ::= LP idxlist RP",
91850  /* 249 */ "idxlist ::= idxlist COMMA nm collate sortorder",
91851  /* 250 */ "idxlist ::= nm collate sortorder",
91852  /* 251 */ "collate ::=",
91853  /* 252 */ "collate ::= COLLATE ids",
91854  /* 253 */ "cmd ::= DROP INDEX ifexists fullname",
91855  /* 254 */ "cmd ::= VACUUM",
91856  /* 255 */ "cmd ::= VACUUM nm",
91857  /* 256 */ "cmd ::= PRAGMA nm dbnm",
91858  /* 257 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
91859  /* 258 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
91860  /* 259 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
91861  /* 260 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
91862  /* 261 */ "nmnum ::= plus_num",
91863  /* 262 */ "nmnum ::= nm",
91864  /* 263 */ "nmnum ::= ON",
91865  /* 264 */ "nmnum ::= DELETE",
91866  /* 265 */ "nmnum ::= DEFAULT",
91867  /* 266 */ "plus_num ::= plus_opt number",
91868  /* 267 */ "minus_num ::= MINUS number",
91869  /* 268 */ "number ::= INTEGER|FLOAT",
91870  /* 269 */ "plus_opt ::= PLUS",
91871  /* 270 */ "plus_opt ::=",
91872  /* 271 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
91873  /* 272 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
91874  /* 273 */ "trigger_time ::= BEFORE",
91875  /* 274 */ "trigger_time ::= AFTER",
91876  /* 275 */ "trigger_time ::= INSTEAD OF",
91877  /* 276 */ "trigger_time ::=",
91878  /* 277 */ "trigger_event ::= DELETE|INSERT",
91879  /* 278 */ "trigger_event ::= UPDATE",
91880  /* 279 */ "trigger_event ::= UPDATE OF inscollist",
91881  /* 280 */ "foreach_clause ::=",
91882  /* 281 */ "foreach_clause ::= FOR EACH ROW",
91883  /* 282 */ "when_clause ::=",
91884  /* 283 */ "when_clause ::= WHEN expr",
91885  /* 284 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
91886  /* 285 */ "trigger_cmd_list ::= trigger_cmd SEMI",
91887  /* 286 */ "trnm ::= nm",
91888  /* 287 */ "trnm ::= nm DOT nm",
91889  /* 288 */ "tridxby ::=",
91890  /* 289 */ "tridxby ::= INDEXED BY nm",
91891  /* 290 */ "tridxby ::= NOT INDEXED",
91892  /* 291 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
91893  /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
91894  /* 293 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
91895  /* 294 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
91896  /* 295 */ "trigger_cmd ::= select",
91897  /* 296 */ "expr ::= RAISE LP IGNORE RP",
91898  /* 297 */ "expr ::= RAISE LP raisetype COMMA nm RP",
91899  /* 298 */ "raisetype ::= ROLLBACK",
91900  /* 299 */ "raisetype ::= ABORT",
91901  /* 300 */ "raisetype ::= FAIL",
91902  /* 301 */ "cmd ::= DROP TRIGGER ifexists fullname",
91903  /* 302 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
91904  /* 303 */ "cmd ::= DETACH database_kw_opt expr",
91905  /* 304 */ "key_opt ::=",
91906  /* 305 */ "key_opt ::= KEY expr",
91907  /* 306 */ "database_kw_opt ::= DATABASE",
91908  /* 307 */ "database_kw_opt ::=",
91909  /* 308 */ "cmd ::= REINDEX",
91910  /* 309 */ "cmd ::= REINDEX nm dbnm",
91911  /* 310 */ "cmd ::= ANALYZE",
91912  /* 311 */ "cmd ::= ANALYZE nm dbnm",
91913  /* 312 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
91914  /* 313 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
91915  /* 314 */ "add_column_fullname ::= fullname",
91916  /* 315 */ "kwcolumn_opt ::=",
91917  /* 316 */ "kwcolumn_opt ::= COLUMNKW",
91918  /* 317 */ "cmd ::= create_vtab",
91919  /* 318 */ "cmd ::= create_vtab LP vtabarglist RP",
91920  /* 319 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
91921  /* 320 */ "vtabarglist ::= vtabarg",
91922  /* 321 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
91923  /* 322 */ "vtabarg ::=",
91924  /* 323 */ "vtabarg ::= vtabarg vtabargtoken",
91925  /* 324 */ "vtabargtoken ::= ANY",
91926  /* 325 */ "vtabargtoken ::= lp anylist RP",
91927  /* 326 */ "lp ::= LP",
91928  /* 327 */ "anylist ::=",
91929  /* 328 */ "anylist ::= anylist LP anylist RP",
91930  /* 329 */ "anylist ::= anylist ANY",
91931 };
91932 #endif /* NDEBUG */
91933
91934
91935 #if YYSTACKDEPTH<=0
91936 /*
91937 ** Try to increase the size of the parser stack.
91938 */
91939 static void yyGrowStack(yyParser *p){
91940   int newSize;
91941   yyStackEntry *pNew;
91942
91943   newSize = p->yystksz*2 + 100;
91944   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
91945   if( pNew ){
91946     p->yystack = pNew;
91947     p->yystksz = newSize;
91948 #ifndef NDEBUG
91949     if( yyTraceFILE ){
91950       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
91951               yyTracePrompt, p->yystksz);
91952     }
91953 #endif
91954   }
91955 }
91956 #endif
91957
91958 /* 
91959 ** This function allocates a new parser.
91960 ** The only argument is a pointer to a function which works like
91961 ** malloc.
91962 **
91963 ** Inputs:
91964 ** A pointer to the function used to allocate memory.
91965 **
91966 ** Outputs:
91967 ** A pointer to a parser.  This pointer is used in subsequent calls
91968 ** to sqlite3Parser and sqlite3ParserFree.
91969 */
91970 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
91971   yyParser *pParser;
91972   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
91973   if( pParser ){
91974     pParser->yyidx = -1;
91975 #ifdef YYTRACKMAXSTACKDEPTH
91976     pParser->yyidxMax = 0;
91977 #endif
91978 #if YYSTACKDEPTH<=0
91979     pParser->yystack = NULL;
91980     pParser->yystksz = 0;
91981     yyGrowStack(pParser);
91982 #endif
91983   }
91984   return pParser;
91985 }
91986
91987 /* The following function deletes the value associated with a
91988 ** symbol.  The symbol can be either a terminal or nonterminal.
91989 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
91990 ** the value.
91991 */
91992 static void yy_destructor(
91993   yyParser *yypParser,    /* The parser */
91994   YYCODETYPE yymajor,     /* Type code for object to destroy */
91995   YYMINORTYPE *yypminor   /* The object to be destroyed */
91996 ){
91997   sqlite3ParserARG_FETCH;
91998   switch( yymajor ){
91999     /* Here is inserted the actions which take place when a
92000     ** terminal or non-terminal is destroyed.  This can happen
92001     ** when the symbol is popped from the stack during a
92002     ** reduce or during error processing or when a parser is 
92003     ** being destroyed before it is finished parsing.
92004     **
92005     ** Note: during a reduce, the only symbols destroyed are those
92006     ** which appear on the RHS of the rule, but which are not used
92007     ** inside the C code.
92008     */
92009     case 160: /* select */
92010     case 194: /* oneselect */
92011 {
92012 sqlite3SelectDelete(pParse->db, (yypminor->yy3));
92013 }
92014       break;
92015     case 174: /* term */
92016     case 175: /* expr */
92017     case 223: /* escape */
92018 {
92019 sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
92020 }
92021       break;
92022     case 179: /* idxlist_opt */
92023     case 187: /* idxlist */
92024     case 197: /* selcollist */
92025     case 200: /* groupby_opt */
92026     case 202: /* orderby_opt */
92027     case 204: /* sclp */
92028     case 214: /* sortlist */
92029     case 216: /* nexprlist */
92030     case 217: /* setlist */
92031     case 220: /* itemlist */
92032     case 221: /* exprlist */
92033     case 227: /* case_exprlist */
92034 {
92035 sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
92036 }
92037       break;
92038     case 193: /* fullname */
92039     case 198: /* from */
92040     case 206: /* seltablist */
92041     case 207: /* stl_prefix */
92042 {
92043 sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
92044 }
92045       break;
92046     case 199: /* where_opt */
92047     case 201: /* having_opt */
92048     case 210: /* on_opt */
92049     case 215: /* sortitem */
92050     case 226: /* case_operand */
92051     case 228: /* case_else */
92052     case 239: /* when_clause */
92053     case 244: /* key_opt */
92054 {
92055 sqlite3ExprDelete(pParse->db, (yypminor->yy132));
92056 }
92057       break;
92058     case 211: /* using_opt */
92059     case 213: /* inscollist */
92060     case 219: /* inscollist_opt */
92061 {
92062 sqlite3IdListDelete(pParse->db, (yypminor->yy408));
92063 }
92064       break;
92065     case 235: /* trigger_cmd_list */
92066     case 240: /* trigger_cmd */
92067 {
92068 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
92069 }
92070       break;
92071     case 237: /* trigger_event */
92072 {
92073 sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
92074 }
92075       break;
92076     default:  break;   /* If no destructor action specified: do nothing */
92077   }
92078 }
92079
92080 /*
92081 ** Pop the parser's stack once.
92082 **
92083 ** If there is a destructor routine associated with the token which
92084 ** is popped from the stack, then call it.
92085 **
92086 ** Return the major token number for the symbol popped.
92087 */
92088 static int yy_pop_parser_stack(yyParser *pParser){
92089   YYCODETYPE yymajor;
92090   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
92091
92092   /* There is no mechanism by which the parser stack can be popped below
92093   ** empty in SQLite.  */
92094   if( NEVER(pParser->yyidx<0) ) return 0;
92095 #ifndef NDEBUG
92096   if( yyTraceFILE && pParser->yyidx>=0 ){
92097     fprintf(yyTraceFILE,"%sPopping %s\n",
92098       yyTracePrompt,
92099       yyTokenName[yytos->major]);
92100   }
92101 #endif
92102   yymajor = yytos->major;
92103   yy_destructor(pParser, yymajor, &yytos->minor);
92104   pParser->yyidx--;
92105   return yymajor;
92106 }
92107
92108 /* 
92109 ** Deallocate and destroy a parser.  Destructors are all called for
92110 ** all stack elements before shutting the parser down.
92111 **
92112 ** Inputs:
92113 ** <ul>
92114 ** <li>  A pointer to the parser.  This should be a pointer
92115 **       obtained from sqlite3ParserAlloc.
92116 ** <li>  A pointer to a function used to reclaim memory obtained
92117 **       from malloc.
92118 ** </ul>
92119 */
92120 SQLITE_PRIVATE void sqlite3ParserFree(
92121   void *p,                    /* The parser to be deleted */
92122   void (*freeProc)(void*)     /* Function used to reclaim memory */
92123 ){
92124   yyParser *pParser = (yyParser*)p;
92125   /* In SQLite, we never try to destroy a parser that was not successfully
92126   ** created in the first place. */
92127   if( NEVER(pParser==0) ) return;
92128   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
92129 #if YYSTACKDEPTH<=0
92130   free(pParser->yystack);
92131 #endif
92132   (*freeProc)((void*)pParser);
92133 }
92134
92135 /*
92136 ** Return the peak depth of the stack for a parser.
92137 */
92138 #ifdef YYTRACKMAXSTACKDEPTH
92139 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
92140   yyParser *pParser = (yyParser*)p;
92141   return pParser->yyidxMax;
92142 }
92143 #endif
92144
92145 /*
92146 ** Find the appropriate action for a parser given the terminal
92147 ** look-ahead token iLookAhead.
92148 **
92149 ** If the look-ahead token is YYNOCODE, then check to see if the action is
92150 ** independent of the look-ahead.  If it is, return the action, otherwise
92151 ** return YY_NO_ACTION.
92152 */
92153 static int yy_find_shift_action(
92154   yyParser *pParser,        /* The parser */
92155   YYCODETYPE iLookAhead     /* The look-ahead token */
92156 ){
92157   int i;
92158   int stateno = pParser->yystack[pParser->yyidx].stateno;
92159  
92160   if( stateno>YY_SHIFT_COUNT
92161    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
92162     return yy_default[stateno];
92163   }
92164   assert( iLookAhead!=YYNOCODE );
92165   i += iLookAhead;
92166   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
92167     if( iLookAhead>0 ){
92168 #ifdef YYFALLBACK
92169       YYCODETYPE iFallback;            /* Fallback token */
92170       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
92171              && (iFallback = yyFallback[iLookAhead])!=0 ){
92172 #ifndef NDEBUG
92173         if( yyTraceFILE ){
92174           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
92175              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
92176         }
92177 #endif
92178         return yy_find_shift_action(pParser, iFallback);
92179       }
92180 #endif
92181 #ifdef YYWILDCARD
92182       {
92183         int j = i - iLookAhead + YYWILDCARD;
92184         if( 
92185 #if YY_SHIFT_MIN+YYWILDCARD<0
92186           j>=0 &&
92187 #endif
92188 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
92189           j<YY_ACTTAB_COUNT &&
92190 #endif
92191           yy_lookahead[j]==YYWILDCARD
92192         ){
92193 #ifndef NDEBUG
92194           if( yyTraceFILE ){
92195             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
92196                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
92197           }
92198 #endif /* NDEBUG */
92199           return yy_action[j];
92200         }
92201       }
92202 #endif /* YYWILDCARD */
92203     }
92204     return yy_default[stateno];
92205   }else{
92206     return yy_action[i];
92207   }
92208 }
92209
92210 /*
92211 ** Find the appropriate action for a parser given the non-terminal
92212 ** look-ahead token iLookAhead.
92213 **
92214 ** If the look-ahead token is YYNOCODE, then check to see if the action is
92215 ** independent of the look-ahead.  If it is, return the action, otherwise
92216 ** return YY_NO_ACTION.
92217 */
92218 static int yy_find_reduce_action(
92219   int stateno,              /* Current state number */
92220   YYCODETYPE iLookAhead     /* The look-ahead token */
92221 ){
92222   int i;
92223 #ifdef YYERRORSYMBOL
92224   if( stateno>YY_REDUCE_COUNT ){
92225     return yy_default[stateno];
92226   }
92227 #else
92228   assert( stateno<=YY_REDUCE_COUNT );
92229 #endif
92230   i = yy_reduce_ofst[stateno];
92231   assert( i!=YY_REDUCE_USE_DFLT );
92232   assert( iLookAhead!=YYNOCODE );
92233   i += iLookAhead;
92234 #ifdef YYERRORSYMBOL
92235   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
92236     return yy_default[stateno];
92237   }
92238 #else
92239   assert( i>=0 && i<YY_ACTTAB_COUNT );
92240   assert( yy_lookahead[i]==iLookAhead );
92241 #endif
92242   return yy_action[i];
92243 }
92244
92245 /*
92246 ** The following routine is called if the stack overflows.
92247 */
92248 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
92249    sqlite3ParserARG_FETCH;
92250    yypParser->yyidx--;
92251 #ifndef NDEBUG
92252    if( yyTraceFILE ){
92253      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
92254    }
92255 #endif
92256    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
92257    /* Here code is inserted which will execute if the parser
92258    ** stack every overflows */
92259
92260   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
92261   sqlite3ErrorMsg(pParse, "parser stack overflow");
92262   pParse->parseError = 1;
92263    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
92264 }
92265
92266 /*
92267 ** Perform a shift action.
92268 */
92269 static void yy_shift(
92270   yyParser *yypParser,          /* The parser to be shifted */
92271   int yyNewState,               /* The new state to shift in */
92272   int yyMajor,                  /* The major token to shift in */
92273   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
92274 ){
92275   yyStackEntry *yytos;
92276   yypParser->yyidx++;
92277 #ifdef YYTRACKMAXSTACKDEPTH
92278   if( yypParser->yyidx>yypParser->yyidxMax ){
92279     yypParser->yyidxMax = yypParser->yyidx;
92280   }
92281 #endif
92282 #if YYSTACKDEPTH>0 
92283   if( yypParser->yyidx>=YYSTACKDEPTH ){
92284     yyStackOverflow(yypParser, yypMinor);
92285     return;
92286   }
92287 #else
92288   if( yypParser->yyidx>=yypParser->yystksz ){
92289     yyGrowStack(yypParser);
92290     if( yypParser->yyidx>=yypParser->yystksz ){
92291       yyStackOverflow(yypParser, yypMinor);
92292       return;
92293     }
92294   }
92295 #endif
92296   yytos = &yypParser->yystack[yypParser->yyidx];
92297   yytos->stateno = (YYACTIONTYPE)yyNewState;
92298   yytos->major = (YYCODETYPE)yyMajor;
92299   yytos->minor = *yypMinor;
92300 #ifndef NDEBUG
92301   if( yyTraceFILE && yypParser->yyidx>0 ){
92302     int i;
92303     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
92304     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
92305     for(i=1; i<=yypParser->yyidx; i++)
92306       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
92307     fprintf(yyTraceFILE,"\n");
92308   }
92309 #endif
92310 }
92311
92312 /* The following table contains information about every rule that
92313 ** is used during the reduce.
92314 */
92315 static const struct {
92316   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
92317   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
92318 } yyRuleInfo[] = {
92319   { 142, 1 },
92320   { 143, 2 },
92321   { 143, 1 },
92322   { 144, 1 },
92323   { 144, 3 },
92324   { 145, 0 },
92325   { 145, 1 },
92326   { 145, 3 },
92327   { 146, 1 },
92328   { 147, 3 },
92329   { 149, 0 },
92330   { 149, 1 },
92331   { 149, 2 },
92332   { 148, 0 },
92333   { 148, 1 },
92334   { 148, 1 },
92335   { 148, 1 },
92336   { 147, 2 },
92337   { 147, 2 },
92338   { 147, 2 },
92339   { 151, 1 },
92340   { 151, 0 },
92341   { 147, 2 },
92342   { 147, 3 },
92343   { 147, 5 },
92344   { 147, 2 },
92345   { 152, 6 },
92346   { 154, 1 },
92347   { 156, 0 },
92348   { 156, 3 },
92349   { 155, 1 },
92350   { 155, 0 },
92351   { 153, 4 },
92352   { 153, 2 },
92353   { 158, 3 },
92354   { 158, 1 },
92355   { 161, 3 },
92356   { 162, 1 },
92357   { 165, 1 },
92358   { 165, 1 },
92359   { 166, 1 },
92360   { 150, 1 },
92361   { 150, 1 },
92362   { 150, 1 },
92363   { 163, 0 },
92364   { 163, 1 },
92365   { 167, 1 },
92366   { 167, 4 },
92367   { 167, 6 },
92368   { 168, 1 },
92369   { 168, 2 },
92370   { 169, 1 },
92371   { 169, 1 },
92372   { 164, 2 },
92373   { 164, 0 },
92374   { 172, 3 },
92375   { 172, 1 },
92376   { 173, 2 },
92377   { 173, 4 },
92378   { 173, 3 },
92379   { 173, 3 },
92380   { 173, 2 },
92381   { 173, 2 },
92382   { 173, 3 },
92383   { 173, 5 },
92384   { 173, 2 },
92385   { 173, 4 },
92386   { 173, 4 },
92387   { 173, 1 },
92388   { 173, 2 },
92389   { 178, 0 },
92390   { 178, 1 },
92391   { 180, 0 },
92392   { 180, 2 },
92393   { 182, 2 },
92394   { 182, 3 },
92395   { 182, 3 },
92396   { 182, 3 },
92397   { 183, 2 },
92398   { 183, 2 },
92399   { 183, 1 },
92400   { 183, 1 },
92401   { 183, 2 },
92402   { 181, 3 },
92403   { 181, 2 },
92404   { 184, 0 },
92405   { 184, 2 },
92406   { 184, 2 },
92407   { 159, 0 },
92408   { 159, 2 },
92409   { 185, 3 },
92410   { 185, 2 },
92411   { 185, 1 },
92412   { 186, 2 },
92413   { 186, 7 },
92414   { 186, 5 },
92415   { 186, 5 },
92416   { 186, 10 },
92417   { 188, 0 },
92418   { 188, 1 },
92419   { 176, 0 },
92420   { 176, 3 },
92421   { 189, 0 },
92422   { 189, 2 },
92423   { 190, 1 },
92424   { 190, 1 },
92425   { 190, 1 },
92426   { 147, 4 },
92427   { 192, 2 },
92428   { 192, 0 },
92429   { 147, 8 },
92430   { 147, 4 },
92431   { 147, 1 },
92432   { 160, 1 },
92433   { 160, 3 },
92434   { 195, 1 },
92435   { 195, 2 },
92436   { 195, 1 },
92437   { 194, 9 },
92438   { 196, 1 },
92439   { 196, 1 },
92440   { 196, 0 },
92441   { 204, 2 },
92442   { 204, 0 },
92443   { 197, 3 },
92444   { 197, 2 },
92445   { 197, 4 },
92446   { 205, 2 },
92447   { 205, 1 },
92448   { 205, 0 },
92449   { 198, 0 },
92450   { 198, 2 },
92451   { 207, 2 },
92452   { 207, 0 },
92453   { 206, 7 },
92454   { 206, 7 },
92455   { 206, 7 },
92456   { 157, 0 },
92457   { 157, 2 },
92458   { 193, 2 },
92459   { 208, 1 },
92460   { 208, 2 },
92461   { 208, 3 },
92462   { 208, 4 },
92463   { 210, 2 },
92464   { 210, 0 },
92465   { 209, 0 },
92466   { 209, 3 },
92467   { 209, 2 },
92468   { 211, 4 },
92469   { 211, 0 },
92470   { 202, 0 },
92471   { 202, 3 },
92472   { 214, 4 },
92473   { 214, 2 },
92474   { 215, 1 },
92475   { 177, 1 },
92476   { 177, 1 },
92477   { 177, 0 },
92478   { 200, 0 },
92479   { 200, 3 },
92480   { 201, 0 },
92481   { 201, 2 },
92482   { 203, 0 },
92483   { 203, 2 },
92484   { 203, 4 },
92485   { 203, 4 },
92486   { 147, 5 },
92487   { 199, 0 },
92488   { 199, 2 },
92489   { 147, 7 },
92490   { 217, 5 },
92491   { 217, 3 },
92492   { 147, 8 },
92493   { 147, 5 },
92494   { 147, 6 },
92495   { 218, 2 },
92496   { 218, 1 },
92497   { 220, 3 },
92498   { 220, 1 },
92499   { 219, 0 },
92500   { 219, 3 },
92501   { 213, 3 },
92502   { 213, 1 },
92503   { 175, 1 },
92504   { 175, 3 },
92505   { 174, 1 },
92506   { 175, 1 },
92507   { 175, 1 },
92508   { 175, 3 },
92509   { 175, 5 },
92510   { 174, 1 },
92511   { 174, 1 },
92512   { 175, 1 },
92513   { 175, 1 },
92514   { 175, 3 },
92515   { 175, 6 },
92516   { 175, 5 },
92517   { 175, 4 },
92518   { 174, 1 },
92519   { 175, 3 },
92520   { 175, 3 },
92521   { 175, 3 },
92522   { 175, 3 },
92523   { 175, 3 },
92524   { 175, 3 },
92525   { 175, 3 },
92526   { 175, 3 },
92527   { 222, 1 },
92528   { 222, 2 },
92529   { 222, 1 },
92530   { 222, 2 },
92531   { 223, 2 },
92532   { 223, 0 },
92533   { 175, 4 },
92534   { 175, 2 },
92535   { 175, 3 },
92536   { 175, 3 },
92537   { 175, 4 },
92538   { 175, 2 },
92539   { 175, 2 },
92540   { 175, 2 },
92541   { 175, 2 },
92542   { 224, 1 },
92543   { 224, 2 },
92544   { 175, 5 },
92545   { 225, 1 },
92546   { 225, 2 },
92547   { 175, 5 },
92548   { 175, 3 },
92549   { 175, 5 },
92550   { 175, 4 },
92551   { 175, 4 },
92552   { 175, 5 },
92553   { 227, 5 },
92554   { 227, 4 },
92555   { 228, 2 },
92556   { 228, 0 },
92557   { 226, 1 },
92558   { 226, 0 },
92559   { 221, 1 },
92560   { 221, 0 },
92561   { 216, 3 },
92562   { 216, 1 },
92563   { 147, 11 },
92564   { 229, 1 },
92565   { 229, 0 },
92566   { 179, 0 },
92567   { 179, 3 },
92568   { 187, 5 },
92569   { 187, 3 },
92570   { 230, 0 },
92571   { 230, 2 },
92572   { 147, 4 },
92573   { 147, 1 },
92574   { 147, 2 },
92575   { 147, 3 },
92576   { 147, 5 },
92577   { 147, 6 },
92578   { 147, 5 },
92579   { 147, 6 },
92580   { 231, 1 },
92581   { 231, 1 },
92582   { 231, 1 },
92583   { 231, 1 },
92584   { 231, 1 },
92585   { 170, 2 },
92586   { 171, 2 },
92587   { 233, 1 },
92588   { 232, 1 },
92589   { 232, 0 },
92590   { 147, 5 },
92591   { 234, 11 },
92592   { 236, 1 },
92593   { 236, 1 },
92594   { 236, 2 },
92595   { 236, 0 },
92596   { 237, 1 },
92597   { 237, 1 },
92598   { 237, 3 },
92599   { 238, 0 },
92600   { 238, 3 },
92601   { 239, 0 },
92602   { 239, 2 },
92603   { 235, 3 },
92604   { 235, 2 },
92605   { 241, 1 },
92606   { 241, 3 },
92607   { 242, 0 },
92608   { 242, 3 },
92609   { 242, 2 },
92610   { 240, 7 },
92611   { 240, 8 },
92612   { 240, 5 },
92613   { 240, 5 },
92614   { 240, 1 },
92615   { 175, 4 },
92616   { 175, 6 },
92617   { 191, 1 },
92618   { 191, 1 },
92619   { 191, 1 },
92620   { 147, 4 },
92621   { 147, 6 },
92622   { 147, 3 },
92623   { 244, 0 },
92624   { 244, 2 },
92625   { 243, 1 },
92626   { 243, 0 },
92627   { 147, 1 },
92628   { 147, 3 },
92629   { 147, 1 },
92630   { 147, 3 },
92631   { 147, 6 },
92632   { 147, 6 },
92633   { 245, 1 },
92634   { 246, 0 },
92635   { 246, 1 },
92636   { 147, 1 },
92637   { 147, 4 },
92638   { 247, 7 },
92639   { 248, 1 },
92640   { 248, 3 },
92641   { 249, 0 },
92642   { 249, 2 },
92643   { 250, 1 },
92644   { 250, 3 },
92645   { 251, 1 },
92646   { 252, 0 },
92647   { 252, 4 },
92648   { 252, 2 },
92649 };
92650
92651 static void yy_accept(yyParser*);  /* Forward Declaration */
92652
92653 /*
92654 ** Perform a reduce action and the shift that must immediately
92655 ** follow the reduce.
92656 */
92657 static void yy_reduce(
92658   yyParser *yypParser,         /* The parser */
92659   int yyruleno                 /* Number of the rule by which to reduce */
92660 ){
92661   int yygoto;                     /* The next state */
92662   int yyact;                      /* The next action */
92663   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
92664   yyStackEntry *yymsp;            /* The top of the parser's stack */
92665   int yysize;                     /* Amount to pop the stack */
92666   sqlite3ParserARG_FETCH;
92667   yymsp = &yypParser->yystack[yypParser->yyidx];
92668 #ifndef NDEBUG
92669   if( yyTraceFILE && yyruleno>=0 
92670         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
92671     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
92672       yyRuleName[yyruleno]);
92673   }
92674 #endif /* NDEBUG */
92675
92676   /* Silence complaints from purify about yygotominor being uninitialized
92677   ** in some cases when it is copied into the stack after the following
92678   ** switch.  yygotominor is uninitialized when a rule reduces that does
92679   ** not set the value of its left-hand side nonterminal.  Leaving the
92680   ** value of the nonterminal uninitialized is utterly harmless as long
92681   ** as the value is never used.  So really the only thing this code
92682   ** accomplishes is to quieten purify.  
92683   **
92684   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
92685   ** without this code, their parser segfaults.  I'm not sure what there
92686   ** parser is doing to make this happen.  This is the second bug report
92687   ** from wireshark this week.  Clearly they are stressing Lemon in ways
92688   ** that it has not been previously stressed...  (SQLite ticket #2172)
92689   */
92690   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
92691   yygotominor = yyzerominor;
92692
92693
92694   switch( yyruleno ){
92695   /* Beginning here are the reduction cases.  A typical example
92696   ** follows:
92697   **   case 0:
92698   **  #line <lineno> <grammarfile>
92699   **     { ... }           // User supplied code
92700   **  #line <lineno> <thisfile>
92701   **     break;
92702   */
92703       case 5: /* explain ::= */
92704 { sqlite3BeginParse(pParse, 0); }
92705         break;
92706       case 6: /* explain ::= EXPLAIN */
92707 { sqlite3BeginParse(pParse, 1); }
92708         break;
92709       case 7: /* explain ::= EXPLAIN QUERY PLAN */
92710 { sqlite3BeginParse(pParse, 2); }
92711         break;
92712       case 8: /* cmdx ::= cmd */
92713 { sqlite3FinishCoding(pParse); }
92714         break;
92715       case 9: /* cmd ::= BEGIN transtype trans_opt */
92716 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
92717         break;
92718       case 13: /* transtype ::= */
92719 {yygotominor.yy328 = TK_DEFERRED;}
92720         break;
92721       case 14: /* transtype ::= DEFERRED */
92722       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
92723       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
92724       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
92725       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
92726 {yygotominor.yy328 = yymsp[0].major;}
92727         break;
92728       case 17: /* cmd ::= COMMIT trans_opt */
92729       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
92730 {sqlite3CommitTransaction(pParse);}
92731         break;
92732       case 19: /* cmd ::= ROLLBACK trans_opt */
92733 {sqlite3RollbackTransaction(pParse);}
92734         break;
92735       case 22: /* cmd ::= SAVEPOINT nm */
92736 {
92737   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
92738 }
92739         break;
92740       case 23: /* cmd ::= RELEASE savepoint_opt nm */
92741 {
92742   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
92743 }
92744         break;
92745       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
92746 {
92747   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
92748 }
92749         break;
92750       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
92751 {
92752    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
92753 }
92754         break;
92755       case 27: /* createkw ::= CREATE */
92756 {
92757   pParse->db->lookaside.bEnabled = 0;
92758   yygotominor.yy0 = yymsp[0].minor.yy0;
92759 }
92760         break;
92761       case 28: /* ifnotexists ::= */
92762       case 31: /* temp ::= */ yytestcase(yyruleno==31);
92763       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
92764       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
92765       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
92766       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
92767       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
92768       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
92769       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
92770       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
92771       case 223: /* between_op ::= BETWEEN */ yytestcase(yyruleno==223);
92772       case 226: /* in_op ::= IN */ yytestcase(yyruleno==226);
92773 {yygotominor.yy328 = 0;}
92774         break;
92775       case 29: /* ifnotexists ::= IF NOT EXISTS */
92776       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
92777       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
92778       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
92779       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
92780       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
92781       case 224: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==224);
92782       case 227: /* in_op ::= NOT IN */ yytestcase(yyruleno==227);
92783 {yygotominor.yy328 = 1;}
92784         break;
92785       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
92786 {
92787   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
92788 }
92789         break;
92790       case 33: /* create_table_args ::= AS select */
92791 {
92792   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy3);
92793   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
92794 }
92795         break;
92796       case 36: /* column ::= columnid type carglist */
92797 {
92798   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
92799   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
92800 }
92801         break;
92802       case 37: /* columnid ::= nm */
92803 {
92804   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
92805   yygotominor.yy0 = yymsp[0].minor.yy0;
92806 }
92807         break;
92808       case 38: /* id ::= ID */
92809       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
92810       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
92811       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
92812       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
92813       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
92814       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
92815       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
92816       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
92817       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
92818       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
92819       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
92820       case 252: /* collate ::= COLLATE ids */ yytestcase(yyruleno==252);
92821       case 261: /* nmnum ::= plus_num */ yytestcase(yyruleno==261);
92822       case 262: /* nmnum ::= nm */ yytestcase(yyruleno==262);
92823       case 263: /* nmnum ::= ON */ yytestcase(yyruleno==263);
92824       case 264: /* nmnum ::= DELETE */ yytestcase(yyruleno==264);
92825       case 265: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==265);
92826       case 266: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==266);
92827       case 267: /* minus_num ::= MINUS number */ yytestcase(yyruleno==267);
92828       case 268: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==268);
92829       case 286: /* trnm ::= nm */ yytestcase(yyruleno==286);
92830 {yygotominor.yy0 = yymsp[0].minor.yy0;}
92831         break;
92832       case 45: /* type ::= typetoken */
92833 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
92834         break;
92835       case 47: /* typetoken ::= typename LP signed RP */
92836 {
92837   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
92838   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
92839 }
92840         break;
92841       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
92842 {
92843   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
92844   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
92845 }
92846         break;
92847       case 50: /* typename ::= typename ids */
92848 {yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
92849         break;
92850       case 57: /* ccons ::= DEFAULT term */
92851       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
92852 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
92853         break;
92854       case 58: /* ccons ::= DEFAULT LP expr RP */
92855 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
92856         break;
92857       case 60: /* ccons ::= DEFAULT MINUS term */
92858 {
92859   ExprSpan v;
92860   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
92861   v.zStart = yymsp[-1].minor.yy0.z;
92862   v.zEnd = yymsp[0].minor.yy346.zEnd;
92863   sqlite3AddDefaultValue(pParse,&v);
92864 }
92865         break;
92866       case 61: /* ccons ::= DEFAULT id */
92867 {
92868   ExprSpan v;
92869   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
92870   sqlite3AddDefaultValue(pParse,&v);
92871 }
92872         break;
92873       case 63: /* ccons ::= NOT NULL onconf */
92874 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
92875         break;
92876       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
92877 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
92878         break;
92879       case 65: /* ccons ::= UNIQUE onconf */
92880 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
92881         break;
92882       case 66: /* ccons ::= CHECK LP expr RP */
92883 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
92884         break;
92885       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
92886 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
92887         break;
92888       case 68: /* ccons ::= defer_subclause */
92889 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
92890         break;
92891       case 69: /* ccons ::= COLLATE ids */
92892 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
92893         break;
92894       case 72: /* refargs ::= */
92895 { yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
92896         break;
92897       case 73: /* refargs ::= refargs refarg */
92898 { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
92899         break;
92900       case 74: /* refarg ::= MATCH nm */
92901       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
92902 { yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
92903         break;
92904       case 76: /* refarg ::= ON DELETE refact */
92905 { yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
92906         break;
92907       case 77: /* refarg ::= ON UPDATE refact */
92908 { yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
92909         break;
92910       case 78: /* refact ::= SET NULL */
92911 { yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
92912         break;
92913       case 79: /* refact ::= SET DEFAULT */
92914 { yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
92915         break;
92916       case 80: /* refact ::= CASCADE */
92917 { yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
92918         break;
92919       case 81: /* refact ::= RESTRICT */
92920 { yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
92921         break;
92922       case 82: /* refact ::= NO ACTION */
92923 { yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
92924         break;
92925       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
92926       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
92927       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
92928       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
92929 {yygotominor.yy328 = yymsp[0].minor.yy328;}
92930         break;
92931       case 88: /* conslist_opt ::= */
92932 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
92933         break;
92934       case 89: /* conslist_opt ::= COMMA conslist */
92935 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
92936         break;
92937       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
92938 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
92939         break;
92940       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
92941 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
92942         break;
92943       case 96: /* tcons ::= CHECK LP expr RP onconf */
92944 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
92945         break;
92946       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
92947 {
92948     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
92949     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
92950 }
92951         break;
92952       case 100: /* onconf ::= */
92953 {yygotominor.yy328 = OE_Default;}
92954         break;
92955       case 102: /* orconf ::= */
92956 {yygotominor.yy186 = OE_Default;}
92957         break;
92958       case 103: /* orconf ::= OR resolvetype */
92959 {yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
92960         break;
92961       case 105: /* resolvetype ::= IGNORE */
92962 {yygotominor.yy328 = OE_Ignore;}
92963         break;
92964       case 106: /* resolvetype ::= REPLACE */
92965 {yygotominor.yy328 = OE_Replace;}
92966         break;
92967       case 107: /* cmd ::= DROP TABLE ifexists fullname */
92968 {
92969   sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
92970 }
92971         break;
92972       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
92973 {
92974   sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy3, yymsp[-6].minor.yy328, yymsp[-4].minor.yy328);
92975 }
92976         break;
92977       case 111: /* cmd ::= DROP VIEW ifexists fullname */
92978 {
92979   sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
92980 }
92981         break;
92982       case 112: /* cmd ::= select */
92983 {
92984   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
92985   sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
92986   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
92987 }
92988         break;
92989       case 113: /* select ::= oneselect */
92990 {yygotominor.yy3 = yymsp[0].minor.yy3;}
92991         break;
92992       case 114: /* select ::= select multiselect_op oneselect */
92993 {
92994   if( yymsp[0].minor.yy3 ){
92995     yymsp[0].minor.yy3->op = (u8)yymsp[-1].minor.yy328;
92996     yymsp[0].minor.yy3->pPrior = yymsp[-2].minor.yy3;
92997   }else{
92998     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
92999   }
93000   yygotominor.yy3 = yymsp[0].minor.yy3;
93001 }
93002         break;
93003       case 116: /* multiselect_op ::= UNION ALL */
93004 {yygotominor.yy328 = TK_ALL;}
93005         break;
93006       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
93007 {
93008   yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy14,yymsp[-5].minor.yy65,yymsp[-4].minor.yy132,yymsp[-3].minor.yy14,yymsp[-2].minor.yy132,yymsp[-1].minor.yy14,yymsp[-7].minor.yy328,yymsp[0].minor.yy476.pLimit,yymsp[0].minor.yy476.pOffset);
93009 }
93010         break;
93011       case 122: /* sclp ::= selcollist COMMA */
93012       case 248: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==248);
93013 {yygotominor.yy14 = yymsp[-1].minor.yy14;}
93014         break;
93015       case 123: /* sclp ::= */
93016       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
93017       case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
93018       case 241: /* exprlist ::= */ yytestcase(yyruleno==241);
93019       case 247: /* idxlist_opt ::= */ yytestcase(yyruleno==247);
93020 {yygotominor.yy14 = 0;}
93021         break;
93022       case 124: /* selcollist ::= sclp expr as */
93023 {
93024    yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
93025    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
93026    sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
93027 }
93028         break;
93029       case 125: /* selcollist ::= sclp STAR */
93030 {
93031   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
93032   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
93033 }
93034         break;
93035       case 126: /* selcollist ::= sclp nm DOT STAR */
93036 {
93037   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
93038   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
93039   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
93040   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
93041 }
93042         break;
93043       case 129: /* as ::= */
93044 {yygotominor.yy0.n = 0;}
93045         break;
93046       case 130: /* from ::= */
93047 {yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
93048         break;
93049       case 131: /* from ::= FROM seltablist */
93050 {
93051   yygotominor.yy65 = yymsp[0].minor.yy65;
93052   sqlite3SrcListShiftJoinType(yygotominor.yy65);
93053 }
93054         break;
93055       case 132: /* stl_prefix ::= seltablist joinop */
93056 {
93057    yygotominor.yy65 = yymsp[-1].minor.yy65;
93058    if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
93059 }
93060         break;
93061       case 133: /* stl_prefix ::= */
93062 {yygotominor.yy65 = 0;}
93063         break;
93064       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
93065 {
93066   yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
93067   sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
93068 }
93069         break;
93070       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
93071 {
93072     yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy3,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
93073   }
93074         break;
93075       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
93076 {
93077     if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
93078       yygotominor.yy65 = yymsp[-4].minor.yy65;
93079     }else{
93080       Select *pSubquery;
93081       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
93082       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,0,0,0);
93083       yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
93084     }
93085   }
93086         break;
93087       case 137: /* dbnm ::= */
93088       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
93089 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
93090         break;
93091       case 139: /* fullname ::= nm dbnm */
93092 {yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
93093         break;
93094       case 140: /* joinop ::= COMMA|JOIN */
93095 { yygotominor.yy328 = JT_INNER; }
93096         break;
93097       case 141: /* joinop ::= JOIN_KW JOIN */
93098 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
93099         break;
93100       case 142: /* joinop ::= JOIN_KW nm JOIN */
93101 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
93102         break;
93103       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
93104 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
93105         break;
93106       case 144: /* on_opt ::= ON expr */
93107       case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
93108       case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
93109       case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
93110       case 236: /* case_else ::= ELSE expr */ yytestcase(yyruleno==236);
93111       case 238: /* case_operand ::= expr */ yytestcase(yyruleno==238);
93112 {yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
93113         break;
93114       case 145: /* on_opt ::= */
93115       case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
93116       case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
93117       case 237: /* case_else ::= */ yytestcase(yyruleno==237);
93118       case 239: /* case_operand ::= */ yytestcase(yyruleno==239);
93119 {yygotominor.yy132 = 0;}
93120         break;
93121       case 148: /* indexed_opt ::= NOT INDEXED */
93122 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
93123         break;
93124       case 149: /* using_opt ::= USING LP inscollist RP */
93125       case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
93126 {yygotominor.yy408 = yymsp[-1].minor.yy408;}
93127         break;
93128       case 150: /* using_opt ::= */
93129       case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
93130 {yygotominor.yy408 = 0;}
93131         break;
93132       case 152: /* orderby_opt ::= ORDER BY sortlist */
93133       case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
93134       case 240: /* exprlist ::= nexprlist */ yytestcase(yyruleno==240);
93135 {yygotominor.yy14 = yymsp[0].minor.yy14;}
93136         break;
93137       case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
93138 {
93139   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy132);
93140   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
93141 }
93142         break;
93143       case 154: /* sortlist ::= sortitem sortorder */
93144 {
93145   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy132);
93146   if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
93147 }
93148         break;
93149       case 156: /* sortorder ::= ASC */
93150       case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
93151 {yygotominor.yy328 = SQLITE_SO_ASC;}
93152         break;
93153       case 157: /* sortorder ::= DESC */
93154 {yygotominor.yy328 = SQLITE_SO_DESC;}
93155         break;
93156       case 163: /* limit_opt ::= */
93157 {yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
93158         break;
93159       case 164: /* limit_opt ::= LIMIT expr */
93160 {yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
93161         break;
93162       case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
93163 {yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
93164         break;
93165       case 166: /* limit_opt ::= LIMIT expr COMMA expr */
93166 {yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
93167         break;
93168       case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
93169 {
93170   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
93171   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
93172 }
93173         break;
93174       case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
93175 {
93176   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
93177   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list"); 
93178   sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
93179 }
93180         break;
93181       case 171: /* setlist ::= setlist COMMA nm EQ expr */
93182 {
93183   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
93184   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
93185 }
93186         break;
93187       case 172: /* setlist ::= nm EQ expr */
93188 {
93189   yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
93190   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
93191 }
93192         break;
93193       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
93194 {sqlite3Insert(pParse, yymsp[-5].minor.yy65, yymsp[-1].minor.yy14, 0, yymsp[-4].minor.yy408, yymsp[-7].minor.yy186);}
93195         break;
93196       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
93197 {sqlite3Insert(pParse, yymsp[-2].minor.yy65, 0, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);}
93198         break;
93199       case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
93200 {sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);}
93201         break;
93202       case 176: /* insert_cmd ::= INSERT orconf */
93203 {yygotominor.yy186 = yymsp[0].minor.yy186;}
93204         break;
93205       case 177: /* insert_cmd ::= REPLACE */
93206 {yygotominor.yy186 = OE_Replace;}
93207         break;
93208       case 178: /* itemlist ::= itemlist COMMA expr */
93209       case 242: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==242);
93210 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
93211         break;
93212       case 179: /* itemlist ::= expr */
93213       case 243: /* nexprlist ::= expr */ yytestcase(yyruleno==243);
93214 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
93215         break;
93216       case 182: /* inscollist ::= inscollist COMMA nm */
93217 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
93218         break;
93219       case 183: /* inscollist ::= nm */
93220 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
93221         break;
93222       case 184: /* expr ::= term */
93223       case 212: /* escape ::= ESCAPE expr */ yytestcase(yyruleno==212);
93224 {yygotominor.yy346 = yymsp[0].minor.yy346;}
93225         break;
93226       case 185: /* expr ::= LP expr RP */
93227 {yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
93228         break;
93229       case 186: /* term ::= NULL */
93230       case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
93231       case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
93232 {spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
93233         break;
93234       case 187: /* expr ::= id */
93235       case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
93236 {spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
93237         break;
93238       case 189: /* expr ::= nm DOT nm */
93239 {
93240   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
93241   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
93242   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
93243   spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
93244 }
93245         break;
93246       case 190: /* expr ::= nm DOT nm DOT nm */
93247 {
93248   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
93249   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
93250   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
93251   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
93252   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
93253   spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
93254 }
93255         break;
93256       case 193: /* expr ::= REGISTER */
93257 {
93258   /* When doing a nested parse, one can include terms in an expression
93259   ** that look like this:   #1 #2 ...  These terms refer to registers
93260   ** in the virtual machine.  #N is the N-th register. */
93261   if( pParse->nested==0 ){
93262     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
93263     yygotominor.yy346.pExpr = 0;
93264   }else{
93265     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
93266     if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
93267   }
93268   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
93269 }
93270         break;
93271       case 194: /* expr ::= VARIABLE */
93272 {
93273   spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
93274   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
93275   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
93276 }
93277         break;
93278       case 195: /* expr ::= expr COLLATE ids */
93279 {
93280   yygotominor.yy346.pExpr = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
93281   yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
93282   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93283 }
93284         break;
93285       case 196: /* expr ::= CAST LP expr AS typetoken RP */
93286 {
93287   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
93288   spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
93289 }
93290         break;
93291       case 197: /* expr ::= ID LP distinct exprlist RP */
93292 {
93293   if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
93294     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
93295   }
93296   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
93297   spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
93298   if( yymsp[-2].minor.yy328 && yygotominor.yy346.pExpr ){
93299     yygotominor.yy346.pExpr->flags |= EP_Distinct;
93300   }
93301 }
93302         break;
93303       case 198: /* expr ::= ID LP STAR RP */
93304 {
93305   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
93306   spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
93307 }
93308         break;
93309       case 199: /* term ::= CTIME_KW */
93310 {
93311   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
93312   ** treated as functions that return constants */
93313   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
93314   if( yygotominor.yy346.pExpr ){
93315     yygotominor.yy346.pExpr->op = TK_CONST_FUNC;  
93316   }
93317   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
93318 }
93319         break;
93320       case 200: /* expr ::= expr AND expr */
93321       case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
93322       case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
93323       case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
93324       case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
93325       case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
93326       case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
93327       case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
93328 {spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
93329         break;
93330       case 208: /* likeop ::= LIKE_KW */
93331       case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
93332 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 0;}
93333         break;
93334       case 209: /* likeop ::= NOT LIKE_KW */
93335       case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
93336 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 1;}
93337         break;
93338       case 213: /* escape ::= */
93339 {memset(&yygotominor.yy346,0,sizeof(yygotominor.yy346));}
93340         break;
93341       case 214: /* expr ::= expr likeop expr escape */
93342 {
93343   ExprList *pList;
93344   pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy346.pExpr);
93345   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy346.pExpr);
93346   if( yymsp[0].minor.yy346.pExpr ){
93347     pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
93348   }
93349   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy96.eOperator);
93350   if( yymsp[-2].minor.yy96.not ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93351   yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
93352   yygotominor.yy346.zEnd = yymsp[-1].minor.yy346.zEnd;
93353   if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
93354 }
93355         break;
93356       case 215: /* expr ::= expr ISNULL|NOTNULL */
93357 {spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
93358         break;
93359       case 216: /* expr ::= expr NOT NULL */
93360 {spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
93361         break;
93362       case 217: /* expr ::= expr IS expr */
93363 {
93364   spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
93365   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
93366 }
93367         break;
93368       case 218: /* expr ::= expr IS NOT expr */
93369 {
93370   spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
93371   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
93372 }
93373         break;
93374       case 219: /* expr ::= NOT expr */
93375       case 220: /* expr ::= BITNOT expr */ yytestcase(yyruleno==220);
93376 {spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
93377         break;
93378       case 221: /* expr ::= MINUS expr */
93379 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
93380         break;
93381       case 222: /* expr ::= PLUS expr */
93382 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
93383         break;
93384       case 225: /* expr ::= expr between_op expr AND expr */
93385 {
93386   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
93387   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
93388   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
93389   if( yygotominor.yy346.pExpr ){
93390     yygotominor.yy346.pExpr->x.pList = pList;
93391   }else{
93392     sqlite3ExprListDelete(pParse->db, pList);
93393   } 
93394   if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93395   yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
93396   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
93397 }
93398         break;
93399       case 228: /* expr ::= expr in_op LP exprlist RP */
93400 {
93401     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
93402     if( yygotominor.yy346.pExpr ){
93403       yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
93404       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93405     }else{
93406       sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
93407     }
93408     if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93409     yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
93410     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93411   }
93412         break;
93413       case 229: /* expr ::= LP select RP */
93414 {
93415     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
93416     if( yygotominor.yy346.pExpr ){
93417       yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
93418       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
93419       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93420     }else{
93421       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
93422     }
93423     yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
93424     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93425   }
93426         break;
93427       case 230: /* expr ::= expr in_op LP select RP */
93428 {
93429     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
93430     if( yygotominor.yy346.pExpr ){
93431       yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
93432       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
93433       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93434     }else{
93435       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
93436     }
93437     if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93438     yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
93439     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93440   }
93441         break;
93442       case 231: /* expr ::= expr in_op nm dbnm */
93443 {
93444     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
93445     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
93446     if( yygotominor.yy346.pExpr ){
93447       yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
93448       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
93449       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93450     }else{
93451       sqlite3SrcListDelete(pParse->db, pSrc);
93452     }
93453     if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93454     yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
93455     yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
93456   }
93457         break;
93458       case 232: /* expr ::= EXISTS LP select RP */
93459 {
93460     Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
93461     if( p ){
93462       p->x.pSelect = yymsp[-1].minor.yy3;
93463       ExprSetProperty(p, EP_xIsSelect);
93464       sqlite3ExprSetHeight(pParse, p);
93465     }else{
93466       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
93467     }
93468     yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
93469     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93470   }
93471         break;
93472       case 233: /* expr ::= CASE case_operand case_exprlist case_else END */
93473 {
93474   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, yymsp[-1].minor.yy132, 0);
93475   if( yygotominor.yy346.pExpr ){
93476     yygotominor.yy346.pExpr->x.pList = yymsp[-2].minor.yy14;
93477     sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93478   }else{
93479     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
93480   }
93481   yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
93482   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93483 }
93484         break;
93485       case 234: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
93486 {
93487   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
93488   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
93489 }
93490         break;
93491       case 235: /* case_exprlist ::= WHEN expr THEN expr */
93492 {
93493   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
93494   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
93495 }
93496         break;
93497       case 244: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
93498 {
93499   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
93500                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy14, yymsp[-9].minor.yy328,
93501                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy328);
93502 }
93503         break;
93504       case 245: /* uniqueflag ::= UNIQUE */
93505       case 299: /* raisetype ::= ABORT */ yytestcase(yyruleno==299);
93506 {yygotominor.yy328 = OE_Abort;}
93507         break;
93508       case 246: /* uniqueflag ::= */
93509 {yygotominor.yy328 = OE_None;}
93510         break;
93511       case 249: /* idxlist ::= idxlist COMMA nm collate sortorder */
93512 {
93513   Expr *p = 0;
93514   if( yymsp[-1].minor.yy0.n>0 ){
93515     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
93516     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
93517   }
93518   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
93519   sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
93520   sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
93521   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
93522 }
93523         break;
93524       case 250: /* idxlist ::= nm collate sortorder */
93525 {
93526   Expr *p = 0;
93527   if( yymsp[-1].minor.yy0.n>0 ){
93528     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
93529     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
93530   }
93531   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
93532   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
93533   sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
93534   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
93535 }
93536         break;
93537       case 251: /* collate ::= */
93538 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
93539         break;
93540       case 253: /* cmd ::= DROP INDEX ifexists fullname */
93541 {sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
93542         break;
93543       case 254: /* cmd ::= VACUUM */
93544       case 255: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==255);
93545 {sqlite3Vacuum(pParse);}
93546         break;
93547       case 256: /* cmd ::= PRAGMA nm dbnm */
93548 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
93549         break;
93550       case 257: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
93551 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
93552         break;
93553       case 258: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
93554 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
93555         break;
93556       case 259: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
93557 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
93558         break;
93559       case 260: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
93560 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
93561         break;
93562       case 271: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
93563 {
93564   Token all;
93565   all.z = yymsp[-3].minor.yy0.z;
93566   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
93567   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
93568 }
93569         break;
93570       case 272: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
93571 {
93572   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy328, yymsp[-4].minor.yy378.a, yymsp[-4].minor.yy378.b, yymsp[-2].minor.yy65, yymsp[0].minor.yy132, yymsp[-10].minor.yy328, yymsp[-8].minor.yy328);
93573   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
93574 }
93575         break;
93576       case 273: /* trigger_time ::= BEFORE */
93577       case 276: /* trigger_time ::= */ yytestcase(yyruleno==276);
93578 { yygotominor.yy328 = TK_BEFORE; }
93579         break;
93580       case 274: /* trigger_time ::= AFTER */
93581 { yygotominor.yy328 = TK_AFTER;  }
93582         break;
93583       case 275: /* trigger_time ::= INSTEAD OF */
93584 { yygotominor.yy328 = TK_INSTEAD;}
93585         break;
93586       case 277: /* trigger_event ::= DELETE|INSERT */
93587       case 278: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==278);
93588 {yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
93589         break;
93590       case 279: /* trigger_event ::= UPDATE OF inscollist */
93591 {yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
93592         break;
93593       case 282: /* when_clause ::= */
93594       case 304: /* key_opt ::= */ yytestcase(yyruleno==304);
93595 { yygotominor.yy132 = 0; }
93596         break;
93597       case 283: /* when_clause ::= WHEN expr */
93598       case 305: /* key_opt ::= KEY expr */ yytestcase(yyruleno==305);
93599 { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
93600         break;
93601       case 284: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
93602 {
93603   assert( yymsp[-2].minor.yy473!=0 );
93604   yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
93605   yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
93606   yygotominor.yy473 = yymsp[-2].minor.yy473;
93607 }
93608         break;
93609       case 285: /* trigger_cmd_list ::= trigger_cmd SEMI */
93610
93611   assert( yymsp[-1].minor.yy473!=0 );
93612   yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
93613   yygotominor.yy473 = yymsp[-1].minor.yy473;
93614 }
93615         break;
93616       case 287: /* trnm ::= nm DOT nm */
93617 {
93618   yygotominor.yy0 = yymsp[0].minor.yy0;
93619   sqlite3ErrorMsg(pParse, 
93620         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
93621         "statements within triggers");
93622 }
93623         break;
93624       case 289: /* tridxby ::= INDEXED BY nm */
93625 {
93626   sqlite3ErrorMsg(pParse,
93627         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
93628         "within triggers");
93629 }
93630         break;
93631       case 290: /* tridxby ::= NOT INDEXED */
93632 {
93633   sqlite3ErrorMsg(pParse,
93634         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
93635         "within triggers");
93636 }
93637         break;
93638       case 291: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
93639 { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
93640         break;
93641       case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
93642 {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy408, yymsp[-1].minor.yy14, 0, yymsp[-7].minor.yy186);}
93643         break;
93644       case 293: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
93645 {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, 0, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
93646         break;
93647       case 294: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
93648 {yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
93649         break;
93650       case 295: /* trigger_cmd ::= select */
93651 {yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
93652         break;
93653       case 296: /* expr ::= RAISE LP IGNORE RP */
93654 {
93655   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
93656   if( yygotominor.yy346.pExpr ){
93657     yygotominor.yy346.pExpr->affinity = OE_Ignore;
93658   }
93659   yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
93660   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93661 }
93662         break;
93663       case 297: /* expr ::= RAISE LP raisetype COMMA nm RP */
93664 {
93665   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
93666   if( yygotominor.yy346.pExpr ) {
93667     yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
93668   }
93669   yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
93670   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93671 }
93672         break;
93673       case 298: /* raisetype ::= ROLLBACK */
93674 {yygotominor.yy328 = OE_Rollback;}
93675         break;
93676       case 300: /* raisetype ::= FAIL */
93677 {yygotominor.yy328 = OE_Fail;}
93678         break;
93679       case 301: /* cmd ::= DROP TRIGGER ifexists fullname */
93680 {
93681   sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
93682 }
93683         break;
93684       case 302: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
93685 {
93686   sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
93687 }
93688         break;
93689       case 303: /* cmd ::= DETACH database_kw_opt expr */
93690 {
93691   sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
93692 }
93693         break;
93694       case 308: /* cmd ::= REINDEX */
93695 {sqlite3Reindex(pParse, 0, 0);}
93696         break;
93697       case 309: /* cmd ::= REINDEX nm dbnm */
93698 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
93699         break;
93700       case 310: /* cmd ::= ANALYZE */
93701 {sqlite3Analyze(pParse, 0, 0);}
93702         break;
93703       case 311: /* cmd ::= ANALYZE nm dbnm */
93704 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
93705         break;
93706       case 312: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
93707 {
93708   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
93709 }
93710         break;
93711       case 313: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
93712 {
93713   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
93714 }
93715         break;
93716       case 314: /* add_column_fullname ::= fullname */
93717 {
93718   pParse->db->lookaside.bEnabled = 0;
93719   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
93720 }
93721         break;
93722       case 317: /* cmd ::= create_vtab */
93723 {sqlite3VtabFinishParse(pParse,0);}
93724         break;
93725       case 318: /* cmd ::= create_vtab LP vtabarglist RP */
93726 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
93727         break;
93728       case 319: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
93729 {
93730     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
93731 }
93732         break;
93733       case 322: /* vtabarg ::= */
93734 {sqlite3VtabArgInit(pParse);}
93735         break;
93736       case 324: /* vtabargtoken ::= ANY */
93737       case 325: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==325);
93738       case 326: /* lp ::= LP */ yytestcase(yyruleno==326);
93739 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
93740         break;
93741       default:
93742       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
93743       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
93744       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
93745       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
93746       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
93747       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
93748       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
93749       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
93750       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
93751       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
93752       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
93753       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
93754       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
93755       /* (44) type ::= */ yytestcase(yyruleno==44);
93756       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
93757       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
93758       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
93759       /* (54) carglist ::= */ yytestcase(yyruleno==54);
93760       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
93761       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
93762       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
93763       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
93764       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
93765       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
93766       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
93767       /* (269) plus_opt ::= PLUS */ yytestcase(yyruleno==269);
93768       /* (270) plus_opt ::= */ yytestcase(yyruleno==270);
93769       /* (280) foreach_clause ::= */ yytestcase(yyruleno==280);
93770       /* (281) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==281);
93771       /* (288) tridxby ::= */ yytestcase(yyruleno==288);
93772       /* (306) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==306);
93773       /* (307) database_kw_opt ::= */ yytestcase(yyruleno==307);
93774       /* (315) kwcolumn_opt ::= */ yytestcase(yyruleno==315);
93775       /* (316) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==316);
93776       /* (320) vtabarglist ::= vtabarg */ yytestcase(yyruleno==320);
93777       /* (321) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==321);
93778       /* (323) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==323);
93779       /* (327) anylist ::= */ yytestcase(yyruleno==327);
93780       /* (328) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==328);
93781       /* (329) anylist ::= anylist ANY */ yytestcase(yyruleno==329);
93782         break;
93783   };
93784   yygoto = yyRuleInfo[yyruleno].lhs;
93785   yysize = yyRuleInfo[yyruleno].nrhs;
93786   yypParser->yyidx -= yysize;
93787   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
93788   if( yyact < YYNSTATE ){
93789 #ifdef NDEBUG
93790     /* If we are not debugging and the reduce action popped at least
93791     ** one element off the stack, then we can push the new element back
93792     ** onto the stack here, and skip the stack overflow test in yy_shift().
93793     ** That gives a significant speed improvement. */
93794     if( yysize ){
93795       yypParser->yyidx++;
93796       yymsp -= yysize-1;
93797       yymsp->stateno = (YYACTIONTYPE)yyact;
93798       yymsp->major = (YYCODETYPE)yygoto;
93799       yymsp->minor = yygotominor;
93800     }else
93801 #endif
93802     {
93803       yy_shift(yypParser,yyact,yygoto,&yygotominor);
93804     }
93805   }else{
93806     assert( yyact == YYNSTATE + YYNRULE + 1 );
93807     yy_accept(yypParser);
93808   }
93809 }
93810
93811 /*
93812 ** The following code executes when the parse fails
93813 */
93814 #ifndef YYNOERRORRECOVERY
93815 static void yy_parse_failed(
93816   yyParser *yypParser           /* The parser */
93817 ){
93818   sqlite3ParserARG_FETCH;
93819 #ifndef NDEBUG
93820   if( yyTraceFILE ){
93821     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
93822   }
93823 #endif
93824   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
93825   /* Here code is inserted which will be executed whenever the
93826   ** parser fails */
93827   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
93828 }
93829 #endif /* YYNOERRORRECOVERY */
93830
93831 /*
93832 ** The following code executes when a syntax error first occurs.
93833 */
93834 static void yy_syntax_error(
93835   yyParser *yypParser,           /* The parser */
93836   int yymajor,                   /* The major type of the error token */
93837   YYMINORTYPE yyminor            /* The minor type of the error token */
93838 ){
93839   sqlite3ParserARG_FETCH;
93840 #define TOKEN (yyminor.yy0)
93841
93842   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
93843   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
93844   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
93845   pParse->parseError = 1;
93846   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
93847 }
93848
93849 /*
93850 ** The following is executed when the parser accepts
93851 */
93852 static void yy_accept(
93853   yyParser *yypParser           /* The parser */
93854 ){
93855   sqlite3ParserARG_FETCH;
93856 #ifndef NDEBUG
93857   if( yyTraceFILE ){
93858     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
93859   }
93860 #endif
93861   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
93862   /* Here code is inserted which will be executed whenever the
93863   ** parser accepts */
93864   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
93865 }
93866
93867 /* The main parser program.
93868 ** The first argument is a pointer to a structure obtained from
93869 ** "sqlite3ParserAlloc" which describes the current state of the parser.
93870 ** The second argument is the major token number.  The third is
93871 ** the minor token.  The fourth optional argument is whatever the
93872 ** user wants (and specified in the grammar) and is available for
93873 ** use by the action routines.
93874 **
93875 ** Inputs:
93876 ** <ul>
93877 ** <li> A pointer to the parser (an opaque structure.)
93878 ** <li> The major token number.
93879 ** <li> The minor token number.
93880 ** <li> An option argument of a grammar-specified type.
93881 ** </ul>
93882 **
93883 ** Outputs:
93884 ** None.
93885 */
93886 SQLITE_PRIVATE void sqlite3Parser(
93887   void *yyp,                   /* The parser */
93888   int yymajor,                 /* The major token code number */
93889   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
93890   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
93891 ){
93892   YYMINORTYPE yyminorunion;
93893   int yyact;            /* The parser action. */
93894   int yyendofinput;     /* True if we are at the end of input */
93895 #ifdef YYERRORSYMBOL
93896   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
93897 #endif
93898   yyParser *yypParser;  /* The parser */
93899
93900   /* (re)initialize the parser, if necessary */
93901   yypParser = (yyParser*)yyp;
93902   if( yypParser->yyidx<0 ){
93903 #if YYSTACKDEPTH<=0
93904     if( yypParser->yystksz <=0 ){
93905       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
93906       yyminorunion = yyzerominor;
93907       yyStackOverflow(yypParser, &yyminorunion);
93908       return;
93909     }
93910 #endif
93911     yypParser->yyidx = 0;
93912     yypParser->yyerrcnt = -1;
93913     yypParser->yystack[0].stateno = 0;
93914     yypParser->yystack[0].major = 0;
93915   }
93916   yyminorunion.yy0 = yyminor;
93917   yyendofinput = (yymajor==0);
93918   sqlite3ParserARG_STORE;
93919
93920 #ifndef NDEBUG
93921   if( yyTraceFILE ){
93922     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
93923   }
93924 #endif
93925
93926   do{
93927     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
93928     if( yyact<YYNSTATE ){
93929       assert( !yyendofinput );  /* Impossible to shift the $ token */
93930       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
93931       yypParser->yyerrcnt--;
93932       yymajor = YYNOCODE;
93933     }else if( yyact < YYNSTATE + YYNRULE ){
93934       yy_reduce(yypParser,yyact-YYNSTATE);
93935     }else{
93936       assert( yyact == YY_ERROR_ACTION );
93937 #ifdef YYERRORSYMBOL
93938       int yymx;
93939 #endif
93940 #ifndef NDEBUG
93941       if( yyTraceFILE ){
93942         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
93943       }
93944 #endif
93945 #ifdef YYERRORSYMBOL
93946       /* A syntax error has occurred.
93947       ** The response to an error depends upon whether or not the
93948       ** grammar defines an error token "ERROR".  
93949       **
93950       ** This is what we do if the grammar does define ERROR:
93951       **
93952       **  * Call the %syntax_error function.
93953       **
93954       **  * Begin popping the stack until we enter a state where
93955       **    it is legal to shift the error symbol, then shift
93956       **    the error symbol.
93957       **
93958       **  * Set the error count to three.
93959       **
93960       **  * Begin accepting and shifting new tokens.  No new error
93961       **    processing will occur until three tokens have been
93962       **    shifted successfully.
93963       **
93964       */
93965       if( yypParser->yyerrcnt<0 ){
93966         yy_syntax_error(yypParser,yymajor,yyminorunion);
93967       }
93968       yymx = yypParser->yystack[yypParser->yyidx].major;
93969       if( yymx==YYERRORSYMBOL || yyerrorhit ){
93970 #ifndef NDEBUG
93971         if( yyTraceFILE ){
93972           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
93973              yyTracePrompt,yyTokenName[yymajor]);
93974         }
93975 #endif
93976         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
93977         yymajor = YYNOCODE;
93978       }else{
93979          while(
93980           yypParser->yyidx >= 0 &&
93981           yymx != YYERRORSYMBOL &&
93982           (yyact = yy_find_reduce_action(
93983                         yypParser->yystack[yypParser->yyidx].stateno,
93984                         YYERRORSYMBOL)) >= YYNSTATE
93985         ){
93986           yy_pop_parser_stack(yypParser);
93987         }
93988         if( yypParser->yyidx < 0 || yymajor==0 ){
93989           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
93990           yy_parse_failed(yypParser);
93991           yymajor = YYNOCODE;
93992         }else if( yymx!=YYERRORSYMBOL ){
93993           YYMINORTYPE u2;
93994           u2.YYERRSYMDT = 0;
93995           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
93996         }
93997       }
93998       yypParser->yyerrcnt = 3;
93999       yyerrorhit = 1;
94000 #elif defined(YYNOERRORRECOVERY)
94001       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
94002       ** do any kind of error recovery.  Instead, simply invoke the syntax
94003       ** error routine and continue going as if nothing had happened.
94004       **
94005       ** Applications can set this macro (for example inside %include) if
94006       ** they intend to abandon the parse upon the first syntax error seen.
94007       */
94008       yy_syntax_error(yypParser,yymajor,yyminorunion);
94009       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
94010       yymajor = YYNOCODE;
94011       
94012 #else  /* YYERRORSYMBOL is not defined */
94013       /* This is what we do if the grammar does not define ERROR:
94014       **
94015       **  * Report an error message, and throw away the input token.
94016       **
94017       **  * If the input token is $, then fail the parse.
94018       **
94019       ** As before, subsequent error messages are suppressed until
94020       ** three input tokens have been successfully shifted.
94021       */
94022       if( yypParser->yyerrcnt<=0 ){
94023         yy_syntax_error(yypParser,yymajor,yyminorunion);
94024       }
94025       yypParser->yyerrcnt = 3;
94026       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
94027       if( yyendofinput ){
94028         yy_parse_failed(yypParser);
94029       }
94030       yymajor = YYNOCODE;
94031 #endif
94032     }
94033   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
94034   return;
94035 }
94036
94037 /************** End of parse.c ***********************************************/
94038 /************** Begin file tokenize.c ****************************************/
94039 /*
94040 ** 2001 September 15
94041 **
94042 ** The author disclaims copyright to this source code.  In place of
94043 ** a legal notice, here is a blessing:
94044 **
94045 **    May you do good and not evil.
94046 **    May you find forgiveness for yourself and forgive others.
94047 **    May you share freely, never taking more than you give.
94048 **
94049 *************************************************************************
94050 ** An tokenizer for SQL
94051 **
94052 ** This file contains C code that splits an SQL input string up into
94053 ** individual tokens and sends those tokens one-by-one over to the
94054 ** parser for analysis.
94055 */
94056
94057 /*
94058 ** The charMap() macro maps alphabetic characters into their
94059 ** lower-case ASCII equivalent.  On ASCII machines, this is just
94060 ** an upper-to-lower case map.  On EBCDIC machines we also need
94061 ** to adjust the encoding.  Only alphabetic characters and underscores
94062 ** need to be translated.
94063 */
94064 #ifdef SQLITE_ASCII
94065 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
94066 #endif
94067 #ifdef SQLITE_EBCDIC
94068 # define charMap(X) ebcdicToAscii[(unsigned char)X]
94069 const unsigned char ebcdicToAscii[] = {
94070 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
94071    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
94072    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
94073    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
94074    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
94075    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
94076    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
94077    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
94078    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
94079    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
94080    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
94081    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
94082    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
94083    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
94084    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
94085    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
94086    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
94087 };
94088 #endif
94089
94090 /*
94091 ** The sqlite3KeywordCode function looks up an identifier to determine if
94092 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
94093 ** returned.  If the input is not a keyword, TK_ID is returned.
94094 **
94095 ** The implementation of this routine was generated by a program,
94096 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
94097 ** The output of the mkkeywordhash.c program is written into a file
94098 ** named keywordhash.h and then included into this source file by
94099 ** the #include below.
94100 */
94101 /************** Include keywordhash.h in the middle of tokenize.c ************/
94102 /************** Begin file keywordhash.h *************************************/
94103 /***** This file contains automatically generated code ******
94104 **
94105 ** The code in this file has been automatically generated by
94106 **
94107 **   sqlite/tool/mkkeywordhash.c
94108 **
94109 ** The code in this file implements a function that determines whether
94110 ** or not a given identifier is really an SQL keyword.  The same thing
94111 ** might be implemented more directly using a hand-written hash table.
94112 ** But by using this automatically generated code, the size of the code
94113 ** is substantially reduced.  This is important for embedded applications
94114 ** on platforms with limited memory.
94115 */
94116 /* Hash score: 175 */
94117 static int keywordCode(const char *z, int n){
94118   /* zText[] encodes 811 bytes of keywords in 541 bytes */
94119   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
94120   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
94121   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
94122   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
94123   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
94124   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
94125   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
94126   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
94127   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
94128   /*   INITIALLY                                                          */
94129   static const char zText[540] = {
94130     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
94131     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
94132     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
94133     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
94134     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
94135     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
94136     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
94137     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
94138     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
94139     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
94140     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
94141     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
94142     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
94143     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
94144     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
94145     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
94146     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
94147     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
94148     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
94149     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
94150     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
94151     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
94152     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
94153     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
94154     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
94155     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
94156     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
94157     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
94158     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
94159     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
94160   };
94161   static const unsigned char aHash[127] = {
94162       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
94163       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
94164      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
94165        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
94166        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
94167       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
94168       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
94169       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
94170       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
94171       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
94172   };
94173   static const unsigned char aNext[121] = {
94174        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
94175        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
94176        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
94177        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
94178        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
94179       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
94180       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
94181        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
94182      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
94183       35,  64,   0,   0,
94184   };
94185   static const unsigned char aLen[121] = {
94186        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
94187        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
94188       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
94189        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
94190        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
94191        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
94192        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
94193        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
94194        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
94195        6,   4,   9,   3,
94196   };
94197   static const unsigned short int aOffset[121] = {
94198        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
94199       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
94200       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
94201      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
94202      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
94203      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
94204      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
94205      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
94206      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
94207      521, 527, 531, 536,
94208   };
94209   static const unsigned char aCode[121] = {
94210     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
94211     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
94212     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
94213     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
94214     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
94215     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
94216     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
94217     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
94218     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
94219     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
94220     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
94221     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
94222     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
94223     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
94224     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
94225     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
94226     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
94227     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
94228     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
94229     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
94230     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
94231     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
94232     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
94233     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
94234     TK_ALL,        
94235   };
94236   int h, i;
94237   if( n<2 ) return TK_ID;
94238   h = ((charMap(z[0])*4) ^
94239       (charMap(z[n-1])*3) ^
94240       n) % 127;
94241   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
94242     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
94243       testcase( i==0 ); /* REINDEX */
94244       testcase( i==1 ); /* INDEXED */
94245       testcase( i==2 ); /* INDEX */
94246       testcase( i==3 ); /* DESC */
94247       testcase( i==4 ); /* ESCAPE */
94248       testcase( i==5 ); /* EACH */
94249       testcase( i==6 ); /* CHECK */
94250       testcase( i==7 ); /* KEY */
94251       testcase( i==8 ); /* BEFORE */
94252       testcase( i==9 ); /* FOREIGN */
94253       testcase( i==10 ); /* FOR */
94254       testcase( i==11 ); /* IGNORE */
94255       testcase( i==12 ); /* REGEXP */
94256       testcase( i==13 ); /* EXPLAIN */
94257       testcase( i==14 ); /* INSTEAD */
94258       testcase( i==15 ); /* ADD */
94259       testcase( i==16 ); /* DATABASE */
94260       testcase( i==17 ); /* AS */
94261       testcase( i==18 ); /* SELECT */
94262       testcase( i==19 ); /* TABLE */
94263       testcase( i==20 ); /* LEFT */
94264       testcase( i==21 ); /* THEN */
94265       testcase( i==22 ); /* END */
94266       testcase( i==23 ); /* DEFERRABLE */
94267       testcase( i==24 ); /* ELSE */
94268       testcase( i==25 ); /* EXCEPT */
94269       testcase( i==26 ); /* TRANSACTION */
94270       testcase( i==27 ); /* ACTION */
94271       testcase( i==28 ); /* ON */
94272       testcase( i==29 ); /* NATURAL */
94273       testcase( i==30 ); /* ALTER */
94274       testcase( i==31 ); /* RAISE */
94275       testcase( i==32 ); /* EXCLUSIVE */
94276       testcase( i==33 ); /* EXISTS */
94277       testcase( i==34 ); /* SAVEPOINT */
94278       testcase( i==35 ); /* INTERSECT */
94279       testcase( i==36 ); /* TRIGGER */
94280       testcase( i==37 ); /* REFERENCES */
94281       testcase( i==38 ); /* CONSTRAINT */
94282       testcase( i==39 ); /* INTO */
94283       testcase( i==40 ); /* OFFSET */
94284       testcase( i==41 ); /* OF */
94285       testcase( i==42 ); /* SET */
94286       testcase( i==43 ); /* TEMPORARY */
94287       testcase( i==44 ); /* TEMP */
94288       testcase( i==45 ); /* OR */
94289       testcase( i==46 ); /* UNIQUE */
94290       testcase( i==47 ); /* QUERY */
94291       testcase( i==48 ); /* ATTACH */
94292       testcase( i==49 ); /* HAVING */
94293       testcase( i==50 ); /* GROUP */
94294       testcase( i==51 ); /* UPDATE */
94295       testcase( i==52 ); /* BEGIN */
94296       testcase( i==53 ); /* INNER */
94297       testcase( i==54 ); /* RELEASE */
94298       testcase( i==55 ); /* BETWEEN */
94299       testcase( i==56 ); /* NOTNULL */
94300       testcase( i==57 ); /* NOT */
94301       testcase( i==58 ); /* NO */
94302       testcase( i==59 ); /* NULL */
94303       testcase( i==60 ); /* LIKE */
94304       testcase( i==61 ); /* CASCADE */
94305       testcase( i==62 ); /* ASC */
94306       testcase( i==63 ); /* DELETE */
94307       testcase( i==64 ); /* CASE */
94308       testcase( i==65 ); /* COLLATE */
94309       testcase( i==66 ); /* CREATE */
94310       testcase( i==67 ); /* CURRENT_DATE */
94311       testcase( i==68 ); /* DETACH */
94312       testcase( i==69 ); /* IMMEDIATE */
94313       testcase( i==70 ); /* JOIN */
94314       testcase( i==71 ); /* INSERT */
94315       testcase( i==72 ); /* MATCH */
94316       testcase( i==73 ); /* PLAN */
94317       testcase( i==74 ); /* ANALYZE */
94318       testcase( i==75 ); /* PRAGMA */
94319       testcase( i==76 ); /* ABORT */
94320       testcase( i==77 ); /* VALUES */
94321       testcase( i==78 ); /* VIRTUAL */
94322       testcase( i==79 ); /* LIMIT */
94323       testcase( i==80 ); /* WHEN */
94324       testcase( i==81 ); /* WHERE */
94325       testcase( i==82 ); /* RENAME */
94326       testcase( i==83 ); /* AFTER */
94327       testcase( i==84 ); /* REPLACE */
94328       testcase( i==85 ); /* AND */
94329       testcase( i==86 ); /* DEFAULT */
94330       testcase( i==87 ); /* AUTOINCREMENT */
94331       testcase( i==88 ); /* TO */
94332       testcase( i==89 ); /* IN */
94333       testcase( i==90 ); /* CAST */
94334       testcase( i==91 ); /* COLUMN */
94335       testcase( i==92 ); /* COMMIT */
94336       testcase( i==93 ); /* CONFLICT */
94337       testcase( i==94 ); /* CROSS */
94338       testcase( i==95 ); /* CURRENT_TIMESTAMP */
94339       testcase( i==96 ); /* CURRENT_TIME */
94340       testcase( i==97 ); /* PRIMARY */
94341       testcase( i==98 ); /* DEFERRED */
94342       testcase( i==99 ); /* DISTINCT */
94343       testcase( i==100 ); /* IS */
94344       testcase( i==101 ); /* DROP */
94345       testcase( i==102 ); /* FAIL */
94346       testcase( i==103 ); /* FROM */
94347       testcase( i==104 ); /* FULL */
94348       testcase( i==105 ); /* GLOB */
94349       testcase( i==106 ); /* BY */
94350       testcase( i==107 ); /* IF */
94351       testcase( i==108 ); /* ISNULL */
94352       testcase( i==109 ); /* ORDER */
94353       testcase( i==110 ); /* RESTRICT */
94354       testcase( i==111 ); /* OUTER */
94355       testcase( i==112 ); /* RIGHT */
94356       testcase( i==113 ); /* ROLLBACK */
94357       testcase( i==114 ); /* ROW */
94358       testcase( i==115 ); /* UNION */
94359       testcase( i==116 ); /* USING */
94360       testcase( i==117 ); /* VACUUM */
94361       testcase( i==118 ); /* VIEW */
94362       testcase( i==119 ); /* INITIALLY */
94363       testcase( i==120 ); /* ALL */
94364       return aCode[i];
94365     }
94366   }
94367   return TK_ID;
94368 }
94369 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
94370   return keywordCode((char*)z, n);
94371 }
94372 #define SQLITE_N_KEYWORD 121
94373
94374 /************** End of keywordhash.h *****************************************/
94375 /************** Continuing where we left off in tokenize.c *******************/
94376
94377
94378 /*
94379 ** If X is a character that can be used in an identifier then
94380 ** IdChar(X) will be true.  Otherwise it is false.
94381 **
94382 ** For ASCII, any character with the high-order bit set is
94383 ** allowed in an identifier.  For 7-bit characters, 
94384 ** sqlite3IsIdChar[X] must be 1.
94385 **
94386 ** For EBCDIC, the rules are more complex but have the same
94387 ** end result.
94388 **
94389 ** Ticket #1066.  the SQL standard does not allow '$' in the
94390 ** middle of identfiers.  But many SQL implementations do. 
94391 ** SQLite will allow '$' in identifiers for compatibility.
94392 ** But the feature is undocumented.
94393 */
94394 #ifdef SQLITE_ASCII
94395 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
94396 #endif
94397 #ifdef SQLITE_EBCDIC
94398 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
94399 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
94400     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
94401     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
94402     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
94403     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
94404     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
94405     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
94406     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
94407     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
94408     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
94409     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
94410     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
94411     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
94412 };
94413 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
94414 #endif
94415
94416
94417 /*
94418 ** Return the length of the token that begins at z[0]. 
94419 ** Store the token type in *tokenType before returning.
94420 */
94421 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
94422   int i, c;
94423   switch( *z ){
94424     case ' ': case '\t': case '\n': case '\f': case '\r': {
94425       testcase( z[0]==' ' );
94426       testcase( z[0]=='\t' );
94427       testcase( z[0]=='\n' );
94428       testcase( z[0]=='\f' );
94429       testcase( z[0]=='\r' );
94430       for(i=1; sqlite3Isspace(z[i]); i++){}
94431       *tokenType = TK_SPACE;
94432       return i;
94433     }
94434     case '-': {
94435       if( z[1]=='-' ){
94436         /* IMP: R-15891-05542 -- syntax diagram for comments */
94437         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
94438         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
94439         return i;
94440       }
94441       *tokenType = TK_MINUS;
94442       return 1;
94443     }
94444     case '(': {
94445       *tokenType = TK_LP;
94446       return 1;
94447     }
94448     case ')': {
94449       *tokenType = TK_RP;
94450       return 1;
94451     }
94452     case ';': {
94453       *tokenType = TK_SEMI;
94454       return 1;
94455     }
94456     case '+': {
94457       *tokenType = TK_PLUS;
94458       return 1;
94459     }
94460     case '*': {
94461       *tokenType = TK_STAR;
94462       return 1;
94463     }
94464     case '/': {
94465       if( z[1]!='*' || z[2]==0 ){
94466         *tokenType = TK_SLASH;
94467         return 1;
94468       }
94469       /* IMP: R-15891-05542 -- syntax diagram for comments */
94470       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
94471       if( c ) i++;
94472       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
94473       return i;
94474     }
94475     case '%': {
94476       *tokenType = TK_REM;
94477       return 1;
94478     }
94479     case '=': {
94480       *tokenType = TK_EQ;
94481       return 1 + (z[1]=='=');
94482     }
94483     case '<': {
94484       if( (c=z[1])=='=' ){
94485         *tokenType = TK_LE;
94486         return 2;
94487       }else if( c=='>' ){
94488         *tokenType = TK_NE;
94489         return 2;
94490       }else if( c=='<' ){
94491         *tokenType = TK_LSHIFT;
94492         return 2;
94493       }else{
94494         *tokenType = TK_LT;
94495         return 1;
94496       }
94497     }
94498     case '>': {
94499       if( (c=z[1])=='=' ){
94500         *tokenType = TK_GE;
94501         return 2;
94502       }else if( c=='>' ){
94503         *tokenType = TK_RSHIFT;
94504         return 2;
94505       }else{
94506         *tokenType = TK_GT;
94507         return 1;
94508       }
94509     }
94510     case '!': {
94511       if( z[1]!='=' ){
94512         *tokenType = TK_ILLEGAL;
94513         return 2;
94514       }else{
94515         *tokenType = TK_NE;
94516         return 2;
94517       }
94518     }
94519     case '|': {
94520       if( z[1]!='|' ){
94521         *tokenType = TK_BITOR;
94522         return 1;
94523       }else{
94524         *tokenType = TK_CONCAT;
94525         return 2;
94526       }
94527     }
94528     case ',': {
94529       *tokenType = TK_COMMA;
94530       return 1;
94531     }
94532     case '&': {
94533       *tokenType = TK_BITAND;
94534       return 1;
94535     }
94536     case '~': {
94537       *tokenType = TK_BITNOT;
94538       return 1;
94539     }
94540     case '`':
94541     case '\'':
94542     case '"': {
94543       int delim = z[0];
94544       testcase( delim=='`' );
94545       testcase( delim=='\'' );
94546       testcase( delim=='"' );
94547       for(i=1; (c=z[i])!=0; i++){
94548         if( c==delim ){
94549           if( z[i+1]==delim ){
94550             i++;
94551           }else{
94552             break;
94553           }
94554         }
94555       }
94556       if( c=='\'' ){
94557         *tokenType = TK_STRING;
94558         return i+1;
94559       }else if( c!=0 ){
94560         *tokenType = TK_ID;
94561         return i+1;
94562       }else{
94563         *tokenType = TK_ILLEGAL;
94564         return i;
94565       }
94566     }
94567     case '.': {
94568 #ifndef SQLITE_OMIT_FLOATING_POINT
94569       if( !sqlite3Isdigit(z[1]) )
94570 #endif
94571       {
94572         *tokenType = TK_DOT;
94573         return 1;
94574       }
94575       /* If the next character is a digit, this is a floating point
94576       ** number that begins with ".".  Fall thru into the next case */
94577     }
94578     case '0': case '1': case '2': case '3': case '4':
94579     case '5': case '6': case '7': case '8': case '9': {
94580       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
94581       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
94582       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
94583       testcase( z[0]=='9' );
94584       *tokenType = TK_INTEGER;
94585       for(i=0; sqlite3Isdigit(z[i]); i++){}
94586 #ifndef SQLITE_OMIT_FLOATING_POINT
94587       if( z[i]=='.' ){
94588         i++;
94589         while( sqlite3Isdigit(z[i]) ){ i++; }
94590         *tokenType = TK_FLOAT;
94591       }
94592       if( (z[i]=='e' || z[i]=='E') &&
94593            ( sqlite3Isdigit(z[i+1]) 
94594             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
94595            )
94596       ){
94597         i += 2;
94598         while( sqlite3Isdigit(z[i]) ){ i++; }
94599         *tokenType = TK_FLOAT;
94600       }
94601 #endif
94602       while( IdChar(z[i]) ){
94603         *tokenType = TK_ILLEGAL;
94604         i++;
94605       }
94606       return i;
94607     }
94608     case '[': {
94609       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
94610       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
94611       return i;
94612     }
94613     case '?': {
94614       *tokenType = TK_VARIABLE;
94615       for(i=1; sqlite3Isdigit(z[i]); i++){}
94616       return i;
94617     }
94618     case '#': {
94619       for(i=1; sqlite3Isdigit(z[i]); i++){}
94620       if( i>1 ){
94621         /* Parameters of the form #NNN (where NNN is a number) are used
94622         ** internally by sqlite3NestedParse.  */
94623         *tokenType = TK_REGISTER;
94624         return i;
94625       }
94626       /* Fall through into the next case if the '#' is not followed by
94627       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
94628     }
94629 #ifndef SQLITE_OMIT_TCL_VARIABLE
94630     case '$':
94631 #endif
94632     case '@':  /* For compatibility with MS SQL Server */
94633     case ':': {
94634       int n = 0;
94635       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
94636       *tokenType = TK_VARIABLE;
94637       for(i=1; (c=z[i])!=0; i++){
94638         if( IdChar(c) ){
94639           n++;
94640 #ifndef SQLITE_OMIT_TCL_VARIABLE
94641         }else if( c=='(' && n>0 ){
94642           do{
94643             i++;
94644           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
94645           if( c==')' ){
94646             i++;
94647           }else{
94648             *tokenType = TK_ILLEGAL;
94649           }
94650           break;
94651         }else if( c==':' && z[i+1]==':' ){
94652           i++;
94653 #endif
94654         }else{
94655           break;
94656         }
94657       }
94658       if( n==0 ) *tokenType = TK_ILLEGAL;
94659       return i;
94660     }
94661 #ifndef SQLITE_OMIT_BLOB_LITERAL
94662     case 'x': case 'X': {
94663       testcase( z[0]=='x' ); testcase( z[0]=='X' );
94664       if( z[1]=='\'' ){
94665         *tokenType = TK_BLOB;
94666         for(i=2; (c=z[i])!=0 && c!='\''; i++){
94667           if( !sqlite3Isxdigit(c) ){
94668             *tokenType = TK_ILLEGAL;
94669           }
94670         }
94671         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
94672         if( c ) i++;
94673         return i;
94674       }
94675       /* Otherwise fall through to the next case */
94676     }
94677 #endif
94678     default: {
94679       if( !IdChar(*z) ){
94680         break;
94681       }
94682       for(i=1; IdChar(z[i]); i++){}
94683       *tokenType = keywordCode((char*)z, i);
94684       return i;
94685     }
94686   }
94687   *tokenType = TK_ILLEGAL;
94688   return 1;
94689 }
94690
94691 /*
94692 ** Run the parser on the given SQL string.  The parser structure is
94693 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
94694 ** then an and attempt is made to write an error message into 
94695 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
94696 ** error message.
94697 */
94698 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
94699   int nErr = 0;                   /* Number of errors encountered */
94700   int i;                          /* Loop counter */
94701   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
94702   int tokenType;                  /* type of the next token */
94703   int lastTokenParsed = -1;       /* type of the previous token */
94704   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
94705   sqlite3 *db = pParse->db;       /* The database connection */
94706   int mxSqlLen;                   /* Max length of an SQL string */
94707
94708
94709   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
94710   if( db->activeVdbeCnt==0 ){
94711     db->u1.isInterrupted = 0;
94712   }
94713   pParse->rc = SQLITE_OK;
94714   pParse->zTail = zSql;
94715   i = 0;
94716   assert( pzErrMsg!=0 );
94717   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
94718   if( pEngine==0 ){
94719     db->mallocFailed = 1;
94720     return SQLITE_NOMEM;
94721   }
94722   assert( pParse->pNewTable==0 );
94723   assert( pParse->pNewTrigger==0 );
94724   assert( pParse->nVar==0 );
94725   assert( pParse->nVarExpr==0 );
94726   assert( pParse->nVarExprAlloc==0 );
94727   assert( pParse->apVarExpr==0 );
94728   enableLookaside = db->lookaside.bEnabled;
94729   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
94730   while( !db->mallocFailed && zSql[i]!=0 ){
94731     assert( i>=0 );
94732     pParse->sLastToken.z = &zSql[i];
94733     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
94734     i += pParse->sLastToken.n;
94735     if( i>mxSqlLen ){
94736       pParse->rc = SQLITE_TOOBIG;
94737       break;
94738     }
94739     switch( tokenType ){
94740       case TK_SPACE: {
94741         if( db->u1.isInterrupted ){
94742           sqlite3ErrorMsg(pParse, "interrupt");
94743           pParse->rc = SQLITE_INTERRUPT;
94744           goto abort_parse;
94745         }
94746         break;
94747       }
94748       case TK_ILLEGAL: {
94749         sqlite3DbFree(db, *pzErrMsg);
94750         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
94751                         &pParse->sLastToken);
94752         nErr++;
94753         goto abort_parse;
94754       }
94755       case TK_SEMI: {
94756         pParse->zTail = &zSql[i];
94757         /* Fall thru into the default case */
94758       }
94759       default: {
94760         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
94761         lastTokenParsed = tokenType;
94762         if( pParse->rc!=SQLITE_OK ){
94763           goto abort_parse;
94764         }
94765         break;
94766       }
94767     }
94768   }
94769 abort_parse:
94770   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
94771     if( lastTokenParsed!=TK_SEMI ){
94772       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
94773       pParse->zTail = &zSql[i];
94774     }
94775     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
94776   }
94777 #ifdef YYTRACKMAXSTACKDEPTH
94778   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
94779       sqlite3ParserStackPeak(pEngine)
94780   );
94781 #endif /* YYDEBUG */
94782   sqlite3ParserFree(pEngine, sqlite3_free);
94783   db->lookaside.bEnabled = enableLookaside;
94784   if( db->mallocFailed ){
94785     pParse->rc = SQLITE_NOMEM;
94786   }
94787   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
94788     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
94789   }
94790   assert( pzErrMsg!=0 );
94791   if( pParse->zErrMsg ){
94792     *pzErrMsg = pParse->zErrMsg;
94793     pParse->zErrMsg = 0;
94794     nErr++;
94795   }
94796   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
94797     sqlite3VdbeDelete(pParse->pVdbe);
94798     pParse->pVdbe = 0;
94799   }
94800 #ifndef SQLITE_OMIT_SHARED_CACHE
94801   if( pParse->nested==0 ){
94802     sqlite3DbFree(db, pParse->aTableLock);
94803     pParse->aTableLock = 0;
94804     pParse->nTableLock = 0;
94805   }
94806 #endif
94807 #ifndef SQLITE_OMIT_VIRTUALTABLE
94808   sqlite3DbFree(db, pParse->apVtabLock);
94809 #endif
94810
94811   if( !IN_DECLARE_VTAB ){
94812     /* If the pParse->declareVtab flag is set, do not delete any table 
94813     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
94814     ** will take responsibility for freeing the Table structure.
94815     */
94816     sqlite3DeleteTable(pParse->pNewTable);
94817   }
94818
94819   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
94820   sqlite3DbFree(db, pParse->apVarExpr);
94821   sqlite3DbFree(db, pParse->aAlias);
94822   while( pParse->pAinc ){
94823     AutoincInfo *p = pParse->pAinc;
94824     pParse->pAinc = p->pNext;
94825     sqlite3DbFree(db, p);
94826   }
94827   while( pParse->pZombieTab ){
94828     Table *p = pParse->pZombieTab;
94829     pParse->pZombieTab = p->pNextZombie;
94830     sqlite3DeleteTable(p);
94831   }
94832   if( nErr>0 && pParse->rc==SQLITE_OK ){
94833     pParse->rc = SQLITE_ERROR;
94834   }
94835   return nErr;
94836 }
94837
94838 /************** End of tokenize.c ********************************************/
94839 /************** Begin file complete.c ****************************************/
94840 /*
94841 ** 2001 September 15
94842 **
94843 ** The author disclaims copyright to this source code.  In place of
94844 ** a legal notice, here is a blessing:
94845 **
94846 **    May you do good and not evil.
94847 **    May you find forgiveness for yourself and forgive others.
94848 **    May you share freely, never taking more than you give.
94849 **
94850 *************************************************************************
94851 ** An tokenizer for SQL
94852 **
94853 ** This file contains C code that implements the sqlite3_complete() API.
94854 ** This code used to be part of the tokenizer.c source file.  But by
94855 ** separating it out, the code will be automatically omitted from
94856 ** static links that do not use it.
94857 */
94858 #ifndef SQLITE_OMIT_COMPLETE
94859
94860 /*
94861 ** This is defined in tokenize.c.  We just have to import the definition.
94862 */
94863 #ifndef SQLITE_AMALGAMATION
94864 #ifdef SQLITE_ASCII
94865 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
94866 #endif
94867 #ifdef SQLITE_EBCDIC
94868 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
94869 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
94870 #endif
94871 #endif /* SQLITE_AMALGAMATION */
94872
94873
94874 /*
94875 ** Token types used by the sqlite3_complete() routine.  See the header
94876 ** comments on that procedure for additional information.
94877 */
94878 #define tkSEMI    0
94879 #define tkWS      1
94880 #define tkOTHER   2
94881 #ifndef SQLITE_OMIT_TRIGGER
94882 #define tkEXPLAIN 3
94883 #define tkCREATE  4
94884 #define tkTEMP    5
94885 #define tkTRIGGER 6
94886 #define tkEND     7
94887 #endif
94888
94889 /*
94890 ** Return TRUE if the given SQL string ends in a semicolon.
94891 **
94892 ** Special handling is require for CREATE TRIGGER statements.
94893 ** Whenever the CREATE TRIGGER keywords are seen, the statement
94894 ** must end with ";END;".
94895 **
94896 ** This implementation uses a state machine with 8 states:
94897 **
94898 **   (0) INVALID   We have not yet seen a non-whitespace character.
94899 **
94900 **   (1) START     At the beginning or end of an SQL statement.  This routine
94901 **                 returns 1 if it ends in the START state and 0 if it ends
94902 **                 in any other state.
94903 **
94904 **   (2) NORMAL    We are in the middle of statement which ends with a single
94905 **                 semicolon.
94906 **
94907 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
94908 **                 a statement.
94909 **
94910 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
94911 **                 statement, possibly preceeded by EXPLAIN and/or followed by
94912 **                 TEMP or TEMPORARY
94913 **
94914 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
94915 **                 ended by a semicolon, the keyword END, and another semicolon.
94916 **
94917 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
94918 **                 the end of a trigger definition.
94919 **
94920 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
94921 **                 of a trigger difinition.
94922 **
94923 ** Transitions between states above are determined by tokens extracted
94924 ** from the input.  The following tokens are significant:
94925 **
94926 **   (0) tkSEMI      A semicolon.
94927 **   (1) tkWS        Whitespace.
94928 **   (2) tkOTHER     Any other SQL token.
94929 **   (3) tkEXPLAIN   The "explain" keyword.
94930 **   (4) tkCREATE    The "create" keyword.
94931 **   (5) tkTEMP      The "temp" or "temporary" keyword.
94932 **   (6) tkTRIGGER   The "trigger" keyword.
94933 **   (7) tkEND       The "end" keyword.
94934 **
94935 ** Whitespace never causes a state transition and is always ignored.
94936 ** This means that a SQL string of all whitespace is invalid.
94937 **
94938 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
94939 ** to recognize the end of a trigger can be omitted.  All we have to do
94940 ** is look for a semicolon that is not part of an string or comment.
94941 */
94942 SQLITE_API int sqlite3_complete(const char *zSql){
94943   u8 state = 0;   /* Current state, using numbers defined in header comment */
94944   u8 token;       /* Value of the next token */
94945
94946 #ifndef SQLITE_OMIT_TRIGGER
94947   /* A complex statement machine used to detect the end of a CREATE TRIGGER
94948   ** statement.  This is the normal case.
94949   */
94950   static const u8 trans[8][8] = {
94951                      /* Token:                                                */
94952      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
94953      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
94954      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
94955      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
94956      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
94957      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
94958      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
94959      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
94960      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
94961   };
94962 #else
94963   /* If triggers are not supported by this compile then the statement machine
94964   ** used to detect the end of a statement is much simplier
94965   */
94966   static const u8 trans[3][3] = {
94967                      /* Token:           */
94968      /* State:       **  SEMI  WS  OTHER */
94969      /* 0 INVALID: */ {    1,  0,     2, },
94970      /* 1   START: */ {    1,  1,     2, },
94971      /* 2  NORMAL: */ {    1,  2,     2, },
94972   };
94973 #endif /* SQLITE_OMIT_TRIGGER */
94974
94975   while( *zSql ){
94976     switch( *zSql ){
94977       case ';': {  /* A semicolon */
94978         token = tkSEMI;
94979         break;
94980       }
94981       case ' ':
94982       case '\r':
94983       case '\t':
94984       case '\n':
94985       case '\f': {  /* White space is ignored */
94986         token = tkWS;
94987         break;
94988       }
94989       case '/': {   /* C-style comments */
94990         if( zSql[1]!='*' ){
94991           token = tkOTHER;
94992           break;
94993         }
94994         zSql += 2;
94995         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
94996         if( zSql[0]==0 ) return 0;
94997         zSql++;
94998         token = tkWS;
94999         break;
95000       }
95001       case '-': {   /* SQL-style comments from "--" to end of line */
95002         if( zSql[1]!='-' ){
95003           token = tkOTHER;
95004           break;
95005         }
95006         while( *zSql && *zSql!='\n' ){ zSql++; }
95007         if( *zSql==0 ) return state==1;
95008         token = tkWS;
95009         break;
95010       }
95011       case '[': {   /* Microsoft-style identifiers in [...] */
95012         zSql++;
95013         while( *zSql && *zSql!=']' ){ zSql++; }
95014         if( *zSql==0 ) return 0;
95015         token = tkOTHER;
95016         break;
95017       }
95018       case '`':     /* Grave-accent quoted symbols used by MySQL */
95019       case '"':     /* single- and double-quoted strings */
95020       case '\'': {
95021         int c = *zSql;
95022         zSql++;
95023         while( *zSql && *zSql!=c ){ zSql++; }
95024         if( *zSql==0 ) return 0;
95025         token = tkOTHER;
95026         break;
95027       }
95028       default: {
95029 #ifdef SQLITE_EBCDIC
95030         unsigned char c;
95031 #endif
95032         if( IdChar((u8)*zSql) ){
95033           /* Keywords and unquoted identifiers */
95034           int nId;
95035           for(nId=1; IdChar(zSql[nId]); nId++){}
95036 #ifdef SQLITE_OMIT_TRIGGER
95037           token = tkOTHER;
95038 #else
95039           switch( *zSql ){
95040             case 'c': case 'C': {
95041               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
95042                 token = tkCREATE;
95043               }else{
95044                 token = tkOTHER;
95045               }
95046               break;
95047             }
95048             case 't': case 'T': {
95049               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
95050                 token = tkTRIGGER;
95051               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
95052                 token = tkTEMP;
95053               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
95054                 token = tkTEMP;
95055               }else{
95056                 token = tkOTHER;
95057               }
95058               break;
95059             }
95060             case 'e':  case 'E': {
95061               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
95062                 token = tkEND;
95063               }else
95064 #ifndef SQLITE_OMIT_EXPLAIN
95065               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
95066                 token = tkEXPLAIN;
95067               }else
95068 #endif
95069               {
95070                 token = tkOTHER;
95071               }
95072               break;
95073             }
95074             default: {
95075               token = tkOTHER;
95076               break;
95077             }
95078           }
95079 #endif /* SQLITE_OMIT_TRIGGER */
95080           zSql += nId-1;
95081         }else{
95082           /* Operators and special symbols */
95083           token = tkOTHER;
95084         }
95085         break;
95086       }
95087     }
95088     state = trans[state][token];
95089     zSql++;
95090   }
95091   return state==1;
95092 }
95093
95094 #ifndef SQLITE_OMIT_UTF16
95095 /*
95096 ** This routine is the same as the sqlite3_complete() routine described
95097 ** above, except that the parameter is required to be UTF-16 encoded, not
95098 ** UTF-8.
95099 */
95100 SQLITE_API int sqlite3_complete16(const void *zSql){
95101   sqlite3_value *pVal;
95102   char const *zSql8;
95103   int rc = SQLITE_NOMEM;
95104
95105 #ifndef SQLITE_OMIT_AUTOINIT
95106   rc = sqlite3_initialize();
95107   if( rc ) return rc;
95108 #endif
95109   pVal = sqlite3ValueNew(0);
95110   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
95111   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
95112   if( zSql8 ){
95113     rc = sqlite3_complete(zSql8);
95114   }else{
95115     rc = SQLITE_NOMEM;
95116   }
95117   sqlite3ValueFree(pVal);
95118   return sqlite3ApiExit(0, rc);
95119 }
95120 #endif /* SQLITE_OMIT_UTF16 */
95121 #endif /* SQLITE_OMIT_COMPLETE */
95122
95123 /************** End of complete.c ********************************************/
95124 /************** Begin file main.c ********************************************/
95125 /*
95126 ** 2001 September 15
95127 **
95128 ** The author disclaims copyright to this source code.  In place of
95129 ** a legal notice, here is a blessing:
95130 **
95131 **    May you do good and not evil.
95132 **    May you find forgiveness for yourself and forgive others.
95133 **    May you share freely, never taking more than you give.
95134 **
95135 *************************************************************************
95136 ** Main file for the SQLite library.  The routines in this file
95137 ** implement the programmer interface to the library.  Routines in
95138 ** other files are for internal use by SQLite and should not be
95139 ** accessed by users of the library.
95140 */
95141
95142 #ifdef SQLITE_ENABLE_FTS3
95143 /************** Include fts3.h in the middle of main.c ***********************/
95144 /************** Begin file fts3.h ********************************************/
95145 /*
95146 ** 2006 Oct 10
95147 **
95148 ** The author disclaims copyright to this source code.  In place of
95149 ** a legal notice, here is a blessing:
95150 **
95151 **    May you do good and not evil.
95152 **    May you find forgiveness for yourself and forgive others.
95153 **    May you share freely, never taking more than you give.
95154 **
95155 ******************************************************************************
95156 **
95157 ** This header file is used by programs that want to link against the
95158 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
95159 */
95160
95161 #if 0
95162 extern "C" {
95163 #endif  /* __cplusplus */
95164
95165 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
95166
95167 #if 0
95168 }  /* extern "C" */
95169 #endif  /* __cplusplus */
95170
95171 /************** End of fts3.h ************************************************/
95172 /************** Continuing where we left off in main.c ***********************/
95173 #endif
95174 #ifdef SQLITE_ENABLE_RTREE
95175 /************** Include rtree.h in the middle of main.c **********************/
95176 /************** Begin file rtree.h *******************************************/
95177 /*
95178 ** 2008 May 26
95179 **
95180 ** The author disclaims copyright to this source code.  In place of
95181 ** a legal notice, here is a blessing:
95182 **
95183 **    May you do good and not evil.
95184 **    May you find forgiveness for yourself and forgive others.
95185 **    May you share freely, never taking more than you give.
95186 **
95187 ******************************************************************************
95188 **
95189 ** This header file is used by programs that want to link against the
95190 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
95191 */
95192
95193 #if 0
95194 extern "C" {
95195 #endif  /* __cplusplus */
95196
95197 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
95198
95199 #if 0
95200 }  /* extern "C" */
95201 #endif  /* __cplusplus */
95202
95203 /************** End of rtree.h ***********************************************/
95204 /************** Continuing where we left off in main.c ***********************/
95205 #endif
95206 #ifdef SQLITE_ENABLE_ICU
95207 /************** Include sqliteicu.h in the middle of main.c ******************/
95208 /************** Begin file sqliteicu.h ***************************************/
95209 /*
95210 ** 2008 May 26
95211 **
95212 ** The author disclaims copyright to this source code.  In place of
95213 ** a legal notice, here is a blessing:
95214 **
95215 **    May you do good and not evil.
95216 **    May you find forgiveness for yourself and forgive others.
95217 **    May you share freely, never taking more than you give.
95218 **
95219 ******************************************************************************
95220 **
95221 ** This header file is used by programs that want to link against the
95222 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
95223 */
95224
95225 #if 0
95226 extern "C" {
95227 #endif  /* __cplusplus */
95228
95229 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
95230
95231 #if 0
95232 }  /* extern "C" */
95233 #endif  /* __cplusplus */
95234
95235
95236 /************** End of sqliteicu.h *******************************************/
95237 /************** Continuing where we left off in main.c ***********************/
95238 #endif
95239
95240 /*
95241 ** The version of the library
95242 */
95243 #ifndef SQLITE_AMALGAMATION
95244 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
95245 #endif
95246 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
95247 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
95248 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
95249 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
95250
95251 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
95252 /*
95253 ** If the following function pointer is not NULL and if
95254 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
95255 ** I/O active are written using this function.  These messages
95256 ** are intended for debugging activity only.
95257 */
95258 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
95259 #endif
95260
95261 /*
95262 ** If the following global variable points to a string which is the
95263 ** name of a directory, then that directory will be used to store
95264 ** temporary files.
95265 **
95266 ** See also the "PRAGMA temp_store_directory" SQL command.
95267 */
95268 SQLITE_API char *sqlite3_temp_directory = 0;
95269
95270 /*
95271 ** Initialize SQLite.  
95272 **
95273 ** This routine must be called to initialize the memory allocation,
95274 ** VFS, and mutex subsystems prior to doing any serious work with
95275 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
95276 ** this routine will be called automatically by key routines such as
95277 ** sqlite3_open().  
95278 **
95279 ** This routine is a no-op except on its very first call for the process,
95280 ** or for the first call after a call to sqlite3_shutdown.
95281 **
95282 ** The first thread to call this routine runs the initialization to
95283 ** completion.  If subsequent threads call this routine before the first
95284 ** thread has finished the initialization process, then the subsequent
95285 ** threads must block until the first thread finishes with the initialization.
95286 **
95287 ** The first thread might call this routine recursively.  Recursive
95288 ** calls to this routine should not block, of course.  Otherwise the
95289 ** initialization process would never complete.
95290 **
95291 ** Let X be the first thread to enter this routine.  Let Y be some other
95292 ** thread.  Then while the initial invocation of this routine by X is
95293 ** incomplete, it is required that:
95294 **
95295 **    *  Calls to this routine from Y must block until the outer-most
95296 **       call by X completes.
95297 **
95298 **    *  Recursive calls to this routine from thread X return immediately
95299 **       without blocking.
95300 */
95301 SQLITE_API int sqlite3_initialize(void){
95302   sqlite3_mutex *pMaster;                      /* The main static mutex */
95303   int rc;                                      /* Result code */
95304
95305 #ifdef SQLITE_OMIT_WSD
95306   rc = sqlite3_wsd_init(4096, 24);
95307   if( rc!=SQLITE_OK ){
95308     return rc;
95309   }
95310 #endif
95311
95312   /* If SQLite is already completely initialized, then this call
95313   ** to sqlite3_initialize() should be a no-op.  But the initialization
95314   ** must be complete.  So isInit must not be set until the very end
95315   ** of this routine.
95316   */
95317   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
95318
95319   /* Make sure the mutex subsystem is initialized.  If unable to 
95320   ** initialize the mutex subsystem, return early with the error.
95321   ** If the system is so sick that we are unable to allocate a mutex,
95322   ** there is not much SQLite is going to be able to do.
95323   **
95324   ** The mutex subsystem must take care of serializing its own
95325   ** initialization.
95326   */
95327   rc = sqlite3MutexInit();
95328   if( rc ) return rc;
95329
95330   /* Initialize the malloc() system and the recursive pInitMutex mutex.
95331   ** This operation is protected by the STATIC_MASTER mutex.  Note that
95332   ** MutexAlloc() is called for a static mutex prior to initializing the
95333   ** malloc subsystem - this implies that the allocation of a static
95334   ** mutex must not require support from the malloc subsystem.
95335   */
95336   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
95337   sqlite3_mutex_enter(pMaster);
95338   sqlite3GlobalConfig.isMutexInit = 1;
95339   if( !sqlite3GlobalConfig.isMallocInit ){
95340     rc = sqlite3MallocInit();
95341   }
95342   if( rc==SQLITE_OK ){
95343     sqlite3GlobalConfig.isMallocInit = 1;
95344     if( !sqlite3GlobalConfig.pInitMutex ){
95345       sqlite3GlobalConfig.pInitMutex =
95346            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
95347       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
95348         rc = SQLITE_NOMEM;
95349       }
95350     }
95351   }
95352   if( rc==SQLITE_OK ){
95353     sqlite3GlobalConfig.nRefInitMutex++;
95354   }
95355   sqlite3_mutex_leave(pMaster);
95356
95357   /* If rc is not SQLITE_OK at this point, then either the malloc
95358   ** subsystem could not be initialized or the system failed to allocate
95359   ** the pInitMutex mutex. Return an error in either case.  */
95360   if( rc!=SQLITE_OK ){
95361     return rc;
95362   }
95363
95364   /* Do the rest of the initialization under the recursive mutex so
95365   ** that we will be able to handle recursive calls into
95366   ** sqlite3_initialize().  The recursive calls normally come through
95367   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
95368   ** recursive calls might also be possible.
95369   */
95370   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
95371   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
95372     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
95373     sqlite3GlobalConfig.inProgress = 1;
95374     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
95375     sqlite3RegisterGlobalFunctions();
95376     if( sqlite3GlobalConfig.isPCacheInit==0 ){
95377       rc = sqlite3PcacheInitialize();
95378     }
95379     if( rc==SQLITE_OK ){
95380       sqlite3GlobalConfig.isPCacheInit = 1;
95381       rc = sqlite3OsInit();
95382     }
95383     if( rc==SQLITE_OK ){
95384       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
95385           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
95386       sqlite3GlobalConfig.isInit = 1;
95387     }
95388     sqlite3GlobalConfig.inProgress = 0;
95389   }
95390   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
95391
95392   /* Go back under the static mutex and clean up the recursive
95393   ** mutex to prevent a resource leak.
95394   */
95395   sqlite3_mutex_enter(pMaster);
95396   sqlite3GlobalConfig.nRefInitMutex--;
95397   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
95398     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
95399     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
95400     sqlite3GlobalConfig.pInitMutex = 0;
95401   }
95402   sqlite3_mutex_leave(pMaster);
95403
95404   /* The following is just a sanity check to make sure SQLite has
95405   ** been compiled correctly.  It is important to run this code, but
95406   ** we don't want to run it too often and soak up CPU cycles for no
95407   ** reason.  So we run it once during initialization.
95408   */
95409 #ifndef NDEBUG
95410 #ifndef SQLITE_OMIT_FLOATING_POINT
95411   /* This section of code's only "output" is via assert() statements. */
95412   if ( rc==SQLITE_OK ){
95413     u64 x = (((u64)1)<<63)-1;
95414     double y;
95415     assert(sizeof(x)==8);
95416     assert(sizeof(x)==sizeof(y));
95417     memcpy(&y, &x, 8);
95418     assert( sqlite3IsNaN(y) );
95419   }
95420 #endif
95421 #endif
95422
95423   return rc;
95424 }
95425
95426 /*
95427 ** Undo the effects of sqlite3_initialize().  Must not be called while
95428 ** there are outstanding database connections or memory allocations or
95429 ** while any part of SQLite is otherwise in use in any thread.  This
95430 ** routine is not threadsafe.  But it is safe to invoke this routine
95431 ** on when SQLite is already shut down.  If SQLite is already shut down
95432 ** when this routine is invoked, then this routine is a harmless no-op.
95433 */
95434 SQLITE_API int sqlite3_shutdown(void){
95435   if( sqlite3GlobalConfig.isInit ){
95436     sqlite3_os_end();
95437     sqlite3_reset_auto_extension();
95438     sqlite3GlobalConfig.isInit = 0;
95439   }
95440   if( sqlite3GlobalConfig.isPCacheInit ){
95441     sqlite3PcacheShutdown();
95442     sqlite3GlobalConfig.isPCacheInit = 0;
95443   }
95444   if( sqlite3GlobalConfig.isMallocInit ){
95445     sqlite3MallocEnd();
95446     sqlite3GlobalConfig.isMallocInit = 0;
95447   }
95448   if( sqlite3GlobalConfig.isMutexInit ){
95449     sqlite3MutexEnd();
95450     sqlite3GlobalConfig.isMutexInit = 0;
95451   }
95452
95453   return SQLITE_OK;
95454 }
95455
95456 /*
95457 ** This API allows applications to modify the global configuration of
95458 ** the SQLite library at run-time.
95459 **
95460 ** This routine should only be called when there are no outstanding
95461 ** database connections or memory allocations.  This routine is not
95462 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
95463 ** behavior.
95464 */
95465 SQLITE_API int sqlite3_config(int op, ...){
95466   va_list ap;
95467   int rc = SQLITE_OK;
95468
95469   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
95470   ** the SQLite library is in use. */
95471   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE;
95472
95473   va_start(ap, op);
95474   switch( op ){
95475
95476     /* Mutex configuration options are only available in a threadsafe
95477     ** compile. 
95478     */
95479 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
95480     case SQLITE_CONFIG_SINGLETHREAD: {
95481       /* Disable all mutexing */
95482       sqlite3GlobalConfig.bCoreMutex = 0;
95483       sqlite3GlobalConfig.bFullMutex = 0;
95484       break;
95485     }
95486     case SQLITE_CONFIG_MULTITHREAD: {
95487       /* Disable mutexing of database connections */
95488       /* Enable mutexing of core data structures */
95489       sqlite3GlobalConfig.bCoreMutex = 1;
95490       sqlite3GlobalConfig.bFullMutex = 0;
95491       break;
95492     }
95493     case SQLITE_CONFIG_SERIALIZED: {
95494       /* Enable all mutexing */
95495       sqlite3GlobalConfig.bCoreMutex = 1;
95496       sqlite3GlobalConfig.bFullMutex = 1;
95497       break;
95498     }
95499     case SQLITE_CONFIG_MUTEX: {
95500       /* Specify an alternative mutex implementation */
95501       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
95502       break;
95503     }
95504     case SQLITE_CONFIG_GETMUTEX: {
95505       /* Retrieve the current mutex implementation */
95506       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
95507       break;
95508     }
95509 #endif
95510
95511
95512     case SQLITE_CONFIG_MALLOC: {
95513       /* Specify an alternative malloc implementation */
95514       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
95515       break;
95516     }
95517     case SQLITE_CONFIG_GETMALLOC: {
95518       /* Retrieve the current malloc() implementation */
95519       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
95520       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
95521       break;
95522     }
95523     case SQLITE_CONFIG_MEMSTATUS: {
95524       /* Enable or disable the malloc status collection */
95525       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
95526       break;
95527     }
95528     case SQLITE_CONFIG_SCRATCH: {
95529       /* Designate a buffer for scratch memory space */
95530       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
95531       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
95532       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
95533       break;
95534     }
95535     case SQLITE_CONFIG_PAGECACHE: {
95536       /* Designate a buffer for page cache memory space */
95537       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
95538       sqlite3GlobalConfig.szPage = va_arg(ap, int);
95539       sqlite3GlobalConfig.nPage = va_arg(ap, int);
95540       break;
95541     }
95542
95543     case SQLITE_CONFIG_PCACHE: {
95544       /* Specify an alternative page cache implementation */
95545       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
95546       break;
95547     }
95548
95549     case SQLITE_CONFIG_GETPCACHE: {
95550       if( sqlite3GlobalConfig.pcache.xInit==0 ){
95551         sqlite3PCacheSetDefault();
95552       }
95553       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
95554       break;
95555     }
95556
95557 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
95558     case SQLITE_CONFIG_HEAP: {
95559       /* Designate a buffer for heap memory space */
95560       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
95561       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
95562       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
95563
95564       if( sqlite3GlobalConfig.pHeap==0 ){
95565         /* If the heap pointer is NULL, then restore the malloc implementation
95566         ** back to NULL pointers too.  This will cause the malloc to go
95567         ** back to its default implementation when sqlite3_initialize() is
95568         ** run.
95569         */
95570         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
95571       }else{
95572         /* The heap pointer is not NULL, then install one of the
95573         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
95574         ** ENABLE_MEMSYS5 is defined, return an error.
95575         */
95576 #ifdef SQLITE_ENABLE_MEMSYS3
95577         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
95578 #endif
95579 #ifdef SQLITE_ENABLE_MEMSYS5
95580         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
95581 #endif
95582       }
95583       break;
95584     }
95585 #endif
95586
95587     case SQLITE_CONFIG_LOOKASIDE: {
95588       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
95589       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
95590       break;
95591     }
95592
95593     default: {
95594       rc = SQLITE_ERROR;
95595       break;
95596     }
95597   }
95598   va_end(ap);
95599   return rc;
95600 }
95601
95602 /*
95603 ** Set up the lookaside buffers for a database connection.
95604 ** Return SQLITE_OK on success.  
95605 ** If lookaside is already active, return SQLITE_BUSY.
95606 **
95607 ** The sz parameter is the number of bytes in each lookaside slot.
95608 ** The cnt parameter is the number of slots.  If pStart is NULL the
95609 ** space for the lookaside memory is obtained from sqlite3_malloc().
95610 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
95611 ** the lookaside memory.
95612 */
95613 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
95614   void *pStart;
95615   if( db->lookaside.nOut ){
95616     return SQLITE_BUSY;
95617   }
95618   /* Free any existing lookaside buffer for this handle before
95619   ** allocating a new one so we don't have to have space for 
95620   ** both at the same time.
95621   */
95622   if( db->lookaside.bMalloced ){
95623     sqlite3_free(db->lookaside.pStart);
95624   }
95625   /* The size of a lookaside slot needs to be larger than a pointer
95626   ** to be useful.
95627   */
95628   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
95629   if( cnt<0 ) cnt = 0;
95630   if( sz==0 || cnt==0 ){
95631     sz = 0;
95632     pStart = 0;
95633   }else if( pBuf==0 ){
95634     sz = ROUND8(sz);
95635     sqlite3BeginBenignMalloc();
95636     pStart = sqlite3Malloc( sz*cnt );
95637     sqlite3EndBenignMalloc();
95638   }else{
95639     sz = ROUNDDOWN8(sz);
95640     pStart = pBuf;
95641   }
95642   db->lookaside.pStart = pStart;
95643   db->lookaside.pFree = 0;
95644   db->lookaside.sz = (u16)sz;
95645   if( pStart ){
95646     int i;
95647     LookasideSlot *p;
95648     assert( sz > (int)sizeof(LookasideSlot*) );
95649     p = (LookasideSlot*)pStart;
95650     for(i=cnt-1; i>=0; i--){
95651       p->pNext = db->lookaside.pFree;
95652       db->lookaside.pFree = p;
95653       p = (LookasideSlot*)&((u8*)p)[sz];
95654     }
95655     db->lookaside.pEnd = p;
95656     db->lookaside.bEnabled = 1;
95657     db->lookaside.bMalloced = pBuf==0 ?1:0;
95658   }else{
95659     db->lookaside.pEnd = 0;
95660     db->lookaside.bEnabled = 0;
95661     db->lookaside.bMalloced = 0;
95662   }
95663   return SQLITE_OK;
95664 }
95665
95666 /*
95667 ** Return the mutex associated with a database connection.
95668 */
95669 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
95670   return db->mutex;
95671 }
95672
95673 /*
95674 ** Configuration settings for an individual database connection
95675 */
95676 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
95677   va_list ap;
95678   int rc;
95679   va_start(ap, op);
95680   switch( op ){
95681     case SQLITE_DBCONFIG_LOOKASIDE: {
95682       void *pBuf = va_arg(ap, void*);
95683       int sz = va_arg(ap, int);
95684       int cnt = va_arg(ap, int);
95685       rc = setupLookaside(db, pBuf, sz, cnt);
95686       break;
95687     }
95688     default: {
95689       rc = SQLITE_ERROR;
95690       break;
95691     }
95692   }
95693   va_end(ap);
95694   return rc;
95695 }
95696
95697
95698 /*
95699 ** Return true if the buffer z[0..n-1] contains all spaces.
95700 */
95701 static int allSpaces(const char *z, int n){
95702   while( n>0 && z[n-1]==' ' ){ n--; }
95703   return n==0;
95704 }
95705
95706 /*
95707 ** This is the default collating function named "BINARY" which is always
95708 ** available.
95709 **
95710 ** If the padFlag argument is not NULL then space padding at the end
95711 ** of strings is ignored.  This implements the RTRIM collation.
95712 */
95713 static int binCollFunc(
95714   void *padFlag,
95715   int nKey1, const void *pKey1,
95716   int nKey2, const void *pKey2
95717 ){
95718   int rc, n;
95719   n = nKey1<nKey2 ? nKey1 : nKey2;
95720   rc = memcmp(pKey1, pKey2, n);
95721   if( rc==0 ){
95722     if( padFlag
95723      && allSpaces(((char*)pKey1)+n, nKey1-n)
95724      && allSpaces(((char*)pKey2)+n, nKey2-n)
95725     ){
95726       /* Leave rc unchanged at 0 */
95727     }else{
95728       rc = nKey1 - nKey2;
95729     }
95730   }
95731   return rc;
95732 }
95733
95734 /*
95735 ** Another built-in collating sequence: NOCASE. 
95736 **
95737 ** This collating sequence is intended to be used for "case independant
95738 ** comparison". SQLite's knowledge of upper and lower case equivalents
95739 ** extends only to the 26 characters used in the English language.
95740 **
95741 ** At the moment there is only a UTF-8 implementation.
95742 */
95743 static int nocaseCollatingFunc(
95744   void *NotUsed,
95745   int nKey1, const void *pKey1,
95746   int nKey2, const void *pKey2
95747 ){
95748   int r = sqlite3StrNICmp(
95749       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
95750   UNUSED_PARAMETER(NotUsed);
95751   if( 0==r ){
95752     r = nKey1-nKey2;
95753   }
95754   return r;
95755 }
95756
95757 /*
95758 ** Return the ROWID of the most recent insert
95759 */
95760 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
95761   return db->lastRowid;
95762 }
95763
95764 /*
95765 ** Return the number of changes in the most recent call to sqlite3_exec().
95766 */
95767 SQLITE_API int sqlite3_changes(sqlite3 *db){
95768   return db->nChange;
95769 }
95770
95771 /*
95772 ** Return the number of changes since the database handle was opened.
95773 */
95774 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
95775   return db->nTotalChange;
95776 }
95777
95778 /*
95779 ** Close all open savepoints. This function only manipulates fields of the
95780 ** database handle object, it does not close any savepoints that may be open
95781 ** at the b-tree/pager level.
95782 */
95783 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
95784   while( db->pSavepoint ){
95785     Savepoint *pTmp = db->pSavepoint;
95786     db->pSavepoint = pTmp->pNext;
95787     sqlite3DbFree(db, pTmp);
95788   }
95789   db->nSavepoint = 0;
95790   db->nStatement = 0;
95791   db->isTransactionSavepoint = 0;
95792 }
95793
95794 /*
95795 ** Close an existing SQLite database
95796 */
95797 SQLITE_API int sqlite3_close(sqlite3 *db){
95798   HashElem *i;
95799   int j;
95800
95801   if( !db ){
95802     return SQLITE_OK;
95803   }
95804   if( !sqlite3SafetyCheckSickOrOk(db) ){
95805     return SQLITE_MISUSE;
95806   }
95807   sqlite3_mutex_enter(db->mutex);
95808
95809   sqlite3ResetInternalSchema(db, 0);
95810
95811   /* If a transaction is open, the ResetInternalSchema() call above
95812   ** will not have called the xDisconnect() method on any virtual
95813   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
95814   ** call will do so. We need to do this before the check for active
95815   ** SQL statements below, as the v-table implementation may be storing
95816   ** some prepared statements internally.
95817   */
95818   sqlite3VtabRollback(db);
95819
95820   /* If there are any outstanding VMs, return SQLITE_BUSY. */
95821   if( db->pVdbe ){
95822     sqlite3Error(db, SQLITE_BUSY, 
95823         "unable to close due to unfinalised statements");
95824     sqlite3_mutex_leave(db->mutex);
95825     return SQLITE_BUSY;
95826   }
95827   assert( sqlite3SafetyCheckSickOrOk(db) );
95828
95829   for(j=0; j<db->nDb; j++){
95830     Btree *pBt = db->aDb[j].pBt;
95831     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
95832       sqlite3Error(db, SQLITE_BUSY, 
95833           "unable to close due to unfinished backup operation");
95834       sqlite3_mutex_leave(db->mutex);
95835       return SQLITE_BUSY;
95836     }
95837   }
95838
95839   /* Free any outstanding Savepoint structures. */
95840   sqlite3CloseSavepoints(db);
95841
95842   for(j=0; j<db->nDb; j++){
95843     struct Db *pDb = &db->aDb[j];
95844     if( pDb->pBt ){
95845       sqlite3BtreeClose(pDb->pBt);
95846       pDb->pBt = 0;
95847       if( j!=1 ){
95848         pDb->pSchema = 0;
95849       }
95850     }
95851   }
95852   sqlite3ResetInternalSchema(db, 0);
95853
95854   /* Tell the code in notify.c that the connection no longer holds any
95855   ** locks and does not require any further unlock-notify callbacks.
95856   */
95857   sqlite3ConnectionClosed(db);
95858
95859   assert( db->nDb<=2 );
95860   assert( db->aDb==db->aDbStatic );
95861   for(j=0; j<ArraySize(db->aFunc.a); j++){
95862     FuncDef *pNext, *pHash, *p;
95863     for(p=db->aFunc.a[j]; p; p=pHash){
95864       pHash = p->pHash;
95865       while( p ){
95866         pNext = p->pNext;
95867         sqlite3DbFree(db, p);
95868         p = pNext;
95869       }
95870     }
95871   }
95872   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
95873     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
95874     /* Invoke any destructors registered for collation sequence user data. */
95875     for(j=0; j<3; j++){
95876       if( pColl[j].xDel ){
95877         pColl[j].xDel(pColl[j].pUser);
95878       }
95879     }
95880     sqlite3DbFree(db, pColl);
95881   }
95882   sqlite3HashClear(&db->aCollSeq);
95883 #ifndef SQLITE_OMIT_VIRTUALTABLE
95884   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
95885     Module *pMod = (Module *)sqliteHashData(i);
95886     if( pMod->xDestroy ){
95887       pMod->xDestroy(pMod->pAux);
95888     }
95889     sqlite3DbFree(db, pMod);
95890   }
95891   sqlite3HashClear(&db->aModule);
95892 #endif
95893
95894   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
95895   if( db->pErr ){
95896     sqlite3ValueFree(db->pErr);
95897   }
95898   sqlite3CloseExtensions(db);
95899
95900   db->magic = SQLITE_MAGIC_ERROR;
95901
95902   /* The temp-database schema is allocated differently from the other schema
95903   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
95904   ** So it needs to be freed here. Todo: Why not roll the temp schema into
95905   ** the same sqliteMalloc() as the one that allocates the database 
95906   ** structure?
95907   */
95908   sqlite3DbFree(db, db->aDb[1].pSchema);
95909   sqlite3_mutex_leave(db->mutex);
95910   db->magic = SQLITE_MAGIC_CLOSED;
95911   sqlite3_mutex_free(db->mutex);
95912   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
95913   if( db->lookaside.bMalloced ){
95914     sqlite3_free(db->lookaside.pStart);
95915   }
95916   sqlite3_free(db);
95917   return SQLITE_OK;
95918 }
95919
95920 /*
95921 ** Rollback all database files.
95922 */
95923 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
95924   int i;
95925   int inTrans = 0;
95926   assert( sqlite3_mutex_held(db->mutex) );
95927   sqlite3BeginBenignMalloc();
95928   for(i=0; i<db->nDb; i++){
95929     if( db->aDb[i].pBt ){
95930       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
95931         inTrans = 1;
95932       }
95933       sqlite3BtreeRollback(db->aDb[i].pBt);
95934       db->aDb[i].inTrans = 0;
95935     }
95936   }
95937   sqlite3VtabRollback(db);
95938   sqlite3EndBenignMalloc();
95939
95940   if( db->flags&SQLITE_InternChanges ){
95941     sqlite3ExpirePreparedStatements(db);
95942     sqlite3ResetInternalSchema(db, 0);
95943   }
95944
95945   /* Any deferred constraint violations have now been resolved. */
95946   db->nDeferredCons = 0;
95947
95948   /* If one has been configured, invoke the rollback-hook callback */
95949   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
95950     db->xRollbackCallback(db->pRollbackArg);
95951   }
95952 }
95953
95954 /*
95955 ** Return a static string that describes the kind of error specified in the
95956 ** argument.
95957 */
95958 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
95959   static const char* const aMsg[] = {
95960     /* SQLITE_OK          */ "not an error",
95961     /* SQLITE_ERROR       */ "SQL logic error or missing database",
95962     /* SQLITE_INTERNAL    */ 0,
95963     /* SQLITE_PERM        */ "access permission denied",
95964     /* SQLITE_ABORT       */ "callback requested query abort",
95965     /* SQLITE_BUSY        */ "database is locked",
95966     /* SQLITE_LOCKED      */ "database table is locked",
95967     /* SQLITE_NOMEM       */ "out of memory",
95968     /* SQLITE_READONLY    */ "attempt to write a readonly database",
95969     /* SQLITE_INTERRUPT   */ "interrupted",
95970     /* SQLITE_IOERR       */ "disk I/O error",
95971     /* SQLITE_CORRUPT     */ "database disk image is malformed",
95972     /* SQLITE_NOTFOUND    */ 0,
95973     /* SQLITE_FULL        */ "database or disk is full",
95974     /* SQLITE_CANTOPEN    */ "unable to open database file",
95975     /* SQLITE_PROTOCOL    */ 0,
95976     /* SQLITE_EMPTY       */ "table contains no data",
95977     /* SQLITE_SCHEMA      */ "database schema has changed",
95978     /* SQLITE_TOOBIG      */ "string or blob too big",
95979     /* SQLITE_CONSTRAINT  */ "constraint failed",
95980     /* SQLITE_MISMATCH    */ "datatype mismatch",
95981     /* SQLITE_MISUSE      */ "library routine called out of sequence",
95982     /* SQLITE_NOLFS       */ "large file support is disabled",
95983     /* SQLITE_AUTH        */ "authorization denied",
95984     /* SQLITE_FORMAT      */ "auxiliary database format error",
95985     /* SQLITE_RANGE       */ "bind or column index out of range",
95986     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
95987   };
95988   rc &= 0xff;
95989   if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
95990     return aMsg[rc];
95991   }else{
95992     return "unknown error";
95993   }
95994 }
95995
95996 /*
95997 ** This routine implements a busy callback that sleeps and tries
95998 ** again until a timeout value is reached.  The timeout value is
95999 ** an integer number of milliseconds passed in as the first
96000 ** argument.
96001 */
96002 static int sqliteDefaultBusyCallback(
96003  void *ptr,               /* Database connection */
96004  int count                /* Number of times table has been busy */
96005 ){
96006 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
96007   static const u8 delays[] =
96008      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
96009   static const u8 totals[] =
96010      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
96011 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
96012   sqlite3 *db = (sqlite3 *)ptr;
96013   int timeout = db->busyTimeout;
96014   int delay, prior;
96015
96016   assert( count>=0 );
96017   if( count < NDELAY ){
96018     delay = delays[count];
96019     prior = totals[count];
96020   }else{
96021     delay = delays[NDELAY-1];
96022     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
96023   }
96024   if( prior + delay > timeout ){
96025     delay = timeout - prior;
96026     if( delay<=0 ) return 0;
96027   }
96028   sqlite3OsSleep(db->pVfs, delay*1000);
96029   return 1;
96030 #else
96031   sqlite3 *db = (sqlite3 *)ptr;
96032   int timeout = ((sqlite3 *)ptr)->busyTimeout;
96033   if( (count+1)*1000 > timeout ){
96034     return 0;
96035   }
96036   sqlite3OsSleep(db->pVfs, 1000000);
96037   return 1;
96038 #endif
96039 }
96040
96041 /*
96042 ** Invoke the given busy handler.
96043 **
96044 ** This routine is called when an operation failed with a lock.
96045 ** If this routine returns non-zero, the lock is retried.  If it
96046 ** returns 0, the operation aborts with an SQLITE_BUSY error.
96047 */
96048 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
96049   int rc;
96050   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
96051   rc = p->xFunc(p->pArg, p->nBusy);
96052   if( rc==0 ){
96053     p->nBusy = -1;
96054   }else{
96055     p->nBusy++;
96056   }
96057   return rc; 
96058 }
96059
96060 /*
96061 ** This routine sets the busy callback for an Sqlite database to the
96062 ** given callback function with the given argument.
96063 */
96064 SQLITE_API int sqlite3_busy_handler(
96065   sqlite3 *db,
96066   int (*xBusy)(void*,int),
96067   void *pArg
96068 ){
96069   sqlite3_mutex_enter(db->mutex);
96070   db->busyHandler.xFunc = xBusy;
96071   db->busyHandler.pArg = pArg;
96072   db->busyHandler.nBusy = 0;
96073   sqlite3_mutex_leave(db->mutex);
96074   return SQLITE_OK;
96075 }
96076
96077 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
96078 /*
96079 ** This routine sets the progress callback for an Sqlite database to the
96080 ** given callback function with the given argument. The progress callback will
96081 ** be invoked every nOps opcodes.
96082 */
96083 SQLITE_API void sqlite3_progress_handler(
96084   sqlite3 *db, 
96085   int nOps,
96086   int (*xProgress)(void*), 
96087   void *pArg
96088 ){
96089   sqlite3_mutex_enter(db->mutex);
96090   if( nOps>0 ){
96091     db->xProgress = xProgress;
96092     db->nProgressOps = nOps;
96093     db->pProgressArg = pArg;
96094   }else{
96095     db->xProgress = 0;
96096     db->nProgressOps = 0;
96097     db->pProgressArg = 0;
96098   }
96099   sqlite3_mutex_leave(db->mutex);
96100 }
96101 #endif
96102
96103
96104 /*
96105 ** This routine installs a default busy handler that waits for the
96106 ** specified number of milliseconds before returning 0.
96107 */
96108 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
96109   if( ms>0 ){
96110     db->busyTimeout = ms;
96111     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
96112   }else{
96113     sqlite3_busy_handler(db, 0, 0);
96114   }
96115   return SQLITE_OK;
96116 }
96117
96118 /*
96119 ** Cause any pending operation to stop at its earliest opportunity.
96120 */
96121 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
96122   db->u1.isInterrupted = 1;
96123 }
96124
96125
96126 /*
96127 ** This function is exactly the same as sqlite3_create_function(), except
96128 ** that it is designed to be called by internal code. The difference is
96129 ** that if a malloc() fails in sqlite3_create_function(), an error code
96130 ** is returned and the mallocFailed flag cleared. 
96131 */
96132 SQLITE_PRIVATE int sqlite3CreateFunc(
96133   sqlite3 *db,
96134   const char *zFunctionName,
96135   int nArg,
96136   int enc,
96137   void *pUserData,
96138   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
96139   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
96140   void (*xFinal)(sqlite3_context*)
96141 ){
96142   FuncDef *p;
96143   int nName;
96144
96145   assert( sqlite3_mutex_held(db->mutex) );
96146   if( zFunctionName==0 ||
96147       (xFunc && (xFinal || xStep)) || 
96148       (!xFunc && (xFinal && !xStep)) ||
96149       (!xFunc && (!xFinal && xStep)) ||
96150       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
96151       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
96152     return SQLITE_MISUSE;
96153   }
96154   
96155 #ifndef SQLITE_OMIT_UTF16
96156   /* If SQLITE_UTF16 is specified as the encoding type, transform this
96157   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
96158   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
96159   **
96160   ** If SQLITE_ANY is specified, add three versions of the function
96161   ** to the hash table.
96162   */
96163   if( enc==SQLITE_UTF16 ){
96164     enc = SQLITE_UTF16NATIVE;
96165   }else if( enc==SQLITE_ANY ){
96166     int rc;
96167     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
96168          pUserData, xFunc, xStep, xFinal);
96169     if( rc==SQLITE_OK ){
96170       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
96171           pUserData, xFunc, xStep, xFinal);
96172     }
96173     if( rc!=SQLITE_OK ){
96174       return rc;
96175     }
96176     enc = SQLITE_UTF16BE;
96177   }
96178 #else
96179   enc = SQLITE_UTF8;
96180 #endif
96181   
96182   /* Check if an existing function is being overridden or deleted. If so,
96183   ** and there are active VMs, then return SQLITE_BUSY. If a function
96184   ** is being overridden/deleted but there are no active VMs, allow the
96185   ** operation to continue but invalidate all precompiled statements.
96186   */
96187   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
96188   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
96189     if( db->activeVdbeCnt ){
96190       sqlite3Error(db, SQLITE_BUSY, 
96191         "unable to delete/modify user-function due to active statements");
96192       assert( !db->mallocFailed );
96193       return SQLITE_BUSY;
96194     }else{
96195       sqlite3ExpirePreparedStatements(db);
96196     }
96197   }
96198
96199   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
96200   assert(p || db->mallocFailed);
96201   if( !p ){
96202     return SQLITE_NOMEM;
96203   }
96204   p->flags = 0;
96205   p->xFunc = xFunc;
96206   p->xStep = xStep;
96207   p->xFinalize = xFinal;
96208   p->pUserData = pUserData;
96209   p->nArg = (u16)nArg;
96210   return SQLITE_OK;
96211 }
96212
96213 /*
96214 ** Create new user functions.
96215 */
96216 SQLITE_API int sqlite3_create_function(
96217   sqlite3 *db,
96218   const char *zFunctionName,
96219   int nArg,
96220   int enc,
96221   void *p,
96222   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
96223   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
96224   void (*xFinal)(sqlite3_context*)
96225 ){
96226   int rc;
96227   sqlite3_mutex_enter(db->mutex);
96228   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
96229   rc = sqlite3ApiExit(db, rc);
96230   sqlite3_mutex_leave(db->mutex);
96231   return rc;
96232 }
96233
96234 #ifndef SQLITE_OMIT_UTF16
96235 SQLITE_API int sqlite3_create_function16(
96236   sqlite3 *db,
96237   const void *zFunctionName,
96238   int nArg,
96239   int eTextRep,
96240   void *p,
96241   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
96242   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
96243   void (*xFinal)(sqlite3_context*)
96244 ){
96245   int rc;
96246   char *zFunc8;
96247   sqlite3_mutex_enter(db->mutex);
96248   assert( !db->mallocFailed );
96249   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
96250   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
96251   sqlite3DbFree(db, zFunc8);
96252   rc = sqlite3ApiExit(db, rc);
96253   sqlite3_mutex_leave(db->mutex);
96254   return rc;
96255 }
96256 #endif
96257
96258
96259 /*
96260 ** Declare that a function has been overloaded by a virtual table.
96261 **
96262 ** If the function already exists as a regular global function, then
96263 ** this routine is a no-op.  If the function does not exist, then create
96264 ** a new one that always throws a run-time error.  
96265 **
96266 ** When virtual tables intend to provide an overloaded function, they
96267 ** should call this routine to make sure the global function exists.
96268 ** A global function must exist in order for name resolution to work
96269 ** properly.
96270 */
96271 SQLITE_API int sqlite3_overload_function(
96272   sqlite3 *db,
96273   const char *zName,
96274   int nArg
96275 ){
96276   int nName = sqlite3Strlen30(zName);
96277   int rc;
96278   sqlite3_mutex_enter(db->mutex);
96279   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
96280     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
96281                       0, sqlite3InvalidFunction, 0, 0);
96282   }
96283   rc = sqlite3ApiExit(db, SQLITE_OK);
96284   sqlite3_mutex_leave(db->mutex);
96285   return rc;
96286 }
96287
96288 #ifndef SQLITE_OMIT_TRACE
96289 /*
96290 ** Register a trace function.  The pArg from the previously registered trace
96291 ** is returned.  
96292 **
96293 ** A NULL trace function means that no tracing is executes.  A non-NULL
96294 ** trace is a pointer to a function that is invoked at the start of each
96295 ** SQL statement.
96296 */
96297 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
96298   void *pOld;
96299   sqlite3_mutex_enter(db->mutex);
96300   pOld = db->pTraceArg;
96301   db->xTrace = xTrace;
96302   db->pTraceArg = pArg;
96303   sqlite3_mutex_leave(db->mutex);
96304   return pOld;
96305 }
96306 /*
96307 ** Register a profile function.  The pArg from the previously registered 
96308 ** profile function is returned.  
96309 **
96310 ** A NULL profile function means that no profiling is executes.  A non-NULL
96311 ** profile is a pointer to a function that is invoked at the conclusion of
96312 ** each SQL statement that is run.
96313 */
96314 SQLITE_API void *sqlite3_profile(
96315   sqlite3 *db,
96316   void (*xProfile)(void*,const char*,sqlite_uint64),
96317   void *pArg
96318 ){
96319   void *pOld;
96320   sqlite3_mutex_enter(db->mutex);
96321   pOld = db->pProfileArg;
96322   db->xProfile = xProfile;
96323   db->pProfileArg = pArg;
96324   sqlite3_mutex_leave(db->mutex);
96325   return pOld;
96326 }
96327 #endif /* SQLITE_OMIT_TRACE */
96328
96329 /*** EXPERIMENTAL ***
96330 **
96331 ** Register a function to be invoked when a transaction comments.
96332 ** If the invoked function returns non-zero, then the commit becomes a
96333 ** rollback.
96334 */
96335 SQLITE_API void *sqlite3_commit_hook(
96336   sqlite3 *db,              /* Attach the hook to this database */
96337   int (*xCallback)(void*),  /* Function to invoke on each commit */
96338   void *pArg                /* Argument to the function */
96339 ){
96340   void *pOld;
96341   sqlite3_mutex_enter(db->mutex);
96342   pOld = db->pCommitArg;
96343   db->xCommitCallback = xCallback;
96344   db->pCommitArg = pArg;
96345   sqlite3_mutex_leave(db->mutex);
96346   return pOld;
96347 }
96348
96349 /*
96350 ** Register a callback to be invoked each time a row is updated,
96351 ** inserted or deleted using this database connection.
96352 */
96353 SQLITE_API void *sqlite3_update_hook(
96354   sqlite3 *db,              /* Attach the hook to this database */
96355   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
96356   void *pArg                /* Argument to the function */
96357 ){
96358   void *pRet;
96359   sqlite3_mutex_enter(db->mutex);
96360   pRet = db->pUpdateArg;
96361   db->xUpdateCallback = xCallback;
96362   db->pUpdateArg = pArg;
96363   sqlite3_mutex_leave(db->mutex);
96364   return pRet;
96365 }
96366
96367 /*
96368 ** Register a callback to be invoked each time a transaction is rolled
96369 ** back by this database connection.
96370 */
96371 SQLITE_API void *sqlite3_rollback_hook(
96372   sqlite3 *db,              /* Attach the hook to this database */
96373   void (*xCallback)(void*), /* Callback function */
96374   void *pArg                /* Argument to the function */
96375 ){
96376   void *pRet;
96377   sqlite3_mutex_enter(db->mutex);
96378   pRet = db->pRollbackArg;
96379   db->xRollbackCallback = xCallback;
96380   db->pRollbackArg = pArg;
96381   sqlite3_mutex_leave(db->mutex);
96382   return pRet;
96383 }
96384
96385 /*
96386 ** This function returns true if main-memory should be used instead of
96387 ** a temporary file for transient pager files and statement journals.
96388 ** The value returned depends on the value of db->temp_store (runtime
96389 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
96390 ** following table describes the relationship between these two values
96391 ** and this functions return value.
96392 **
96393 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
96394 **   -----------------     --------------     ------------------------------
96395 **   0                     any                file      (return 0)
96396 **   1                     1                  file      (return 0)
96397 **   1                     2                  memory    (return 1)
96398 **   1                     0                  file      (return 0)
96399 **   2                     1                  file      (return 0)
96400 **   2                     2                  memory    (return 1)
96401 **   2                     0                  memory    (return 1)
96402 **   3                     any                memory    (return 1)
96403 */
96404 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
96405 #if SQLITE_TEMP_STORE==1
96406   return ( db->temp_store==2 );
96407 #endif
96408 #if SQLITE_TEMP_STORE==2
96409   return ( db->temp_store!=1 );
96410 #endif
96411 #if SQLITE_TEMP_STORE==3
96412   return 1;
96413 #endif
96414 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
96415   return 0;
96416 #endif
96417 }
96418
96419 /*
96420 ** This routine is called to create a connection to a database BTree
96421 ** driver.  If zFilename is the name of a file, then that file is
96422 ** opened and used.  If zFilename is the magic name ":memory:" then
96423 ** the database is stored in memory (and is thus forgotten as soon as
96424 ** the connection is closed.)  If zFilename is NULL then the database
96425 ** is a "virtual" database for transient use only and is deleted as
96426 ** soon as the connection is closed.
96427 **
96428 ** A virtual database can be either a disk file (that is automatically
96429 ** deleted when the file is closed) or it an be held entirely in memory.
96430 ** The sqlite3TempInMemory() function is used to determine which.
96431 */
96432 SQLITE_PRIVATE int sqlite3BtreeFactory(
96433   sqlite3 *db,              /* Main database when opening aux otherwise 0 */
96434   const char *zFilename,    /* Name of the file containing the BTree database */
96435   int omitJournal,          /* if TRUE then do not journal this file */
96436   int nCache,               /* How many pages in the page cache */
96437   int vfsFlags,             /* Flags passed through to vfsOpen */
96438   Btree **ppBtree           /* Pointer to new Btree object written here */
96439 ){
96440   int btFlags = 0;
96441   int rc;
96442   
96443   assert( sqlite3_mutex_held(db->mutex) );
96444   assert( ppBtree != 0);
96445   if( omitJournal ){
96446     btFlags |= BTREE_OMIT_JOURNAL;
96447   }
96448   if( db->flags & SQLITE_NoReadlock ){
96449     btFlags |= BTREE_NO_READLOCK;
96450   }
96451 #ifndef SQLITE_OMIT_MEMORYDB
96452   if( zFilename==0 && sqlite3TempInMemory(db) ){
96453     zFilename = ":memory:";
96454   }
96455 #endif
96456
96457   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
96458     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
96459   }
96460   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
96461
96462   /* If the B-Tree was successfully opened, set the pager-cache size to the
96463   ** default value. Except, if the call to BtreeOpen() returned a handle
96464   ** open on an existing shared pager-cache, do not change the pager-cache 
96465   ** size.
96466   */
96467   if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
96468     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
96469   }
96470   return rc;
96471 }
96472
96473 /*
96474 ** Return UTF-8 encoded English language explanation of the most recent
96475 ** error.
96476 */
96477 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
96478   const char *z;
96479   if( !db ){
96480     return sqlite3ErrStr(SQLITE_NOMEM);
96481   }
96482   if( !sqlite3SafetyCheckSickOrOk(db) ){
96483     return sqlite3ErrStr(SQLITE_MISUSE);
96484   }
96485   sqlite3_mutex_enter(db->mutex);
96486   if( db->mallocFailed ){
96487     z = sqlite3ErrStr(SQLITE_NOMEM);
96488   }else{
96489     z = (char*)sqlite3_value_text(db->pErr);
96490     assert( !db->mallocFailed );
96491     if( z==0 ){
96492       z = sqlite3ErrStr(db->errCode);
96493     }
96494   }
96495   sqlite3_mutex_leave(db->mutex);
96496   return z;
96497 }
96498
96499 #ifndef SQLITE_OMIT_UTF16
96500 /*
96501 ** Return UTF-16 encoded English language explanation of the most recent
96502 ** error.
96503 */
96504 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
96505   static const u16 outOfMem[] = {
96506     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
96507   };
96508   static const u16 misuse[] = {
96509     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
96510     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
96511     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
96512     'o', 'u', 't', ' ', 
96513     'o', 'f', ' ', 
96514     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
96515   };
96516
96517   const void *z;
96518   if( !db ){
96519     return (void *)outOfMem;
96520   }
96521   if( !sqlite3SafetyCheckSickOrOk(db) ){
96522     return (void *)misuse;
96523   }
96524   sqlite3_mutex_enter(db->mutex);
96525   if( db->mallocFailed ){
96526     z = (void *)outOfMem;
96527   }else{
96528     z = sqlite3_value_text16(db->pErr);
96529     if( z==0 ){
96530       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
96531            SQLITE_UTF8, SQLITE_STATIC);
96532       z = sqlite3_value_text16(db->pErr);
96533     }
96534     /* A malloc() may have failed within the call to sqlite3_value_text16()
96535     ** above. If this is the case, then the db->mallocFailed flag needs to
96536     ** be cleared before returning. Do this directly, instead of via
96537     ** sqlite3ApiExit(), to avoid setting the database handle error message.
96538     */
96539     db->mallocFailed = 0;
96540   }
96541   sqlite3_mutex_leave(db->mutex);
96542   return z;
96543 }
96544 #endif /* SQLITE_OMIT_UTF16 */
96545
96546 /*
96547 ** Return the most recent error code generated by an SQLite routine. If NULL is
96548 ** passed to this function, we assume a malloc() failed during sqlite3_open().
96549 */
96550 SQLITE_API int sqlite3_errcode(sqlite3 *db){
96551   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
96552     return SQLITE_MISUSE;
96553   }
96554   if( !db || db->mallocFailed ){
96555     return SQLITE_NOMEM;
96556   }
96557   return db->errCode & db->errMask;
96558 }
96559 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
96560   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
96561     return SQLITE_MISUSE;
96562   }
96563   if( !db || db->mallocFailed ){
96564     return SQLITE_NOMEM;
96565   }
96566   return db->errCode;
96567 }
96568
96569 /*
96570 ** Create a new collating function for database "db".  The name is zName
96571 ** and the encoding is enc.
96572 */
96573 static int createCollation(
96574   sqlite3* db,
96575   const char *zName, 
96576   u8 enc,
96577   u8 collType,
96578   void* pCtx,
96579   int(*xCompare)(void*,int,const void*,int,const void*),
96580   void(*xDel)(void*)
96581 ){
96582   CollSeq *pColl;
96583   int enc2;
96584   int nName = sqlite3Strlen30(zName);
96585   
96586   assert( sqlite3_mutex_held(db->mutex) );
96587
96588   /* If SQLITE_UTF16 is specified as the encoding type, transform this
96589   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
96590   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
96591   */
96592   enc2 = enc;
96593   testcase( enc2==SQLITE_UTF16 );
96594   testcase( enc2==SQLITE_UTF16_ALIGNED );
96595   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
96596     enc2 = SQLITE_UTF16NATIVE;
96597   }
96598   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
96599     return SQLITE_MISUSE;
96600   }
96601
96602   /* Check if this call is removing or replacing an existing collation 
96603   ** sequence. If so, and there are active VMs, return busy. If there
96604   ** are no active VMs, invalidate any pre-compiled statements.
96605   */
96606   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
96607   if( pColl && pColl->xCmp ){
96608     if( db->activeVdbeCnt ){
96609       sqlite3Error(db, SQLITE_BUSY, 
96610         "unable to delete/modify collation sequence due to active statements");
96611       return SQLITE_BUSY;
96612     }
96613     sqlite3ExpirePreparedStatements(db);
96614
96615     /* If collation sequence pColl was created directly by a call to
96616     ** sqlite3_create_collation, and not generated by synthCollSeq(),
96617     ** then any copies made by synthCollSeq() need to be invalidated.
96618     ** Also, collation destructor - CollSeq.xDel() - function may need
96619     ** to be called.
96620     */ 
96621     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
96622       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
96623       int j;
96624       for(j=0; j<3; j++){
96625         CollSeq *p = &aColl[j];
96626         if( p->enc==pColl->enc ){
96627           if( p->xDel ){
96628             p->xDel(p->pUser);
96629           }
96630           p->xCmp = 0;
96631         }
96632       }
96633     }
96634   }
96635
96636   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
96637   if( pColl ){
96638     pColl->xCmp = xCompare;
96639     pColl->pUser = pCtx;
96640     pColl->xDel = xDel;
96641     pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
96642     pColl->type = collType;
96643   }
96644   sqlite3Error(db, SQLITE_OK, 0);
96645   return SQLITE_OK;
96646 }
96647
96648
96649 /*
96650 ** This array defines hard upper bounds on limit values.  The
96651 ** initializer must be kept in sync with the SQLITE_LIMIT_*
96652 ** #defines in sqlite3.h.
96653 */
96654 static const int aHardLimit[] = {
96655   SQLITE_MAX_LENGTH,
96656   SQLITE_MAX_SQL_LENGTH,
96657   SQLITE_MAX_COLUMN,
96658   SQLITE_MAX_EXPR_DEPTH,
96659   SQLITE_MAX_COMPOUND_SELECT,
96660   SQLITE_MAX_VDBE_OP,
96661   SQLITE_MAX_FUNCTION_ARG,
96662   SQLITE_MAX_ATTACHED,
96663   SQLITE_MAX_LIKE_PATTERN_LENGTH,
96664   SQLITE_MAX_VARIABLE_NUMBER,
96665   SQLITE_MAX_TRIGGER_DEPTH,
96666 };
96667
96668 /*
96669 ** Make sure the hard limits are set to reasonable values
96670 */
96671 #if SQLITE_MAX_LENGTH<100
96672 # error SQLITE_MAX_LENGTH must be at least 100
96673 #endif
96674 #if SQLITE_MAX_SQL_LENGTH<100
96675 # error SQLITE_MAX_SQL_LENGTH must be at least 100
96676 #endif
96677 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
96678 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
96679 #endif
96680 #if SQLITE_MAX_COMPOUND_SELECT<2
96681 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
96682 #endif
96683 #if SQLITE_MAX_VDBE_OP<40
96684 # error SQLITE_MAX_VDBE_OP must be at least 40
96685 #endif
96686 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
96687 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
96688 #endif
96689 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
96690 # error SQLITE_MAX_ATTACHED must be between 0 and 30
96691 #endif
96692 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
96693 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
96694 #endif
96695 #if SQLITE_MAX_COLUMN>32767
96696 # error SQLITE_MAX_COLUMN must not exceed 32767
96697 #endif
96698 #if SQLITE_MAX_TRIGGER_DEPTH<1
96699 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
96700 #endif
96701
96702
96703 /*
96704 ** Change the value of a limit.  Report the old value.
96705 ** If an invalid limit index is supplied, report -1.
96706 ** Make no changes but still report the old value if the
96707 ** new limit is negative.
96708 **
96709 ** A new lower limit does not shrink existing constructs.
96710 ** It merely prevents new constructs that exceed the limit
96711 ** from forming.
96712 */
96713 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
96714   int oldLimit;
96715   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
96716     return -1;
96717   }
96718   oldLimit = db->aLimit[limitId];
96719   if( newLimit>=0 ){
96720     if( newLimit>aHardLimit[limitId] ){
96721       newLimit = aHardLimit[limitId];
96722     }
96723     db->aLimit[limitId] = newLimit;
96724   }
96725   return oldLimit;
96726 }
96727
96728 /*
96729 ** This routine does the work of opening a database on behalf of
96730 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
96731 ** is UTF-8 encoded.
96732 */
96733 static int openDatabase(
96734   const char *zFilename, /* Database filename UTF-8 encoded */
96735   sqlite3 **ppDb,        /* OUT: Returned database handle */
96736   unsigned flags,        /* Operational flags */
96737   const char *zVfs       /* Name of the VFS to use */
96738 ){
96739   sqlite3 *db;
96740   int rc;
96741   int isThreadsafe;
96742
96743   *ppDb = 0;
96744 #ifndef SQLITE_OMIT_AUTOINIT
96745   rc = sqlite3_initialize();
96746   if( rc ) return rc;
96747 #endif
96748
96749   if( sqlite3GlobalConfig.bCoreMutex==0 ){
96750     isThreadsafe = 0;
96751   }else if( flags & SQLITE_OPEN_NOMUTEX ){
96752     isThreadsafe = 0;
96753   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
96754     isThreadsafe = 1;
96755   }else{
96756     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
96757   }
96758   if( flags & SQLITE_OPEN_PRIVATECACHE ){
96759     flags &= ~SQLITE_OPEN_SHAREDCACHE;
96760   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
96761     flags |= SQLITE_OPEN_SHAREDCACHE;
96762   }
96763
96764   /* Remove harmful bits from the flags parameter
96765   **
96766   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
96767   ** dealt with in the previous code block.  Besides these, the only
96768   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
96769   ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE.  Silently mask
96770   ** off all other flags.
96771   */
96772   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
96773                SQLITE_OPEN_EXCLUSIVE |
96774                SQLITE_OPEN_MAIN_DB |
96775                SQLITE_OPEN_TEMP_DB | 
96776                SQLITE_OPEN_TRANSIENT_DB | 
96777                SQLITE_OPEN_MAIN_JOURNAL | 
96778                SQLITE_OPEN_TEMP_JOURNAL | 
96779                SQLITE_OPEN_SUBJOURNAL | 
96780                SQLITE_OPEN_MASTER_JOURNAL |
96781                SQLITE_OPEN_NOMUTEX |
96782                SQLITE_OPEN_FULLMUTEX
96783              );
96784
96785   /* Allocate the sqlite data structure */
96786   db = sqlite3MallocZero( sizeof(sqlite3) );
96787   if( db==0 ) goto opendb_out;
96788   if( isThreadsafe ){
96789     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
96790     if( db->mutex==0 ){
96791       sqlite3_free(db);
96792       db = 0;
96793       goto opendb_out;
96794     }
96795   }
96796   sqlite3_mutex_enter(db->mutex);
96797   db->errMask = 0xff;
96798   db->nDb = 2;
96799   db->magic = SQLITE_MAGIC_BUSY;
96800   db->aDb = db->aDbStatic;
96801
96802   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
96803   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
96804   db->autoCommit = 1;
96805   db->nextAutovac = -1;
96806   db->nextPagesize = 0;
96807   db->flags |= SQLITE_ShortColNames
96808 #if SQLITE_DEFAULT_FILE_FORMAT<4
96809                  | SQLITE_LegacyFileFmt
96810 #endif
96811 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
96812                  | SQLITE_LoadExtension
96813 #endif
96814 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
96815                  | SQLITE_RecTriggers
96816 #endif
96817       ;
96818   sqlite3HashInit(&db->aCollSeq);
96819 #ifndef SQLITE_OMIT_VIRTUALTABLE
96820   sqlite3HashInit(&db->aModule);
96821 #endif
96822
96823   db->pVfs = sqlite3_vfs_find(zVfs);
96824   if( !db->pVfs ){
96825     rc = SQLITE_ERROR;
96826     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
96827     goto opendb_out;
96828   }
96829
96830   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
96831   ** and UTF-16, so add a version for each to avoid any unnecessary
96832   ** conversions. The only error that can occur here is a malloc() failure.
96833   */
96834   createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
96835                   binCollFunc, 0);
96836   createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
96837                   binCollFunc, 0);
96838   createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
96839                   binCollFunc, 0);
96840   createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
96841                   binCollFunc, 0);
96842   if( db->mallocFailed ){
96843     goto opendb_out;
96844   }
96845   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
96846   assert( db->pDfltColl!=0 );
96847
96848   /* Also add a UTF-8 case-insensitive collation sequence. */
96849   createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
96850                   nocaseCollatingFunc, 0);
96851
96852   /* Open the backend database driver */
96853   db->openFlags = flags;
96854   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, 
96855                            flags | SQLITE_OPEN_MAIN_DB,
96856                            &db->aDb[0].pBt);
96857   if( rc!=SQLITE_OK ){
96858     if( rc==SQLITE_IOERR_NOMEM ){
96859       rc = SQLITE_NOMEM;
96860     }
96861     sqlite3Error(db, rc, 0);
96862     goto opendb_out;
96863   }
96864   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
96865   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
96866
96867
96868   /* The default safety_level for the main database is 'full'; for the temp
96869   ** database it is 'NONE'. This matches the pager layer defaults.  
96870   */
96871   db->aDb[0].zName = "main";
96872   db->aDb[0].safety_level = 3;
96873   db->aDb[1].zName = "temp";
96874   db->aDb[1].safety_level = 1;
96875
96876   db->magic = SQLITE_MAGIC_OPEN;
96877   if( db->mallocFailed ){
96878     goto opendb_out;
96879   }
96880
96881   /* Register all built-in functions, but do not attempt to read the
96882   ** database schema yet. This is delayed until the first time the database
96883   ** is accessed.
96884   */
96885   sqlite3Error(db, SQLITE_OK, 0);
96886   sqlite3RegisterBuiltinFunctions(db);
96887
96888   /* Load automatic extensions - extensions that have been registered
96889   ** using the sqlite3_automatic_extension() API.
96890   */
96891   sqlite3AutoLoadExtensions(db);
96892   rc = sqlite3_errcode(db);
96893   if( rc!=SQLITE_OK ){
96894     goto opendb_out;
96895   }
96896
96897 #ifdef SQLITE_ENABLE_FTS1
96898   if( !db->mallocFailed ){
96899     extern int sqlite3Fts1Init(sqlite3*);
96900     rc = sqlite3Fts1Init(db);
96901   }
96902 #endif
96903
96904 #ifdef SQLITE_ENABLE_FTS2
96905   if( !db->mallocFailed && rc==SQLITE_OK ){
96906     extern int sqlite3Fts2Init(sqlite3*);
96907     rc = sqlite3Fts2Init(db);
96908   }
96909 #endif
96910
96911 #ifdef SQLITE_ENABLE_FTS3
96912   if( !db->mallocFailed && rc==SQLITE_OK ){
96913     rc = sqlite3Fts3Init(db);
96914   }
96915 #endif
96916
96917 #ifdef SQLITE_ENABLE_ICU
96918   if( !db->mallocFailed && rc==SQLITE_OK ){
96919     rc = sqlite3IcuInit(db);
96920   }
96921 #endif
96922
96923 #ifdef SQLITE_ENABLE_RTREE
96924   if( !db->mallocFailed && rc==SQLITE_OK){
96925     rc = sqlite3RtreeInit(db);
96926   }
96927 #endif
96928
96929   sqlite3Error(db, rc, 0);
96930
96931   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
96932   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
96933   ** mode.  Doing nothing at all also makes NORMAL the default.
96934   */
96935 #ifdef SQLITE_DEFAULT_LOCKING_MODE
96936   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
96937   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
96938                           SQLITE_DEFAULT_LOCKING_MODE);
96939 #endif
96940
96941   /* Enable the lookaside-malloc subsystem */
96942   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
96943                         sqlite3GlobalConfig.nLookaside);
96944
96945 opendb_out:
96946   if( db ){
96947     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
96948     sqlite3_mutex_leave(db->mutex);
96949   }
96950   rc = sqlite3_errcode(db);
96951   if( rc==SQLITE_NOMEM ){
96952     sqlite3_close(db);
96953     db = 0;
96954   }else if( rc!=SQLITE_OK ){
96955     db->magic = SQLITE_MAGIC_SICK;
96956   }
96957   *ppDb = db;
96958   return sqlite3ApiExit(0, rc);
96959 }
96960
96961 /*
96962 ** Open a new database handle.
96963 */
96964 SQLITE_API int sqlite3_open(
96965   const char *zFilename, 
96966   sqlite3 **ppDb 
96967 ){
96968   return openDatabase(zFilename, ppDb,
96969                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
96970 }
96971 SQLITE_API int sqlite3_open_v2(
96972   const char *filename,   /* Database filename (UTF-8) */
96973   sqlite3 **ppDb,         /* OUT: SQLite db handle */
96974   int flags,              /* Flags */
96975   const char *zVfs        /* Name of VFS module to use */
96976 ){
96977   return openDatabase(filename, ppDb, flags, zVfs);
96978 }
96979
96980 #ifndef SQLITE_OMIT_UTF16
96981 /*
96982 ** Open a new database handle.
96983 */
96984 SQLITE_API int sqlite3_open16(
96985   const void *zFilename, 
96986   sqlite3 **ppDb
96987 ){
96988   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
96989   sqlite3_value *pVal;
96990   int rc;
96991
96992   assert( zFilename );
96993   assert( ppDb );
96994   *ppDb = 0;
96995 #ifndef SQLITE_OMIT_AUTOINIT
96996   rc = sqlite3_initialize();
96997   if( rc ) return rc;
96998 #endif
96999   pVal = sqlite3ValueNew(0);
97000   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
97001   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
97002   if( zFilename8 ){
97003     rc = openDatabase(zFilename8, ppDb,
97004                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
97005     assert( *ppDb || rc==SQLITE_NOMEM );
97006     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
97007       ENC(*ppDb) = SQLITE_UTF16NATIVE;
97008     }
97009   }else{
97010     rc = SQLITE_NOMEM;
97011   }
97012   sqlite3ValueFree(pVal);
97013
97014   return sqlite3ApiExit(0, rc);
97015 }
97016 #endif /* SQLITE_OMIT_UTF16 */
97017
97018 /*
97019 ** Register a new collation sequence with the database handle db.
97020 */
97021 SQLITE_API int sqlite3_create_collation(
97022   sqlite3* db, 
97023   const char *zName, 
97024   int enc, 
97025   void* pCtx,
97026   int(*xCompare)(void*,int,const void*,int,const void*)
97027 ){
97028   int rc;
97029   sqlite3_mutex_enter(db->mutex);
97030   assert( !db->mallocFailed );
97031   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
97032   rc = sqlite3ApiExit(db, rc);
97033   sqlite3_mutex_leave(db->mutex);
97034   return rc;
97035 }
97036
97037 /*
97038 ** Register a new collation sequence with the database handle db.
97039 */
97040 SQLITE_API int sqlite3_create_collation_v2(
97041   sqlite3* db, 
97042   const char *zName, 
97043   int enc, 
97044   void* pCtx,
97045   int(*xCompare)(void*,int,const void*,int,const void*),
97046   void(*xDel)(void*)
97047 ){
97048   int rc;
97049   sqlite3_mutex_enter(db->mutex);
97050   assert( !db->mallocFailed );
97051   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
97052   rc = sqlite3ApiExit(db, rc);
97053   sqlite3_mutex_leave(db->mutex);
97054   return rc;
97055 }
97056
97057 #ifndef SQLITE_OMIT_UTF16
97058 /*
97059 ** Register a new collation sequence with the database handle db.
97060 */
97061 SQLITE_API int sqlite3_create_collation16(
97062   sqlite3* db, 
97063   const void *zName,
97064   int enc, 
97065   void* pCtx,
97066   int(*xCompare)(void*,int,const void*,int,const void*)
97067 ){
97068   int rc = SQLITE_OK;
97069   char *zName8;
97070   sqlite3_mutex_enter(db->mutex);
97071   assert( !db->mallocFailed );
97072   zName8 = sqlite3Utf16to8(db, zName, -1);
97073   if( zName8 ){
97074     rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
97075     sqlite3DbFree(db, zName8);
97076   }
97077   rc = sqlite3ApiExit(db, rc);
97078   sqlite3_mutex_leave(db->mutex);
97079   return rc;
97080 }
97081 #endif /* SQLITE_OMIT_UTF16 */
97082
97083 /*
97084 ** Register a collation sequence factory callback with the database handle
97085 ** db. Replace any previously installed collation sequence factory.
97086 */
97087 SQLITE_API int sqlite3_collation_needed(
97088   sqlite3 *db, 
97089   void *pCollNeededArg, 
97090   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
97091 ){
97092   sqlite3_mutex_enter(db->mutex);
97093   db->xCollNeeded = xCollNeeded;
97094   db->xCollNeeded16 = 0;
97095   db->pCollNeededArg = pCollNeededArg;
97096   sqlite3_mutex_leave(db->mutex);
97097   return SQLITE_OK;
97098 }
97099
97100 #ifndef SQLITE_OMIT_UTF16
97101 /*
97102 ** Register a collation sequence factory callback with the database handle
97103 ** db. Replace any previously installed collation sequence factory.
97104 */
97105 SQLITE_API int sqlite3_collation_needed16(
97106   sqlite3 *db, 
97107   void *pCollNeededArg, 
97108   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
97109 ){
97110   sqlite3_mutex_enter(db->mutex);
97111   db->xCollNeeded = 0;
97112   db->xCollNeeded16 = xCollNeeded16;
97113   db->pCollNeededArg = pCollNeededArg;
97114   sqlite3_mutex_leave(db->mutex);
97115   return SQLITE_OK;
97116 }
97117 #endif /* SQLITE_OMIT_UTF16 */
97118
97119 #ifndef SQLITE_OMIT_GLOBALRECOVER
97120 #ifndef SQLITE_OMIT_DEPRECATED
97121 /*
97122 ** This function is now an anachronism. It used to be used to recover from a
97123 ** malloc() failure, but SQLite now does this automatically.
97124 */
97125 SQLITE_API int sqlite3_global_recover(void){
97126   return SQLITE_OK;
97127 }
97128 #endif
97129 #endif
97130
97131 /*
97132 ** Test to see whether or not the database connection is in autocommit
97133 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
97134 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
97135 ** by the next COMMIT or ROLLBACK.
97136 **
97137 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
97138 */
97139 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
97140   return db->autoCommit;
97141 }
97142
97143 #ifdef SQLITE_DEBUG
97144 /*
97145 ** The following routine is subtituted for constant SQLITE_CORRUPT in
97146 ** debugging builds.  This provides a way to set a breakpoint for when
97147 ** corruption is first detected.
97148 */
97149 SQLITE_PRIVATE int sqlite3Corrupt(void){
97150   return SQLITE_CORRUPT;
97151 }
97152 #endif
97153
97154 #ifndef SQLITE_OMIT_DEPRECATED
97155 /*
97156 ** This is a convenience routine that makes sure that all thread-specific
97157 ** data for this thread has been deallocated.
97158 **
97159 ** SQLite no longer uses thread-specific data so this routine is now a
97160 ** no-op.  It is retained for historical compatibility.
97161 */
97162 SQLITE_API void sqlite3_thread_cleanup(void){
97163 }
97164 #endif
97165
97166 /*
97167 ** Return meta information about a specific column of a database table.
97168 ** See comment in sqlite3.h (sqlite.h.in) for details.
97169 */
97170 #ifdef SQLITE_ENABLE_COLUMN_METADATA
97171 SQLITE_API int sqlite3_table_column_metadata(
97172   sqlite3 *db,                /* Connection handle */
97173   const char *zDbName,        /* Database name or NULL */
97174   const char *zTableName,     /* Table name */
97175   const char *zColumnName,    /* Column name */
97176   char const **pzDataType,    /* OUTPUT: Declared data type */
97177   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
97178   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
97179   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
97180   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
97181 ){
97182   int rc;
97183   char *zErrMsg = 0;
97184   Table *pTab = 0;
97185   Column *pCol = 0;
97186   int iCol;
97187
97188   char const *zDataType = 0;
97189   char const *zCollSeq = 0;
97190   int notnull = 0;
97191   int primarykey = 0;
97192   int autoinc = 0;
97193
97194   /* Ensure the database schema has been loaded */
97195   sqlite3_mutex_enter(db->mutex);
97196   (void)sqlite3SafetyOn(db);
97197   sqlite3BtreeEnterAll(db);
97198   rc = sqlite3Init(db, &zErrMsg);
97199   if( SQLITE_OK!=rc ){
97200     goto error_out;
97201   }
97202
97203   /* Locate the table in question */
97204   pTab = sqlite3FindTable(db, zTableName, zDbName);
97205   if( !pTab || pTab->pSelect ){
97206     pTab = 0;
97207     goto error_out;
97208   }
97209
97210   /* Find the column for which info is requested */
97211   if( sqlite3IsRowid(zColumnName) ){
97212     iCol = pTab->iPKey;
97213     if( iCol>=0 ){
97214       pCol = &pTab->aCol[iCol];
97215     }
97216   }else{
97217     for(iCol=0; iCol<pTab->nCol; iCol++){
97218       pCol = &pTab->aCol[iCol];
97219       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
97220         break;
97221       }
97222     }
97223     if( iCol==pTab->nCol ){
97224       pTab = 0;
97225       goto error_out;
97226     }
97227   }
97228
97229   /* The following block stores the meta information that will be returned
97230   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
97231   ** and autoinc. At this point there are two possibilities:
97232   ** 
97233   **     1. The specified column name was rowid", "oid" or "_rowid_" 
97234   **        and there is no explicitly declared IPK column. 
97235   **
97236   **     2. The table is not a view and the column name identified an 
97237   **        explicitly declared column. Copy meta information from *pCol.
97238   */ 
97239   if( pCol ){
97240     zDataType = pCol->zType;
97241     zCollSeq = pCol->zColl;
97242     notnull = pCol->notNull!=0;
97243     primarykey  = pCol->isPrimKey!=0;
97244     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
97245   }else{
97246     zDataType = "INTEGER";
97247     primarykey = 1;
97248   }
97249   if( !zCollSeq ){
97250     zCollSeq = "BINARY";
97251   }
97252
97253 error_out:
97254   sqlite3BtreeLeaveAll(db);
97255   (void)sqlite3SafetyOff(db);
97256
97257   /* Whether the function call succeeded or failed, set the output parameters
97258   ** to whatever their local counterparts contain. If an error did occur,
97259   ** this has the effect of zeroing all output parameters.
97260   */
97261   if( pzDataType ) *pzDataType = zDataType;
97262   if( pzCollSeq ) *pzCollSeq = zCollSeq;
97263   if( pNotNull ) *pNotNull = notnull;
97264   if( pPrimaryKey ) *pPrimaryKey = primarykey;
97265   if( pAutoinc ) *pAutoinc = autoinc;
97266
97267   if( SQLITE_OK==rc && !pTab ){
97268     sqlite3DbFree(db, zErrMsg);
97269     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
97270         zColumnName);
97271     rc = SQLITE_ERROR;
97272   }
97273   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
97274   sqlite3DbFree(db, zErrMsg);
97275   rc = sqlite3ApiExit(db, rc);
97276   sqlite3_mutex_leave(db->mutex);
97277   return rc;
97278 }
97279 #endif
97280
97281 /*
97282 ** Sleep for a little while.  Return the amount of time slept.
97283 */
97284 SQLITE_API int sqlite3_sleep(int ms){
97285   sqlite3_vfs *pVfs;
97286   int rc;
97287   pVfs = sqlite3_vfs_find(0);
97288   if( pVfs==0 ) return 0;
97289
97290   /* This function works in milliseconds, but the underlying OsSleep() 
97291   ** API uses microseconds. Hence the 1000's.
97292   */
97293   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
97294   return rc;
97295 }
97296
97297 /*
97298 ** Enable or disable the extended result codes.
97299 */
97300 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
97301   sqlite3_mutex_enter(db->mutex);
97302   db->errMask = onoff ? 0xffffffff : 0xff;
97303   sqlite3_mutex_leave(db->mutex);
97304   return SQLITE_OK;
97305 }
97306
97307 /*
97308 ** Invoke the xFileControl method on a particular database.
97309 */
97310 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
97311   int rc = SQLITE_ERROR;
97312   int iDb;
97313   sqlite3_mutex_enter(db->mutex);
97314   if( zDbName==0 ){
97315     iDb = 0;
97316   }else{
97317     for(iDb=0; iDb<db->nDb; iDb++){
97318       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
97319     }
97320   }
97321   if( iDb<db->nDb ){
97322     Btree *pBtree = db->aDb[iDb].pBt;
97323     if( pBtree ){
97324       Pager *pPager;
97325       sqlite3_file *fd;
97326       sqlite3BtreeEnter(pBtree);
97327       pPager = sqlite3BtreePager(pBtree);
97328       assert( pPager!=0 );
97329       fd = sqlite3PagerFile(pPager);
97330       assert( fd!=0 );
97331       if( fd->pMethods ){
97332         rc = sqlite3OsFileControl(fd, op, pArg);
97333       }
97334       sqlite3BtreeLeave(pBtree);
97335     }
97336   }
97337   sqlite3_mutex_leave(db->mutex);
97338   return rc;   
97339 }
97340
97341 /*
97342 ** Interface to the testing logic.
97343 */
97344 SQLITE_API int sqlite3_test_control(int op, ...){
97345   int rc = 0;
97346 #ifndef SQLITE_OMIT_BUILTIN_TEST
97347   va_list ap;
97348   va_start(ap, op);
97349   switch( op ){
97350
97351     /*
97352     ** Save the current state of the PRNG.
97353     */
97354     case SQLITE_TESTCTRL_PRNG_SAVE: {
97355       sqlite3PrngSaveState();
97356       break;
97357     }
97358
97359     /*
97360     ** Restore the state of the PRNG to the last state saved using
97361     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
97362     ** this verb acts like PRNG_RESET.
97363     */
97364     case SQLITE_TESTCTRL_PRNG_RESTORE: {
97365       sqlite3PrngRestoreState();
97366       break;
97367     }
97368
97369     /*
97370     ** Reset the PRNG back to its uninitialized state.  The next call
97371     ** to sqlite3_randomness() will reseed the PRNG using a single call
97372     ** to the xRandomness method of the default VFS.
97373     */
97374     case SQLITE_TESTCTRL_PRNG_RESET: {
97375       sqlite3PrngResetState();
97376       break;
97377     }
97378
97379     /*
97380     **  sqlite3_test_control(BITVEC_TEST, size, program)
97381     **
97382     ** Run a test against a Bitvec object of size.  The program argument
97383     ** is an array of integers that defines the test.  Return -1 on a
97384     ** memory allocation error, 0 on success, or non-zero for an error.
97385     ** See the sqlite3BitvecBuiltinTest() for additional information.
97386     */
97387     case SQLITE_TESTCTRL_BITVEC_TEST: {
97388       int sz = va_arg(ap, int);
97389       int *aProg = va_arg(ap, int*);
97390       rc = sqlite3BitvecBuiltinTest(sz, aProg);
97391       break;
97392     }
97393
97394     /*
97395     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
97396     **
97397     ** Register hooks to call to indicate which malloc() failures 
97398     ** are benign.
97399     */
97400     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
97401       typedef void (*void_function)(void);
97402       void_function xBenignBegin;
97403       void_function xBenignEnd;
97404       xBenignBegin = va_arg(ap, void_function);
97405       xBenignEnd = va_arg(ap, void_function);
97406       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
97407       break;
97408     }
97409
97410     /*
97411     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
97412     **
97413     ** Set the PENDING byte to the value in the argument, if X>0.
97414     ** Make no changes if X==0.  Return the value of the pending byte
97415     ** as it existing before this routine was called.
97416     **
97417     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
97418     ** an incompatible database file format.  Changing the PENDING byte
97419     ** while any database connection is open results in undefined and
97420     ** dileterious behavior.
97421     */
97422     case SQLITE_TESTCTRL_PENDING_BYTE: {
97423       unsigned int newVal = va_arg(ap, unsigned int);
97424       rc = sqlite3PendingByte;
97425       if( newVal ) sqlite3PendingByte = newVal;
97426       break;
97427     }
97428
97429     /*
97430     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
97431     **
97432     ** This action provides a run-time test to see whether or not
97433     ** assert() was enabled at compile-time.  If X is true and assert()
97434     ** is enabled, then the return value is true.  If X is true and
97435     ** assert() is disabled, then the return value is zero.  If X is
97436     ** false and assert() is enabled, then the assertion fires and the
97437     ** process aborts.  If X is false and assert() is disabled, then the
97438     ** return value is zero.
97439     */
97440     case SQLITE_TESTCTRL_ASSERT: {
97441       volatile int x = 0;
97442       assert( (x = va_arg(ap,int))!=0 );
97443       rc = x;
97444       break;
97445     }
97446
97447
97448     /*
97449     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
97450     **
97451     ** This action provides a run-time test to see how the ALWAYS and
97452     ** NEVER macros were defined at compile-time.
97453     **
97454     ** The return value is ALWAYS(X).  
97455     **
97456     ** The recommended test is X==2.  If the return value is 2, that means
97457     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
97458     ** default setting.  If the return value is 1, then ALWAYS() is either
97459     ** hard-coded to true or else it asserts if its argument is false.
97460     ** The first behavior (hard-coded to true) is the case if
97461     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
97462     ** behavior (assert if the argument to ALWAYS() is false) is the case if
97463     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
97464     **
97465     ** The run-time test procedure might look something like this:
97466     **
97467     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
97468     **      // ALWAYS() and NEVER() are no-op pass-through macros
97469     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
97470     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
97471     **    }else{
97472     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
97473     **    }
97474     */
97475     case SQLITE_TESTCTRL_ALWAYS: {
97476       int x = va_arg(ap,int);
97477       rc = ALWAYS(x);
97478       break;
97479     }
97480
97481     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
97482     **
97483     ** Set the nReserve size to N for the main database on the database
97484     ** connection db.
97485     */
97486     case SQLITE_TESTCTRL_RESERVE: {
97487       sqlite3 *db = va_arg(ap, sqlite3*);
97488       int x = va_arg(ap,int);
97489       sqlite3_mutex_enter(db->mutex);
97490       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
97491       sqlite3_mutex_leave(db->mutex);
97492       break;
97493     }
97494
97495     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
97496     **
97497     ** Enable or disable various optimizations for testing purposes.  The 
97498     ** argument N is a bitmask of optimizations to be disabled.  For normal
97499     ** operation N should be 0.  The idea is that a test program (like the
97500     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
97501     ** with various optimizations disabled to verify that the same answer
97502     ** is obtained in every case.
97503     */
97504     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
97505       sqlite3 *db = va_arg(ap, sqlite3*);
97506       int x = va_arg(ap,int);
97507       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
97508       break;
97509     }
97510
97511 #ifdef SQLITE_N_KEYWORD
97512     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
97513     **
97514     ** If zWord is a keyword recognized by the parser, then return the
97515     ** number of keywords.  Or if zWord is not a keyword, return 0.
97516     ** 
97517     ** This test feature is only available in the amalgamation since
97518     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
97519     ** is built using separate source files.
97520     */
97521     case SQLITE_TESTCTRL_ISKEYWORD: {
97522       const char *zWord = va_arg(ap, const char*);
97523       int n = sqlite3Strlen30(zWord);
97524       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
97525       break;
97526     }
97527 #endif 
97528
97529   }
97530   va_end(ap);
97531 #endif /* SQLITE_OMIT_BUILTIN_TEST */
97532   return rc;
97533 }
97534
97535 /************** End of main.c ************************************************/
97536 /************** Begin file notify.c ******************************************/
97537 /*
97538 ** 2009 March 3
97539 **
97540 ** The author disclaims copyright to this source code.  In place of
97541 ** a legal notice, here is a blessing:
97542 **
97543 **    May you do good and not evil.
97544 **    May you find forgiveness for yourself and forgive others.
97545 **    May you share freely, never taking more than you give.
97546 **
97547 *************************************************************************
97548 **
97549 ** This file contains the implementation of the sqlite3_unlock_notify()
97550 ** API method and its associated functionality.
97551 */
97552
97553 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
97554 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
97555
97556 /*
97557 ** Public interfaces:
97558 **
97559 **   sqlite3ConnectionBlocked()
97560 **   sqlite3ConnectionUnlocked()
97561 **   sqlite3ConnectionClosed()
97562 **   sqlite3_unlock_notify()
97563 */
97564
97565 #define assertMutexHeld() \
97566   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
97567
97568 /*
97569 ** Head of a linked list of all sqlite3 objects created by this process
97570 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
97571 ** is not NULL. This variable may only accessed while the STATIC_MASTER
97572 ** mutex is held.
97573 */
97574 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
97575
97576 #ifndef NDEBUG
97577 /*
97578 ** This function is a complex assert() that verifies the following 
97579 ** properties of the blocked connections list:
97580 **
97581 **   1) Each entry in the list has a non-NULL value for either 
97582 **      pUnlockConnection or pBlockingConnection, or both.
97583 **
97584 **   2) All entries in the list that share a common value for 
97585 **      xUnlockNotify are grouped together.
97586 **
97587 **   3) If the argument db is not NULL, then none of the entries in the
97588 **      blocked connections list have pUnlockConnection or pBlockingConnection
97589 **      set to db. This is used when closing connection db.
97590 */
97591 static void checkListProperties(sqlite3 *db){
97592   sqlite3 *p;
97593   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
97594     int seen = 0;
97595     sqlite3 *p2;
97596
97597     /* Verify property (1) */
97598     assert( p->pUnlockConnection || p->pBlockingConnection );
97599
97600     /* Verify property (2) */
97601     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
97602       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
97603       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
97604       assert( db==0 || p->pUnlockConnection!=db );
97605       assert( db==0 || p->pBlockingConnection!=db );
97606     }
97607   }
97608 }
97609 #else
97610 # define checkListProperties(x)
97611 #endif
97612
97613 /*
97614 ** Remove connection db from the blocked connections list. If connection
97615 ** db is not currently a part of the list, this function is a no-op.
97616 */
97617 static void removeFromBlockedList(sqlite3 *db){
97618   sqlite3 **pp;
97619   assertMutexHeld();
97620   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
97621     if( *pp==db ){
97622       *pp = (*pp)->pNextBlocked;
97623       break;
97624     }
97625   }
97626 }
97627
97628 /*
97629 ** Add connection db to the blocked connections list. It is assumed
97630 ** that it is not already a part of the list.
97631 */
97632 static void addToBlockedList(sqlite3 *db){
97633   sqlite3 **pp;
97634   assertMutexHeld();
97635   for(
97636     pp=&sqlite3BlockedList; 
97637     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
97638     pp=&(*pp)->pNextBlocked
97639   );
97640   db->pNextBlocked = *pp;
97641   *pp = db;
97642 }
97643
97644 /*
97645 ** Obtain the STATIC_MASTER mutex.
97646 */
97647 static void enterMutex(void){
97648   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
97649   checkListProperties(0);
97650 }
97651
97652 /*
97653 ** Release the STATIC_MASTER mutex.
97654 */
97655 static void leaveMutex(void){
97656   assertMutexHeld();
97657   checkListProperties(0);
97658   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
97659 }
97660
97661 /*
97662 ** Register an unlock-notify callback.
97663 **
97664 ** This is called after connection "db" has attempted some operation
97665 ** but has received an SQLITE_LOCKED error because another connection
97666 ** (call it pOther) in the same process was busy using the same shared
97667 ** cache.  pOther is found by looking at db->pBlockingConnection.
97668 **
97669 ** If there is no blocking connection, the callback is invoked immediately,
97670 ** before this routine returns.
97671 **
97672 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
97673 ** a deadlock.
97674 **
97675 ** Otherwise, make arrangements to invoke xNotify when pOther drops
97676 ** its locks.
97677 **
97678 ** Each call to this routine overrides any prior callbacks registered
97679 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
97680 ** cancelled.
97681 */
97682 SQLITE_API int sqlite3_unlock_notify(
97683   sqlite3 *db,
97684   void (*xNotify)(void **, int),
97685   void *pArg
97686 ){
97687   int rc = SQLITE_OK;
97688
97689   sqlite3_mutex_enter(db->mutex);
97690   enterMutex();
97691
97692   if( xNotify==0 ){
97693     removeFromBlockedList(db);
97694     db->pUnlockConnection = 0;
97695     db->xUnlockNotify = 0;
97696     db->pUnlockArg = 0;
97697   }else if( 0==db->pBlockingConnection ){
97698     /* The blocking transaction has been concluded. Or there never was a 
97699     ** blocking transaction. In either case, invoke the notify callback
97700     ** immediately. 
97701     */
97702     xNotify(&pArg, 1);
97703   }else{
97704     sqlite3 *p;
97705
97706     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
97707     if( p ){
97708       rc = SQLITE_LOCKED;              /* Deadlock detected. */
97709     }else{
97710       db->pUnlockConnection = db->pBlockingConnection;
97711       db->xUnlockNotify = xNotify;
97712       db->pUnlockArg = pArg;
97713       removeFromBlockedList(db);
97714       addToBlockedList(db);
97715     }
97716   }
97717
97718   leaveMutex();
97719   assert( !db->mallocFailed );
97720   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
97721   sqlite3_mutex_leave(db->mutex);
97722   return rc;
97723 }
97724
97725 /*
97726 ** This function is called while stepping or preparing a statement 
97727 ** associated with connection db. The operation will return SQLITE_LOCKED
97728 ** to the user because it requires a lock that will not be available
97729 ** until connection pBlocker concludes its current transaction.
97730 */
97731 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
97732   enterMutex();
97733   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
97734     addToBlockedList(db);
97735   }
97736   db->pBlockingConnection = pBlocker;
97737   leaveMutex();
97738 }
97739
97740 /*
97741 ** This function is called when
97742 ** the transaction opened by database db has just finished. Locks held 
97743 ** by database connection db have been released.
97744 **
97745 ** This function loops through each entry in the blocked connections
97746 ** list and does the following:
97747 **
97748 **   1) If the sqlite3.pBlockingConnection member of a list entry is
97749 **      set to db, then set pBlockingConnection=0.
97750 **
97751 **   2) If the sqlite3.pUnlockConnection member of a list entry is
97752 **      set to db, then invoke the configured unlock-notify callback and
97753 **      set pUnlockConnection=0.
97754 **
97755 **   3) If the two steps above mean that pBlockingConnection==0 and
97756 **      pUnlockConnection==0, remove the entry from the blocked connections
97757 **      list.
97758 */
97759 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
97760   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
97761   int nArg = 0;                            /* Number of entries in aArg[] */
97762   sqlite3 **pp;                            /* Iterator variable */
97763   void **aArg;               /* Arguments to the unlock callback */
97764   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
97765   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
97766
97767   aArg = aStatic;
97768   enterMutex();         /* Enter STATIC_MASTER mutex */
97769
97770   /* This loop runs once for each entry in the blocked-connections list. */
97771   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
97772     sqlite3 *p = *pp;
97773
97774     /* Step 1. */
97775     if( p->pBlockingConnection==db ){
97776       p->pBlockingConnection = 0;
97777     }
97778
97779     /* Step 2. */
97780     if( p->pUnlockConnection==db ){
97781       assert( p->xUnlockNotify );
97782       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
97783         xUnlockNotify(aArg, nArg);
97784         nArg = 0;
97785       }
97786
97787       sqlite3BeginBenignMalloc();
97788       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
97789       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
97790       if( (!aDyn && nArg==(int)ArraySize(aStatic))
97791        || (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*)))
97792       ){
97793         /* The aArg[] array needs to grow. */
97794         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
97795         if( pNew ){
97796           memcpy(pNew, aArg, nArg*sizeof(void *));
97797           sqlite3_free(aDyn);
97798           aDyn = aArg = pNew;
97799         }else{
97800           /* This occurs when the array of context pointers that need to
97801           ** be passed to the unlock-notify callback is larger than the
97802           ** aStatic[] array allocated on the stack and the attempt to 
97803           ** allocate a larger array from the heap has failed.
97804           **
97805           ** This is a difficult situation to handle. Returning an error
97806           ** code to the caller is insufficient, as even if an error code
97807           ** is returned the transaction on connection db will still be
97808           ** closed and the unlock-notify callbacks on blocked connections
97809           ** will go unissued. This might cause the application to wait
97810           ** indefinitely for an unlock-notify callback that will never 
97811           ** arrive.
97812           **
97813           ** Instead, invoke the unlock-notify callback with the context
97814           ** array already accumulated. We can then clear the array and
97815           ** begin accumulating any further context pointers without 
97816           ** requiring any dynamic allocation. This is sub-optimal because
97817           ** it means that instead of one callback with a large array of
97818           ** context pointers the application will receive two or more
97819           ** callbacks with smaller arrays of context pointers, which will
97820           ** reduce the applications ability to prioritize multiple 
97821           ** connections. But it is the best that can be done under the
97822           ** circumstances.
97823           */
97824           xUnlockNotify(aArg, nArg);
97825           nArg = 0;
97826         }
97827       }
97828       sqlite3EndBenignMalloc();
97829
97830       aArg[nArg++] = p->pUnlockArg;
97831       xUnlockNotify = p->xUnlockNotify;
97832       p->pUnlockConnection = 0;
97833       p->xUnlockNotify = 0;
97834       p->pUnlockArg = 0;
97835     }
97836
97837     /* Step 3. */
97838     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
97839       /* Remove connection p from the blocked connections list. */
97840       *pp = p->pNextBlocked;
97841       p->pNextBlocked = 0;
97842     }else{
97843       pp = &p->pNextBlocked;
97844     }
97845   }
97846
97847   if( nArg!=0 ){
97848     xUnlockNotify(aArg, nArg);
97849   }
97850   sqlite3_free(aDyn);
97851   leaveMutex();         /* Leave STATIC_MASTER mutex */
97852 }
97853
97854 /*
97855 ** This is called when the database connection passed as an argument is 
97856 ** being closed. The connection is removed from the blocked list.
97857 */
97858 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
97859   sqlite3ConnectionUnlocked(db);
97860   enterMutex();
97861   removeFromBlockedList(db);
97862   checkListProperties(db);
97863   leaveMutex();
97864 }
97865 #endif
97866
97867 /************** End of notify.c **********************************************/
97868 /************** Begin file fts3.c ********************************************/
97869 /*
97870 ** 2006 Oct 10
97871 **
97872 ** The author disclaims copyright to this source code.  In place of
97873 ** a legal notice, here is a blessing:
97874 **
97875 **    May you do good and not evil.
97876 **    May you find forgiveness for yourself and forgive others.
97877 **    May you share freely, never taking more than you give.
97878 **
97879 ******************************************************************************
97880 **
97881 ** This is an SQLite module implementing full-text search.
97882 */
97883
97884 /*
97885 ** The code in this file is only compiled if:
97886 **
97887 **     * The FTS3 module is being built as an extension
97888 **       (in which case SQLITE_CORE is not defined), or
97889 **
97890 **     * The FTS3 module is being built into the core of
97891 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
97892 */
97893
97894 /* TODO(shess) Consider exporting this comment to an HTML file or the
97895 ** wiki.
97896 */
97897 /* The full-text index is stored in a series of b+tree (-like)
97898 ** structures called segments which map terms to doclists.  The
97899 ** structures are like b+trees in layout, but are constructed from the
97900 ** bottom up in optimal fashion and are not updatable.  Since trees
97901 ** are built from the bottom up, things will be described from the
97902 ** bottom up.
97903 **
97904 **
97905 **** Varints ****
97906 ** The basic unit of encoding is a variable-length integer called a
97907 ** varint.  We encode variable-length integers in little-endian order
97908 ** using seven bits * per byte as follows:
97909 **
97910 ** KEY:
97911 **         A = 0xxxxxxx    7 bits of data and one flag bit
97912 **         B = 1xxxxxxx    7 bits of data and one flag bit
97913 **
97914 **  7 bits - A
97915 ** 14 bits - BA
97916 ** 21 bits - BBA
97917 ** and so on.
97918 **
97919 ** This is identical to how sqlite encodes varints (see util.c).
97920 **
97921 **
97922 **** Document lists ****
97923 ** A doclist (document list) holds a docid-sorted list of hits for a
97924 ** given term.  Doclists hold docids, and can optionally associate
97925 ** token positions and offsets with docids.
97926 **
97927 ** A DL_POSITIONS_OFFSETS doclist is stored like this:
97928 **
97929 ** array {
97930 **   varint docid;
97931 **   array {                (position list for column 0)
97932 **     varint position;     (delta from previous position plus POS_BASE)
97933 **     varint startOffset;  (delta from previous startOffset)
97934 **     varint endOffset;    (delta from startOffset)
97935 **   }
97936 **   array {
97937 **     varint POS_COLUMN;   (marks start of position list for new column)
97938 **     varint column;       (index of new column)
97939 **     array {
97940 **       varint position;   (delta from previous position plus POS_BASE)
97941 **       varint startOffset;(delta from previous startOffset)
97942 **       varint endOffset;  (delta from startOffset)
97943 **     }
97944 **   }
97945 **   varint POS_END;        (marks end of positions for this document.
97946 ** }
97947 **
97948 ** Here, array { X } means zero or more occurrences of X, adjacent in
97949 ** memory.  A "position" is an index of a token in the token stream
97950 ** generated by the tokenizer, while an "offset" is a byte offset,
97951 ** both based at 0.  Note that POS_END and POS_COLUMN occur in the
97952 ** same logical place as the position element, and act as sentinals
97953 ** ending a position list array.
97954 **
97955 ** A DL_POSITIONS doclist omits the startOffset and endOffset
97956 ** information.  A DL_DOCIDS doclist omits both the position and
97957 ** offset information, becoming an array of varint-encoded docids.
97958 **
97959 ** On-disk data is stored as type DL_DEFAULT, so we don't serialize
97960 ** the type.  Due to how deletion is implemented in the segmentation
97961 ** system, on-disk doclists MUST store at least positions.
97962 **
97963 **
97964 **** Segment leaf nodes ****
97965 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
97966 ** nodes are written using LeafWriter, and read using LeafReader (to
97967 ** iterate through a single leaf node's data) and LeavesReader (to
97968 ** iterate through a segment's entire leaf layer).  Leaf nodes have
97969 ** the format:
97970 **
97971 ** varint iHeight;             (height from leaf level, always 0)
97972 ** varint nTerm;               (length of first term)
97973 ** char pTerm[nTerm];          (content of first term)
97974 ** varint nDoclist;            (length of term's associated doclist)
97975 ** char pDoclist[nDoclist];    (content of doclist)
97976 ** array {
97977 **                             (further terms are delta-encoded)
97978 **   varint nPrefix;           (length of prefix shared with previous term)
97979 **   varint nSuffix;           (length of unshared suffix)
97980 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
97981 **   varint nDoclist;          (length of term's associated doclist)
97982 **   char pDoclist[nDoclist];  (content of doclist)
97983 ** }
97984 **
97985 ** Here, array { X } means zero or more occurrences of X, adjacent in
97986 ** memory.
97987 **
97988 ** Leaf nodes are broken into blocks which are stored contiguously in
97989 ** the %_segments table in sorted order.  This means that when the end
97990 ** of a node is reached, the next term is in the node with the next
97991 ** greater node id.
97992 **
97993 ** New data is spilled to a new leaf node when the current node
97994 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
97995 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
97996 ** node (a leaf node with a single term and doclist).  The goal of
97997 ** these settings is to pack together groups of small doclists while
97998 ** making it efficient to directly access large doclists.  The
97999 ** assumption is that large doclists represent terms which are more
98000 ** likely to be query targets.
98001 **
98002 ** TODO(shess) It may be useful for blocking decisions to be more
98003 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
98004 ** node rather than splitting into 2k and .5k nodes.  My intuition is
98005 ** that this might extend through 2x or 4x the pagesize.
98006 **
98007 **
98008 **** Segment interior nodes ****
98009 ** Segment interior nodes store blockids for subtree nodes and terms
98010 ** to describe what data is stored by the each subtree.  Interior
98011 ** nodes are written using InteriorWriter, and read using
98012 ** InteriorReader.  InteriorWriters are created as needed when
98013 ** SegmentWriter creates new leaf nodes, or when an interior node
98014 ** itself grows too big and must be split.  The format of interior
98015 ** nodes:
98016 **
98017 ** varint iHeight;           (height from leaf level, always >0)
98018 ** varint iBlockid;          (block id of node's leftmost subtree)
98019 ** optional {
98020 **   varint nTerm;           (length of first term)
98021 **   char pTerm[nTerm];      (content of first term)
98022 **   array {
98023 **                                (further terms are delta-encoded)
98024 **     varint nPrefix;            (length of shared prefix with previous term)
98025 **     varint nSuffix;            (length of unshared suffix)
98026 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
98027 **   }
98028 ** }
98029 **
98030 ** Here, optional { X } means an optional element, while array { X }
98031 ** means zero or more occurrences of X, adjacent in memory.
98032 **
98033 ** An interior node encodes n terms separating n+1 subtrees.  The
98034 ** subtree blocks are contiguous, so only the first subtree's blockid
98035 ** is encoded.  The subtree at iBlockid will contain all terms less
98036 ** than the first term encoded (or all terms if no term is encoded).
98037 ** Otherwise, for terms greater than or equal to pTerm[i] but less
98038 ** than pTerm[i+1], the subtree for that term will be rooted at
98039 ** iBlockid+i.  Interior nodes only store enough term data to
98040 ** distinguish adjacent children (if the rightmost term of the left
98041 ** child is "something", and the leftmost term of the right child is
98042 ** "wicked", only "w" is stored).
98043 **
98044 ** New data is spilled to a new interior node at the same height when
98045 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
98046 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
98047 ** interior nodes and making the tree too skinny.  The interior nodes
98048 ** at a given height are naturally tracked by interior nodes at
98049 ** height+1, and so on.
98050 **
98051 **
98052 **** Segment directory ****
98053 ** The segment directory in table %_segdir stores meta-information for
98054 ** merging and deleting segments, and also the root node of the
98055 ** segment's tree.
98056 **
98057 ** The root node is the top node of the segment's tree after encoding
98058 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
98059 ** This could be either a leaf node or an interior node.  If the top
98060 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
98061 ** and a new root interior node is generated (which should always fit
98062 ** within ROOT_MAX because it only needs space for 2 varints, the
98063 ** height and the blockid of the previous root).
98064 **
98065 ** The meta-information in the segment directory is:
98066 **   level               - segment level (see below)
98067 **   idx                 - index within level
98068 **                       - (level,idx uniquely identify a segment)
98069 **   start_block         - first leaf node
98070 **   leaves_end_block    - last leaf node
98071 **   end_block           - last block (including interior nodes)
98072 **   root                - contents of root node
98073 **
98074 ** If the root node is a leaf node, then start_block,
98075 ** leaves_end_block, and end_block are all 0.
98076 **
98077 **
98078 **** Segment merging ****
98079 ** To amortize update costs, segments are grouped into levels and
98080 ** merged in batches.  Each increase in level represents exponentially
98081 ** more documents.
98082 **
98083 ** New documents (actually, document updates) are tokenized and
98084 ** written individually (using LeafWriter) to a level 0 segment, with
98085 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
98086 ** level 0 segments are merged into a single level 1 segment.  Level 1
98087 ** is populated like level 0, and eventually MERGE_COUNT level 1
98088 ** segments are merged to a single level 2 segment (representing
98089 ** MERGE_COUNT^2 updates), and so on.
98090 **
98091 ** A segment merge traverses all segments at a given level in
98092 ** parallel, performing a straightforward sorted merge.  Since segment
98093 ** leaf nodes are written in to the %_segments table in order, this
98094 ** merge traverses the underlying sqlite disk structures efficiently.
98095 ** After the merge, all segment blocks from the merged level are
98096 ** deleted.
98097 **
98098 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
98099 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
98100 ** very similar performance numbers to 16 on insertion, though they're
98101 ** a tiny bit slower (perhaps due to more overhead in merge-time
98102 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
98103 ** 16, 2 about 66% slower than 16.
98104 **
98105 ** At query time, high MERGE_COUNT increases the number of segments
98106 ** which need to be scanned and merged.  For instance, with 100k docs
98107 ** inserted:
98108 **
98109 **    MERGE_COUNT   segments
98110 **       16           25
98111 **        8           12
98112 **        4           10
98113 **        2            6
98114 **
98115 ** This appears to have only a moderate impact on queries for very
98116 ** frequent terms (which are somewhat dominated by segment merge
98117 ** costs), and infrequent and non-existent terms still seem to be fast
98118 ** even with many segments.
98119 **
98120 ** TODO(shess) That said, it would be nice to have a better query-side
98121 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
98122 ** optimizations to things like doclist merging will swing the sweet
98123 ** spot around.
98124 **
98125 **
98126 **
98127 **** Handling of deletions and updates ****
98128 ** Since we're using a segmented structure, with no docid-oriented
98129 ** index into the term index, we clearly cannot simply update the term
98130 ** index when a document is deleted or updated.  For deletions, we
98131 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
98132 ** we simply write the new doclist.  Segment merges overwrite older
98133 ** data for a particular docid with newer data, so deletes or updates
98134 ** will eventually overtake the earlier data and knock it out.  The
98135 ** query logic likewise merges doclists so that newer data knocks out
98136 ** older data.
98137 **
98138 ** TODO(shess) Provide a VACUUM type operation to clear out all
98139 ** deletions and duplications.  This would basically be a forced merge
98140 ** into a single segment.
98141 */
98142
98143 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
98144
98145 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
98146 # define SQLITE_CORE 1
98147 #endif
98148
98149 /************** Include fts3Int.h in the middle of fts3.c ********************/
98150 /************** Begin file fts3Int.h *****************************************/
98151 /*
98152 ** 2009 Nov 12
98153 **
98154 ** The author disclaims copyright to this source code.  In place of
98155 ** a legal notice, here is a blessing:
98156 **
98157 **    May you do good and not evil.
98158 **    May you find forgiveness for yourself and forgive others.
98159 **    May you share freely, never taking more than you give.
98160 **
98161 ******************************************************************************
98162 **
98163 */
98164
98165 #ifndef _FTSINT_H
98166 #define _FTSINT_H
98167
98168 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
98169 # define NDEBUG 1
98170 #endif
98171
98172 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
98173 /************** Begin file fts3_tokenizer.h **********************************/
98174 /*
98175 ** 2006 July 10
98176 **
98177 ** The author disclaims copyright to this source code.
98178 **
98179 *************************************************************************
98180 ** Defines the interface to tokenizers used by fulltext-search.  There
98181 ** are three basic components:
98182 **
98183 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
98184 ** interface functions.  This is essentially the class structure for
98185 ** tokenizers.
98186 **
98187 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
98188 ** including customization information defined at creation time.
98189 **
98190 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
98191 ** tokens from a particular input.
98192 */
98193 #ifndef _FTS3_TOKENIZER_H_
98194 #define _FTS3_TOKENIZER_H_
98195
98196 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
98197 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
98198 ** we will need a way to register the API consistently.
98199 */
98200
98201 /*
98202 ** Structures used by the tokenizer interface. When a new tokenizer
98203 ** implementation is registered, the caller provides a pointer to
98204 ** an sqlite3_tokenizer_module containing pointers to the callback
98205 ** functions that make up an implementation.
98206 **
98207 ** When an fts3 table is created, it passes any arguments passed to
98208 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
98209 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
98210 ** implementation. The xCreate() function in turn returns an 
98211 ** sqlite3_tokenizer structure representing the specific tokenizer to
98212 ** be used for the fts3 table (customized by the tokenizer clause arguments).
98213 **
98214 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
98215 ** method is called. It returns an sqlite3_tokenizer_cursor object
98216 ** that may be used to tokenize a specific input buffer based on
98217 ** the tokenization rules supplied by a specific sqlite3_tokenizer
98218 ** object.
98219 */
98220 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
98221 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
98222 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
98223
98224 struct sqlite3_tokenizer_module {
98225
98226   /*
98227   ** Structure version. Should always be set to 0.
98228   */
98229   int iVersion;
98230
98231   /*
98232   ** Create a new tokenizer. The values in the argv[] array are the
98233   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
98234   ** TABLE statement that created the fts3 table. For example, if
98235   ** the following SQL is executed:
98236   **
98237   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
98238   **
98239   ** then argc is set to 2, and the argv[] array contains pointers
98240   ** to the strings "arg1" and "arg2".
98241   **
98242   ** This method should return either SQLITE_OK (0), or an SQLite error 
98243   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
98244   ** to point at the newly created tokenizer structure. The generic
98245   ** sqlite3_tokenizer.pModule variable should not be initialised by
98246   ** this callback. The caller will do so.
98247   */
98248   int (*xCreate)(
98249     int argc,                           /* Size of argv array */
98250     const char *const*argv,             /* Tokenizer argument strings */
98251     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
98252   );
98253
98254   /*
98255   ** Destroy an existing tokenizer. The fts3 module calls this method
98256   ** exactly once for each successful call to xCreate().
98257   */
98258   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
98259
98260   /*
98261   ** Create a tokenizer cursor to tokenize an input buffer. The caller
98262   ** is responsible for ensuring that the input buffer remains valid
98263   ** until the cursor is closed (using the xClose() method). 
98264   */
98265   int (*xOpen)(
98266     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
98267     const char *pInput, int nBytes,      /* Input buffer */
98268     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
98269   );
98270
98271   /*
98272   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
98273   ** method exactly once for each successful call to xOpen().
98274   */
98275   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
98276
98277   /*
98278   ** Retrieve the next token from the tokenizer cursor pCursor. This
98279   ** method should either return SQLITE_OK and set the values of the
98280   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
98281   ** the end of the buffer has been reached, or an SQLite error code.
98282   **
98283   ** *ppToken should be set to point at a buffer containing the 
98284   ** normalized version of the token (i.e. after any case-folding and/or
98285   ** stemming has been performed). *pnBytes should be set to the length
98286   ** of this buffer in bytes. The input text that generated the token is
98287   ** identified by the byte offsets returned in *piStartOffset and
98288   ** *piEndOffset. *piStartOffset should be set to the index of the first
98289   ** byte of the token in the input buffer. *piEndOffset should be set
98290   ** to the index of the first byte just past the end of the token in
98291   ** the input buffer.
98292   **
98293   ** The buffer *ppToken is set to point at is managed by the tokenizer
98294   ** implementation. It is only required to be valid until the next call
98295   ** to xNext() or xClose(). 
98296   */
98297   /* TODO(shess) current implementation requires pInput to be
98298   ** nul-terminated.  This should either be fixed, or pInput/nBytes
98299   ** should be converted to zInput.
98300   */
98301   int (*xNext)(
98302     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
98303     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
98304     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
98305     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
98306     int *piPosition      /* OUT: Number of tokens returned before this one */
98307   );
98308 };
98309
98310 struct sqlite3_tokenizer {
98311   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
98312   /* Tokenizer implementations will typically add additional fields */
98313 };
98314
98315 struct sqlite3_tokenizer_cursor {
98316   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
98317   /* Tokenizer implementations will typically add additional fields */
98318 };
98319
98320 int fts3_global_term_cnt(int iTerm, int iCol);
98321 int fts3_term_cnt(int iTerm, int iCol);
98322
98323
98324 #endif /* _FTS3_TOKENIZER_H_ */
98325
98326 /************** End of fts3_tokenizer.h **************************************/
98327 /************** Continuing where we left off in fts3Int.h ********************/
98328 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
98329 /************** Begin file fts3_hash.h ***************************************/
98330 /*
98331 ** 2001 September 22
98332 **
98333 ** The author disclaims copyright to this source code.  In place of
98334 ** a legal notice, here is a blessing:
98335 **
98336 **    May you do good and not evil.
98337 **    May you find forgiveness for yourself and forgive others.
98338 **    May you share freely, never taking more than you give.
98339 **
98340 *************************************************************************
98341 ** This is the header file for the generic hash-table implemenation
98342 ** used in SQLite.  We've modified it slightly to serve as a standalone
98343 ** hash table implementation for the full-text indexing module.
98344 **
98345 */
98346 #ifndef _FTS3_HASH_H_
98347 #define _FTS3_HASH_H_
98348
98349 /* Forward declarations of structures. */
98350 typedef struct Fts3Hash Fts3Hash;
98351 typedef struct Fts3HashElem Fts3HashElem;
98352
98353 /* A complete hash table is an instance of the following structure.
98354 ** The internals of this structure are intended to be opaque -- client
98355 ** code should not attempt to access or modify the fields of this structure
98356 ** directly.  Change this structure only by using the routines below.
98357 ** However, many of the "procedures" and "functions" for modifying and
98358 ** accessing this structure are really macros, so we can't really make
98359 ** this structure opaque.
98360 */
98361 struct Fts3Hash {
98362   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
98363   char copyKey;           /* True if copy of key made on insert */
98364   int count;              /* Number of entries in this table */
98365   Fts3HashElem *first;    /* The first element of the array */
98366   int htsize;             /* Number of buckets in the hash table */
98367   struct _fts3ht {        /* the hash table */
98368     int count;               /* Number of entries with this hash */
98369     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
98370   } *ht;
98371 };
98372
98373 /* Each element in the hash table is an instance of the following 
98374 ** structure.  All elements are stored on a single doubly-linked list.
98375 **
98376 ** Again, this structure is intended to be opaque, but it can't really
98377 ** be opaque because it is used by macros.
98378 */
98379 struct Fts3HashElem {
98380   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
98381   void *data;                /* Data associated with this element */
98382   void *pKey; int nKey;      /* Key associated with this element */
98383 };
98384
98385 /*
98386 ** There are 2 different modes of operation for a hash table:
98387 **
98388 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
98389 **                           (including the null-terminator, if any).  Case
98390 **                           is respected in comparisons.
98391 **
98392 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
98393 **                           memcmp() is used to compare keys.
98394 **
98395 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
98396 */
98397 #define FTS3_HASH_STRING    1
98398 #define FTS3_HASH_BINARY    2
98399
98400 /*
98401 ** Access routines.  To delete, insert a NULL pointer.
98402 */
98403 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
98404 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
98405 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
98406 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
98407 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
98408
98409 /*
98410 ** Shorthand for the functions above
98411 */
98412 #define fts3HashInit     sqlite3Fts3HashInit
98413 #define fts3HashInsert   sqlite3Fts3HashInsert
98414 #define fts3HashFind     sqlite3Fts3HashFind
98415 #define fts3HashClear    sqlite3Fts3HashClear
98416 #define fts3HashFindElem sqlite3Fts3HashFindElem
98417
98418 /*
98419 ** Macros for looping over all elements of a hash table.  The idiom is
98420 ** like this:
98421 **
98422 **   Fts3Hash h;
98423 **   Fts3HashElem *p;
98424 **   ...
98425 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
98426 **     SomeStructure *pData = fts3HashData(p);
98427 **     // do something with pData
98428 **   }
98429 */
98430 #define fts3HashFirst(H)  ((H)->first)
98431 #define fts3HashNext(E)   ((E)->next)
98432 #define fts3HashData(E)   ((E)->data)
98433 #define fts3HashKey(E)    ((E)->pKey)
98434 #define fts3HashKeysize(E) ((E)->nKey)
98435
98436 /*
98437 ** Number of entries in a hash table
98438 */
98439 #define fts3HashCount(H)  ((H)->count)
98440
98441 #endif /* _FTS3_HASH_H_ */
98442
98443 /************** End of fts3_hash.h *******************************************/
98444 /************** Continuing where we left off in fts3Int.h ********************/
98445
98446 /*
98447 ** This constant controls how often segments are merged. Once there are
98448 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
98449 ** segment of level N+1.
98450 */
98451 #define FTS3_MERGE_COUNT 16
98452
98453 /*
98454 ** This is the maximum amount of data (in bytes) to store in the 
98455 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
98456 ** populated as documents are inserted/updated/deleted in a transaction
98457 ** and used to create a new segment when the transaction is committed.
98458 ** However if this limit is reached midway through a transaction, a new 
98459 ** segment is created and the hash table cleared immediately.
98460 */
98461 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
98462
98463 /*
98464 ** Macro to return the number of elements in an array. SQLite has a
98465 ** similar macro called ArraySize(). Use a different name to avoid
98466 ** a collision when building an amalgamation with built-in FTS3.
98467 */
98468 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
98469
98470 /*
98471 ** Maximum length of a varint encoded integer. The varint format is different
98472 ** from that used by SQLite, so the maximum length is 10, not 9.
98473 */
98474 #define FTS3_VARINT_MAX 10
98475
98476 /*
98477 ** This section provides definitions to allow the
98478 ** FTS3 extension to be compiled outside of the 
98479 ** amalgamation.
98480 */
98481 #ifndef SQLITE_AMALGAMATION
98482 /*
98483 ** Macros indicating that conditional expressions are always true or
98484 ** false.
98485 */
98486 # define ALWAYS(x) (x)
98487 # define NEVER(X)  (x)
98488 /*
98489 ** Internal types used by SQLite.
98490 */
98491 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
98492 typedef short int i16;            /* 2-byte (or larger) signed integer */
98493 typedef unsigned int u32;         /* 4-byte unsigned integer */
98494 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
98495 /*
98496 ** Macro used to suppress compiler warnings for unused parameters.
98497 */
98498 #define UNUSED_PARAMETER(x) (void)(x)
98499 #endif
98500
98501 typedef struct Fts3Table Fts3Table;
98502 typedef struct Fts3Cursor Fts3Cursor;
98503 typedef struct Fts3Expr Fts3Expr;
98504 typedef struct Fts3Phrase Fts3Phrase;
98505 typedef struct Fts3SegReader Fts3SegReader;
98506 typedef struct Fts3SegFilter Fts3SegFilter;
98507
98508 /*
98509 ** A connection to a fulltext index is an instance of the following
98510 ** structure. The xCreate and xConnect methods create an instance
98511 ** of this structure and xDestroy and xDisconnect free that instance.
98512 ** All other methods receive a pointer to the structure as one of their
98513 ** arguments.
98514 */
98515 struct Fts3Table {
98516   sqlite3_vtab base;              /* Base class used by SQLite core */
98517   sqlite3 *db;                    /* The database connection */
98518   const char *zDb;                /* logical database name */
98519   const char *zName;              /* virtual table name */
98520   int nColumn;                    /* number of named columns in virtual table */
98521   char **azColumn;                /* column names.  malloced */
98522   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
98523
98524   /* Precompiled statements used by the implementation. Each of these 
98525   ** statements is run and reset within a single virtual table API call. 
98526   */
98527   sqlite3_stmt *aStmt[18];
98528
98529   /* Pointer to string containing the SQL:
98530   **
98531   ** "SELECT block FROM %_segments WHERE blockid BETWEEN ? AND ? 
98532   **    ORDER BY blockid"
98533   */
98534   char *zSelectLeaves;
98535   int nLeavesStmt;                /* Valid statements in aLeavesStmt */
98536   int nLeavesTotal;               /* Total number of prepared leaves stmts */
98537   int nLeavesAlloc;               /* Allocated size of aLeavesStmt */
98538   sqlite3_stmt **aLeavesStmt;     /* Array of prepared zSelectLeaves stmts */
98539
98540   int nNodeSize;                  /* Soft limit for node size */
98541
98542   /* The following hash table is used to buffer pending index updates during
98543   ** transactions. Variable nPendingData estimates the memory size of the 
98544   ** pending data, including hash table overhead, but not malloc overhead. 
98545   ** When nPendingData exceeds nMaxPendingData, the buffer is flushed 
98546   ** automatically. Variable iPrevDocid is the docid of the most recently
98547   ** inserted record.
98548   */
98549   int nMaxPendingData;
98550   int nPendingData;
98551   sqlite_int64 iPrevDocid;
98552   Fts3Hash pendingTerms;
98553 };
98554
98555 /*
98556 ** When the core wants to read from the virtual table, it creates a
98557 ** virtual table cursor (an instance of the following structure) using
98558 ** the xOpen method. Cursors are destroyed using the xClose method.
98559 */
98560 struct Fts3Cursor {
98561   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
98562   i16 eSearch;                    /* Search strategy (see below) */
98563   u8 isEof;                       /* True if at End Of Results */
98564   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
98565   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
98566   Fts3Expr *pExpr;                /* Parsed MATCH query string */
98567   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
98568   char *pNextId;                  /* Pointer into the body of aDoclist */
98569   char *aDoclist;                 /* List of docids for full-text queries */
98570   int nDoclist;                   /* Size of buffer at aDoclist */
98571   int isMatchinfoOk;              /* True when aMatchinfo[] matches iPrevId */
98572   u32 *aMatchinfo;
98573 };
98574
98575 /*
98576 ** The Fts3Cursor.eSearch member is always set to one of the following.
98577 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
98578 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
98579 ** of the column to be searched.  For example, in
98580 **
98581 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
98582 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
98583 ** 
98584 ** Because the LHS of the MATCH operator is 2nd column "b",
98585 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
98586 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
98587 ** indicating that all columns should be searched,
98588 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
98589 */
98590 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
98591 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
98592 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
98593
98594 /*
98595 ** A "phrase" is a sequence of one or more tokens that must match in
98596 ** sequence.  A single token is the base case and the most common case.
98597 ** For a sequence of tokens contained in "...", nToken will be the number
98598 ** of tokens in the string.
98599 */
98600 struct Fts3Phrase {
98601   int nToken;                /* Number of tokens in the phrase */
98602   int iColumn;               /* Index of column this phrase must match */
98603   int isNot;                 /* Phrase prefixed by unary not (-) operator */
98604   struct PhraseToken {
98605     char *z;                 /* Text of the token */
98606     int n;                   /* Number of bytes in buffer pointed to by z */
98607     int isPrefix;            /* True if token ends in with a "*" character */
98608   } aToken[1];               /* One entry for each token in the phrase */
98609 };
98610
98611 /*
98612 ** A tree of these objects forms the RHS of a MATCH operator.
98613 **
98614 ** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
98615 ** is true, then aDoclist points to a malloced buffer, size nDoclist bytes, 
98616 ** containing the results of the NEAR or phrase query in FTS3 doclist
98617 ** format. As usual, the initial "Length" field found in doclists stored
98618 ** on disk is omitted from this buffer.
98619 **
98620 ** Variable pCurrent always points to the start of a docid field within
98621 ** aDoclist. Since the doclist is usually scanned in docid order, this can
98622 ** be used to accelerate seeking to the required docid within the doclist.
98623 */
98624 struct Fts3Expr {
98625   int eType;                 /* One of the FTSQUERY_XXX values defined below */
98626   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
98627   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
98628   Fts3Expr *pLeft;           /* Left operand */
98629   Fts3Expr *pRight;          /* Right operand */
98630   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
98631
98632   int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
98633   char *aDoclist;            /* Buffer containing doclist */
98634   int nDoclist;              /* Size of aDoclist in bytes */
98635
98636   sqlite3_int64 iCurrent;
98637   char *pCurrent;
98638 };
98639
98640 /*
98641 ** Candidate values for Fts3Query.eType. Note that the order of the first
98642 ** four values is in order of precedence when parsing expressions. For 
98643 ** example, the following:
98644 **
98645 **   "a OR b AND c NOT d NEAR e"
98646 **
98647 ** is equivalent to:
98648 **
98649 **   "a OR (b AND (c NOT (d NEAR e)))"
98650 */
98651 #define FTSQUERY_NEAR   1
98652 #define FTSQUERY_NOT    2
98653 #define FTSQUERY_AND    3
98654 #define FTSQUERY_OR     4
98655 #define FTSQUERY_PHRASE 5
98656
98657
98658 /* fts3_init.c */
98659 SQLITE_PRIVATE int sqlite3Fts3DeleteVtab(int, sqlite3_vtab *);
98660 SQLITE_PRIVATE int sqlite3Fts3InitVtab(int, sqlite3*, void*, int, const char*const*, 
98661                         sqlite3_vtab **, char **);
98662
98663 /* fts3_write.c */
98664 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
98665 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
98666 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
98667 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
98668 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(Fts3Table *,int, sqlite3_int64,
98669   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
98670 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
98671 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *, Fts3SegReader *);
98672 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
98673   Fts3Table *, Fts3SegReader **, int, Fts3SegFilter *,
98674   int (*)(Fts3Table *, void *, char *, int, char *, int),  void *
98675 );
98676 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char const**, int*);
98677 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
98678
98679 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
98680 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
98681 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
98682 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
98683 #define FTS3_SEGMENT_PREFIX        0x00000008
98684
98685 /* Type passed as 4th argument to SegmentReaderIterate() */
98686 struct Fts3SegFilter {
98687   const char *zTerm;
98688   int nTerm;
98689   int iCol;
98690   int flags;
98691 };
98692
98693 /* fts3.c */
98694 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
98695 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
98696 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
98697 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
98698 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
98699
98700 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
98701 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *, Fts3Expr *);
98702
98703 /* fts3_tokenizer.c */
98704 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
98705 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
98706 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, 
98707   const char *, sqlite3_tokenizer **, const char **, char **
98708 );
98709
98710 /* fts3_snippet.c */
98711 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
98712 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context*, Fts3Cursor*, 
98713   const char *, const char *, const char *
98714 );
98715 SQLITE_PRIVATE void sqlite3Fts3Snippet2(sqlite3_context *, Fts3Cursor *, const char *,
98716   const char *, const char *, int, int
98717 );
98718 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *);
98719
98720 /* fts3_expr.c */
98721 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, 
98722   char **, int, int, const char *, int, Fts3Expr **
98723 );
98724 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
98725 #ifdef SQLITE_TEST
98726 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
98727 #endif
98728
98729 #endif /* _FTSINT_H */
98730
98731 /************** End of fts3Int.h *********************************************/
98732 /************** Continuing where we left off in fts3.c ***********************/
98733
98734
98735 #ifndef SQLITE_CORE 
98736   SQLITE_EXTENSION_INIT1
98737 #endif
98738
98739 /* 
98740 ** Write a 64-bit variable-length integer to memory starting at p[0].
98741 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
98742 ** The number of bytes written is returned.
98743 */
98744 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
98745   unsigned char *q = (unsigned char *) p;
98746   sqlite_uint64 vu = v;
98747   do{
98748     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
98749     vu >>= 7;
98750   }while( vu!=0 );
98751   q[-1] &= 0x7f;  /* turn off high bit in final byte */
98752   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
98753   return (int) (q - (unsigned char *)p);
98754 }
98755
98756 /* 
98757 ** Read a 64-bit variable-length integer from memory starting at p[0].
98758 ** Return the number of bytes read, or 0 on error.
98759 ** The value is stored in *v.
98760 */
98761 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
98762   const unsigned char *q = (const unsigned char *) p;
98763   sqlite_uint64 x = 0, y = 1;
98764   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
98765     x += y * (*q++ & 0x7f);
98766     y <<= 7;
98767   }
98768   x += y * (*q++);
98769   *v = (sqlite_int64) x;
98770   return (int) (q - (unsigned char *)p);
98771 }
98772
98773 /*
98774 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
98775 ** 32-bit integer before it is returned.
98776 */
98777 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
98778  sqlite_int64 i;
98779  int ret = sqlite3Fts3GetVarint(p, &i);
98780  *pi = (int) i;
98781  return ret;
98782 }
98783
98784 /*
98785 ** Return the number of bytes required to store the value passed as the
98786 ** first argument in varint form.
98787 */
98788 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
98789   int i = 0;
98790   do{
98791     i++;
98792     v >>= 7;
98793   }while( v!=0 );
98794   return i;
98795 }
98796
98797 /*
98798 ** Convert an SQL-style quoted string into a normal string by removing
98799 ** the quote characters.  The conversion is done in-place.  If the
98800 ** input does not begin with a quote character, then this routine
98801 ** is a no-op.
98802 **
98803 ** Examples:
98804 **
98805 **     "abc"   becomes   abc
98806 **     'xyz'   becomes   xyz
98807 **     [pqr]   becomes   pqr
98808 **     `mno`   becomes   mno
98809 **
98810 */
98811 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
98812   char quote;                     /* Quote character (if any ) */
98813
98814   quote = z[0];
98815   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
98816     int iIn = 1;                  /* Index of next byte to read from input */
98817     int iOut = 0;                 /* Index of next byte to write to output */
98818
98819     /* If the first byte was a '[', then the close-quote character is a ']' */
98820     if( quote=='[' ) quote = ']';  
98821
98822     while( ALWAYS(z[iIn]) ){
98823       if( z[iIn]==quote ){
98824         if( z[iIn+1]!=quote ) break;
98825         z[iOut++] = quote;
98826         iIn += 2;
98827       }else{
98828         z[iOut++] = z[iIn++];
98829       }
98830     }
98831     z[iOut] = '\0';
98832   }
98833 }
98834
98835 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
98836   sqlite3_int64 iVal;
98837   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
98838   *pVal += iVal;
98839 }
98840
98841 static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
98842   if( *pp>=pEnd ){
98843     *pp = 0;
98844   }else{
98845     fts3GetDeltaVarint(pp, pVal);
98846   }
98847 }
98848
98849 /*
98850 ** The xDisconnect() virtual table method.
98851 */
98852 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
98853   Fts3Table *p = (Fts3Table *)pVtab;
98854   int i;
98855
98856   assert( p->nPendingData==0 );
98857
98858   /* Free any prepared statements held */
98859   for(i=0; i<SizeofArray(p->aStmt); i++){
98860     sqlite3_finalize(p->aStmt[i]);
98861   }
98862   for(i=0; i<p->nLeavesStmt; i++){
98863     sqlite3_finalize(p->aLeavesStmt[i]);
98864   }
98865   sqlite3_free(p->zSelectLeaves);
98866   sqlite3_free(p->aLeavesStmt);
98867
98868   /* Invoke the tokenizer destructor to free the tokenizer. */
98869   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
98870
98871   sqlite3_free(p);
98872   return SQLITE_OK;
98873 }
98874
98875 /*
98876 ** The xDestroy() virtual table method.
98877 */
98878 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
98879   int rc;                         /* Return code */
98880   Fts3Table *p = (Fts3Table *)pVtab;
98881
98882   /* Create a script to drop the underlying three storage tables. */
98883   char *zSql = sqlite3_mprintf(
98884       "DROP TABLE IF EXISTS %Q.'%q_content';"
98885       "DROP TABLE IF EXISTS %Q.'%q_segments';"
98886       "DROP TABLE IF EXISTS %Q.'%q_segdir';", 
98887       p->zDb, p->zName, p->zDb, p->zName, p->zDb, p->zName
98888   );
98889
98890   /* If malloc has failed, set rc to SQLITE_NOMEM. Otherwise, try to
98891   ** execute the SQL script created above.
98892   */
98893   if( zSql ){
98894     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
98895     sqlite3_free(zSql);
98896   }else{
98897     rc = SQLITE_NOMEM;
98898   }
98899
98900   /* If everything has worked, invoke fts3DisconnectMethod() to free the
98901   ** memory associated with the Fts3Table structure and return SQLITE_OK.
98902   ** Otherwise, return an SQLite error code.
98903   */
98904   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
98905 }
98906
98907
98908 /*
98909 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
98910 ** passed as the first argument. This is done as part of the xConnect()
98911 ** and xCreate() methods.
98912 */
98913 static int fts3DeclareVtab(Fts3Table *p){
98914   int i;                          /* Iterator variable */
98915   int rc;                         /* Return code */
98916   char *zSql;                     /* SQL statement passed to declare_vtab() */
98917   char *zCols;                    /* List of user defined columns */
98918
98919   /* Create a list of user columns for the virtual table */
98920   zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
98921   for(i=1; zCols && i<p->nColumn; i++){
98922     zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
98923   }
98924
98925   /* Create the whole "CREATE TABLE" statement to pass to SQLite */
98926   zSql = sqlite3_mprintf(
98927       "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
98928   );
98929
98930   if( !zCols || !zSql ){
98931     rc = SQLITE_NOMEM;
98932   }else{
98933     rc = sqlite3_declare_vtab(p->db, zSql);
98934   }
98935
98936   sqlite3_free(zSql);
98937   sqlite3_free(zCols);
98938   return rc;
98939 }
98940
98941 /*
98942 ** Create the backing store tables (%_content, %_segments and %_segdir)
98943 ** required by the FTS3 table passed as the only argument. This is done
98944 ** as part of the vtab xCreate() method.
98945 */
98946 static int fts3CreateTables(Fts3Table *p){
98947   int rc;                         /* Return code */
98948   int i;                          /* Iterator variable */
98949   char *zContentCols;             /* Columns of %_content table */
98950   char *zSql;                     /* SQL script to create required tables */
98951
98952   /* Create a list of user columns for the content table */
98953   zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
98954   for(i=0; zContentCols && i<p->nColumn; i++){
98955     char *z = p->azColumn[i];
98956     zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
98957   }
98958
98959   /* Create the whole SQL script */
98960   zSql = sqlite3_mprintf(
98961       "CREATE TABLE %Q.'%q_content'(%s);"
98962       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);"
98963       "CREATE TABLE %Q.'%q_segdir'("
98964         "level INTEGER,"
98965         "idx INTEGER,"
98966         "start_block INTEGER,"
98967         "leaves_end_block INTEGER,"
98968         "end_block INTEGER,"
98969         "root BLOB,"
98970         "PRIMARY KEY(level, idx)"
98971       ");",
98972       p->zDb, p->zName, zContentCols, p->zDb, p->zName, p->zDb, p->zName
98973   );
98974
98975   /* Unless a malloc() failure has occurred, execute the SQL script to 
98976   ** create the tables used to store data for this FTS3 virtual table.
98977   */
98978   if( zContentCols==0 || zSql==0 ){
98979     rc = SQLITE_NOMEM;
98980   }else{
98981     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
98982   }
98983
98984   sqlite3_free(zSql);
98985   sqlite3_free(zContentCols);
98986   return rc;
98987 }
98988
98989 /*
98990 ** This function is the implementation of both the xConnect and xCreate
98991 ** methods of the FTS3 virtual table.
98992 **
98993 ** The argv[] array contains the following:
98994 **
98995 **   argv[0]   -> module name
98996 **   argv[1]   -> database name
98997 **   argv[2]   -> table name
98998 **   argv[...] -> "column name" and other module argument fields.
98999 */
99000 static int fts3InitVtab(
99001   int isCreate,                   /* True for xCreate, false for xConnect */
99002   sqlite3 *db,                    /* The SQLite database connection */
99003   void *pAux,                     /* Hash table containing tokenizers */
99004   int argc,                       /* Number of elements in argv array */
99005   const char * const *argv,       /* xCreate/xConnect argument array */
99006   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
99007   char **pzErr                    /* Write any error message here */
99008 ){
99009   Fts3Hash *pHash = (Fts3Hash *)pAux;
99010   Fts3Table *p;                   /* Pointer to allocated vtab */
99011   int rc;                         /* Return code */
99012   int i;                          /* Iterator variable */
99013   int nByte;                      /* Size of allocation used for *p */
99014   int iCol;
99015   int nString = 0;
99016   int nCol = 0;
99017   char *zCsr;
99018   int nDb;
99019   int nName;
99020
99021   const char *zTokenizer = 0;               /* Name of tokenizer to use */
99022   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
99023
99024   nDb = (int)strlen(argv[1]) + 1;
99025   nName = (int)strlen(argv[2]) + 1;
99026   for(i=3; i<argc; i++){
99027     char const *z = argv[i];
99028     rc = sqlite3Fts3InitTokenizer(pHash, z, &pTokenizer, &zTokenizer, pzErr);
99029     if( rc!=SQLITE_OK ){
99030       return rc;
99031     }
99032     if( z!=zTokenizer ){
99033       nString += (int)(strlen(z) + 1);
99034     }
99035   }
99036   nCol = argc - 3 - (zTokenizer!=0);
99037   if( zTokenizer==0 ){
99038     rc = sqlite3Fts3InitTokenizer(pHash, 0, &pTokenizer, 0, pzErr);
99039     if( rc!=SQLITE_OK ){
99040       return rc;
99041     }
99042     assert( pTokenizer );
99043   }
99044
99045   if( nCol==0 ){
99046     nCol = 1;
99047   }
99048
99049   /* Allocate and populate the Fts3Table structure. */
99050   nByte = sizeof(Fts3Table) +              /* Fts3Table */
99051           nCol * sizeof(char *) +              /* azColumn */
99052           nName +                              /* zName */
99053           nDb +                                /* zDb */
99054           nString;                             /* Space for azColumn strings */
99055   p = (Fts3Table*)sqlite3_malloc(nByte);
99056   if( p==0 ){
99057     rc = SQLITE_NOMEM;
99058     goto fts3_init_out;
99059   }
99060   memset(p, 0, nByte);
99061
99062   p->db = db;
99063   p->nColumn = nCol;
99064   p->nPendingData = 0;
99065   p->azColumn = (char **)&p[1];
99066   p->pTokenizer = pTokenizer;
99067   p->nNodeSize = 1000;
99068   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
99069   zCsr = (char *)&p->azColumn[nCol];
99070
99071   fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
99072
99073   /* Fill in the zName and zDb fields of the vtab structure. */
99074   p->zName = zCsr;
99075   memcpy(zCsr, argv[2], nName);
99076   zCsr += nName;
99077   p->zDb = zCsr;
99078   memcpy(zCsr, argv[1], nDb);
99079   zCsr += nDb;
99080
99081   /* Fill in the azColumn array */
99082   iCol = 0;
99083   for(i=3; i<argc; i++){
99084     if( argv[i]!=zTokenizer ){
99085       char *z; 
99086       int n;
99087       z = (char *)sqlite3Fts3NextToken(argv[i], &n);
99088       memcpy(zCsr, z, n);
99089       zCsr[n] = '\0';
99090       sqlite3Fts3Dequote(zCsr);
99091       p->azColumn[iCol++] = zCsr;
99092       zCsr += n+1;
99093       assert( zCsr <= &((char *)p)[nByte] );
99094     }
99095   }
99096   if( iCol==0 ){
99097     assert( nCol==1 );
99098     p->azColumn[0] = "content";
99099   }
99100
99101   /* If this is an xCreate call, create the underlying tables in the 
99102   ** database. TODO: For xConnect(), it could verify that said tables exist.
99103   */
99104   if( isCreate ){
99105     rc = fts3CreateTables(p);
99106     if( rc!=SQLITE_OK ) goto fts3_init_out;
99107   }
99108
99109   rc = fts3DeclareVtab(p);
99110   if( rc!=SQLITE_OK ) goto fts3_init_out;
99111
99112   *ppVTab = &p->base;
99113
99114 fts3_init_out:
99115   assert( p || (pTokenizer && rc!=SQLITE_OK) );
99116   if( rc!=SQLITE_OK ){
99117     if( p ){
99118       fts3DisconnectMethod((sqlite3_vtab *)p);
99119     }else{
99120       pTokenizer->pModule->xDestroy(pTokenizer);
99121     }
99122   }
99123   return rc;
99124 }
99125
99126 /*
99127 ** The xConnect() and xCreate() methods for the virtual table. All the
99128 ** work is done in function fts3InitVtab().
99129 */
99130 static int fts3ConnectMethod(
99131   sqlite3 *db,                    /* Database connection */
99132   void *pAux,                     /* Pointer to tokenizer hash table */
99133   int argc,                       /* Number of elements in argv array */
99134   const char * const *argv,       /* xCreate/xConnect argument array */
99135   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
99136   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
99137 ){
99138   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
99139 }
99140 static int fts3CreateMethod(
99141   sqlite3 *db,                    /* Database connection */
99142   void *pAux,                     /* Pointer to tokenizer hash table */
99143   int argc,                       /* Number of elements in argv array */
99144   const char * const *argv,       /* xCreate/xConnect argument array */
99145   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
99146   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
99147 ){
99148   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
99149 }
99150
99151 /* 
99152 ** Implementation of the xBestIndex method for FTS3 tables. There
99153 ** are three possible strategies, in order of preference:
99154 **
99155 **   1. Direct lookup by rowid or docid. 
99156 **   2. Full-text search using a MATCH operator on a non-docid column.
99157 **   3. Linear scan of %_content table.
99158 */
99159 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
99160   Fts3Table *p = (Fts3Table *)pVTab;
99161   int i;                          /* Iterator variable */
99162   int iCons = -1;                 /* Index of constraint to use */
99163
99164   /* By default use a full table scan. This is an expensive option,
99165   ** so search through the constraints to see if a more efficient 
99166   ** strategy is possible.
99167   */
99168   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
99169   pInfo->estimatedCost = 500000;
99170   for(i=0; i<pInfo->nConstraint; i++){
99171     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
99172     if( pCons->usable==0 ) continue;
99173
99174     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
99175     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
99176      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
99177     ){
99178       pInfo->idxNum = FTS3_DOCID_SEARCH;
99179       pInfo->estimatedCost = 1.0;
99180       iCons = i;
99181     }
99182
99183     /* A MATCH constraint. Use a full-text search.
99184     **
99185     ** If there is more than one MATCH constraint available, use the first
99186     ** one encountered. If there is both a MATCH constraint and a direct
99187     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
99188     ** though the rowid/docid lookup is faster than a MATCH query, selecting
99189     ** it would lead to an "unable to use function MATCH in the requested 
99190     ** context" error.
99191     */
99192     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
99193      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
99194     ){
99195       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
99196       pInfo->estimatedCost = 2.0;
99197       iCons = i;
99198       break;
99199     }
99200   }
99201
99202   if( iCons>=0 ){
99203     pInfo->aConstraintUsage[iCons].argvIndex = 1;
99204     pInfo->aConstraintUsage[iCons].omit = 1;
99205   } 
99206   return SQLITE_OK;
99207 }
99208
99209 /*
99210 ** Implementation of xOpen method.
99211 */
99212 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
99213   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
99214
99215   UNUSED_PARAMETER(pVTab);
99216
99217   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
99218   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
99219   ** if the allocation fails, return SQLITE_NOMEM.
99220   */
99221   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
99222   if( !pCsr ){
99223     return SQLITE_NOMEM;
99224   }
99225   memset(pCsr, 0, sizeof(Fts3Cursor));
99226   return SQLITE_OK;
99227 }
99228
99229 /****************************************************************/
99230 /****************************************************************/
99231 /****************************************************************/
99232 /****************************************************************/
99233
99234
99235 /*
99236 ** Close the cursor.  For additional information see the documentation
99237 ** on the xClose method of the virtual table interface.
99238 */
99239 static int fulltextClose(sqlite3_vtab_cursor *pCursor){
99240   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
99241   sqlite3_finalize(pCsr->pStmt);
99242   sqlite3Fts3ExprFree(pCsr->pExpr);
99243   sqlite3_free(pCsr->aDoclist);
99244   sqlite3_free(pCsr->aMatchinfo);
99245   sqlite3_free(pCsr);
99246   return SQLITE_OK;
99247 }
99248
99249 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
99250   if( pCsr->isRequireSeek ){
99251     pCsr->isRequireSeek = 0;
99252     sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
99253     if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
99254       return SQLITE_OK;
99255     }else{
99256       int rc = sqlite3_reset(pCsr->pStmt);
99257       if( rc==SQLITE_OK ){
99258         /* If no row was found and no error has occured, then the %_content
99259         ** table is missing a row that is present in the full-text index.
99260         ** The data structures are corrupt.
99261         */
99262         rc = SQLITE_CORRUPT;
99263       }
99264       pCsr->isEof = 1;
99265       if( pContext ){
99266         sqlite3_result_error_code(pContext, rc);
99267       }
99268       return rc;
99269     }
99270   }else{
99271     return SQLITE_OK;
99272   }
99273 }
99274
99275 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
99276   int rc = SQLITE_OK;             /* Return code */
99277   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
99278
99279   if( pCsr->aDoclist==0 ){
99280     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
99281       pCsr->isEof = 1;
99282       rc = sqlite3_reset(pCsr->pStmt);
99283     }
99284   }else if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
99285     pCsr->isEof = 1;
99286   }else{
99287     sqlite3_reset(pCsr->pStmt);
99288     fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
99289     pCsr->isRequireSeek = 1;
99290     pCsr->isMatchinfoOk = 1;
99291   }
99292   return rc;
99293 }
99294
99295
99296 /*
99297 ** The buffer pointed to by argument zNode (size nNode bytes) contains the
99298 ** root node of a b-tree segment. The segment is guaranteed to be at least
99299 ** one level high (i.e. the root node is not also a leaf). If successful,
99300 ** this function locates the leaf node of the segment that may contain the 
99301 ** term specified by arguments zTerm and nTerm and writes its block number 
99302 ** to *piLeaf.
99303 **
99304 ** It is possible that the returned leaf node does not contain the specified
99305 ** term. However, if the segment does contain said term, it is stored on
99306 ** the identified leaf node. Because this function only inspects interior
99307 ** segment nodes (and never loads leaf nodes into memory), it is not possible
99308 ** to be sure.
99309 **
99310 ** If an error occurs, an error code other than SQLITE_OK is returned.
99311 */ 
99312 static int fts3SelectLeaf(
99313   Fts3Table *p,                   /* Virtual table handle */
99314   const char *zTerm,              /* Term to select leaves for */
99315   int nTerm,                      /* Size of term zTerm in bytes */
99316   const char *zNode,              /* Buffer containing segment interior node */
99317   int nNode,                      /* Size of buffer at zNode */
99318   sqlite3_int64 *piLeaf           /* Selected leaf node */
99319 ){
99320   int rc = SQLITE_OK;             /* Return code */
99321   const char *zCsr = zNode;       /* Cursor to iterate through node */
99322   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
99323   char *zBuffer = 0;              /* Buffer to load terms into */
99324   int nAlloc = 0;                 /* Size of allocated buffer */
99325
99326   while( 1 ){
99327     int isFirstTerm = 1;          /* True when processing first term on page */
99328     int iHeight;                  /* Height of this node in tree */
99329     sqlite3_int64 iChild;         /* Block id of child node to descend to */
99330     int nBlock;                   /* Size of child node in bytes */
99331
99332     zCsr += sqlite3Fts3GetVarint32(zCsr, &iHeight);
99333     zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
99334   
99335     while( zCsr<zEnd ){
99336       int cmp;                    /* memcmp() result */
99337       int nSuffix;                /* Size of term suffix */
99338       int nPrefix = 0;            /* Size of term prefix */
99339       int nBuffer;                /* Total term size */
99340   
99341       /* Load the next term on the node into zBuffer */
99342       if( !isFirstTerm ){
99343         zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
99344       }
99345       isFirstTerm = 0;
99346       zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
99347       if( nPrefix+nSuffix>nAlloc ){
99348         char *zNew;
99349         nAlloc = (nPrefix+nSuffix) * 2;
99350         zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
99351         if( !zNew ){
99352           sqlite3_free(zBuffer);
99353           return SQLITE_NOMEM;
99354         }
99355         zBuffer = zNew;
99356       }
99357       memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
99358       nBuffer = nPrefix + nSuffix;
99359       zCsr += nSuffix;
99360   
99361       /* Compare the term we are searching for with the term just loaded from
99362       ** the interior node. If the specified term is greater than or equal
99363       ** to the term from the interior node, then all terms on the sub-tree 
99364       ** headed by node iChild are smaller than zTerm. No need to search 
99365       ** iChild.
99366       **
99367       ** If the interior node term is larger than the specified term, then
99368       ** the tree headed by iChild may contain the specified term.
99369       */
99370       cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
99371       if( cmp<0 || (cmp==0 && nBuffer>nTerm) ) break;
99372       iChild++;
99373     };
99374
99375     /* If (iHeight==1), the children of this interior node are leaves. The
99376     ** specified term may be present on leaf node iChild.
99377     */
99378     if( iHeight==1 ){
99379       *piLeaf = iChild;
99380       break;
99381     }
99382
99383     /* Descend to interior node iChild. */
99384     rc = sqlite3Fts3ReadBlock(p, iChild, &zCsr, &nBlock);
99385     if( rc!=SQLITE_OK ) break;
99386     zEnd = &zCsr[nBlock];
99387   }
99388   sqlite3_free(zBuffer);
99389   return rc;
99390 }
99391
99392 /*
99393 ** This function is used to create delta-encoded serialized lists of FTS3 
99394 ** varints. Each call to this function appends a single varint to a list.
99395 */
99396 static void fts3PutDeltaVarint(
99397   char **pp,                      /* IN/OUT: Output pointer */
99398   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
99399   sqlite3_int64 iVal              /* Write this value to the list */
99400 ){
99401   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
99402   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
99403   *piPrev = iVal;
99404 }
99405
99406 /*
99407 ** When this function is called, *ppPoslist is assumed to point to the 
99408 ** start of a position-list.
99409 */
99410 static void fts3PoslistCopy(char **pp, char **ppPoslist){
99411   char *pEnd = *ppPoslist;
99412   char c = 0;
99413
99414   /* The end of a position list is marked by a zero encoded as an FTS3 
99415   ** varint. A single 0x00 byte. Except, if the 0x00 byte is preceded by
99416   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
99417   ** of some other, multi-byte, value.
99418   **
99419   ** The following block moves pEnd to point to the first byte that is not 
99420   ** immediately preceded by a byte with the 0x80 bit set. Then increments
99421   ** pEnd once more so that it points to the byte immediately following the
99422   ** last byte in the position-list.
99423   */
99424   while( *pEnd | c ) c = *pEnd++ & 0x80;
99425   pEnd++;
99426
99427   if( pp ){
99428     int n = (int)(pEnd - *ppPoslist);
99429     char *p = *pp;
99430     memcpy(p, *ppPoslist, n);
99431     p += n;
99432     *pp = p;
99433   }
99434   *ppPoslist = pEnd;
99435 }
99436
99437 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
99438   char *pEnd = *ppPoslist;
99439   char c = 0;
99440
99441   /* A column-list is terminated by either a 0x01 or 0x00. */
99442   while( 0xFE & (*pEnd | c) ) c = *pEnd++ & 0x80;
99443   if( pp ){
99444     int n = (int)(pEnd - *ppPoslist);
99445     char *p = *pp;
99446     memcpy(p, *ppPoslist, n);
99447     p += n;
99448     *pp = p;
99449   }
99450   *ppPoslist = pEnd;
99451 }
99452
99453 /*
99454 ** Value used to signify the end of an offset-list. This is safe because
99455 ** it is not possible to have a document with 2^31 terms.
99456 */
99457 #define OFFSET_LIST_END 0x7fffffff
99458
99459 /*
99460 ** This function is used to help parse offset-lists. When this function is
99461 ** called, *pp may point to the start of the next varint in the offset-list
99462 ** being parsed, or it may point to 1 byte past the end of the offset-list
99463 ** (in which case **pp will be 0x00 or 0x01).
99464 **
99465 ** If *pp points past the end of the current offset list, set *pi to 
99466 ** OFFSET_LIST_END and return. Otherwise, read the next varint from *pp,
99467 ** increment the current value of *pi by the value read, and set *pp to
99468 ** point to the next value before returning.
99469 */
99470 static void fts3ReadNextPos(
99471   char **pp,                      /* IN/OUT: Pointer into offset-list buffer */
99472   sqlite3_int64 *pi               /* IN/OUT: Value read from offset-list */
99473 ){
99474   if( **pp&0xFE ){
99475     fts3GetDeltaVarint(pp, pi);
99476     *pi -= 2;
99477   }else{
99478     *pi = OFFSET_LIST_END;
99479   }
99480 }
99481
99482 /*
99483 ** If parameter iCol is not 0, write an 0x01 byte followed by the value of
99484 ** iCol encoded as a varint to *pp. 
99485 **
99486 ** Set *pp to point to the byte just after the last byte written before 
99487 ** returning (do not modify it if iCol==0). Return the total number of bytes
99488 ** written (0 if iCol==0).
99489 */
99490 static int fts3PutColNumber(char **pp, int iCol){
99491   int n = 0;                      /* Number of bytes written */
99492   if( iCol ){
99493     char *p = *pp;                /* Output pointer */
99494     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
99495     *p = 0x01;
99496     *pp = &p[n];
99497   }
99498   return n;
99499 }
99500
99501 /*
99502 **
99503 */
99504 static void fts3PoslistMerge(
99505   char **pp,                      /* Output buffer */
99506   char **pp1,                     /* Left input list */
99507   char **pp2                      /* Right input list */
99508 ){
99509   char *p = *pp;
99510   char *p1 = *pp1;
99511   char *p2 = *pp2;
99512
99513   while( *p1 || *p2 ){
99514     int iCol1;
99515     int iCol2;
99516
99517     if( *p1==0x01 ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
99518     else if( *p1==0x00 ) iCol1 = OFFSET_LIST_END;
99519     else iCol1 = 0;
99520
99521     if( *p2==0x01 ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
99522     else if( *p2==0x00 ) iCol2 = OFFSET_LIST_END;
99523     else iCol2 = 0;
99524
99525     if( iCol1==iCol2 ){
99526       sqlite3_int64 i1 = 0;
99527       sqlite3_int64 i2 = 0;
99528       sqlite3_int64 iPrev = 0;
99529       int n = fts3PutColNumber(&p, iCol1);
99530       p1 += n;
99531       p2 += n;
99532
99533       /* At this point, both p1 and p2 point to the start of offset-lists.
99534       ** An offset-list is a list of non-negative delta-encoded varints, each 
99535       ** incremented by 2 before being stored. Each list is terminated by a 0 
99536       ** or 1 value (0x00 or 0x01). The following block merges the two lists
99537       ** and writes the results to buffer p. p is left pointing to the byte
99538       ** after the list written. No terminator (0x00 or 0x01) is written to
99539       ** the output.
99540       */
99541       fts3GetDeltaVarint(&p1, &i1);
99542       fts3GetDeltaVarint(&p2, &i2);
99543       do {
99544         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
99545         iPrev -= 2;
99546         if( i1==i2 ){
99547           fts3ReadNextPos(&p1, &i1);
99548           fts3ReadNextPos(&p2, &i2);
99549         }else if( i1<i2 ){
99550           fts3ReadNextPos(&p1, &i1);
99551         }else{
99552           fts3ReadNextPos(&p2, &i2);
99553         }
99554       }while( i1!=OFFSET_LIST_END || i2!=OFFSET_LIST_END );
99555     }else if( iCol1<iCol2 ){
99556       p1 += fts3PutColNumber(&p, iCol1);
99557       fts3ColumnlistCopy(&p, &p1);
99558     }else{
99559       p2 += fts3PutColNumber(&p, iCol2);
99560       fts3ColumnlistCopy(&p, &p2);
99561     }
99562   }
99563
99564   *p++ = '\0';
99565   *pp = p;
99566   *pp1 = p1 + 1;
99567   *pp2 = p2 + 1;
99568 }
99569
99570 /*
99571 ** nToken==1 searches for adjacent positions.
99572 */
99573 static int fts3PoslistPhraseMerge(
99574   char **pp,                      /* Output buffer */
99575   int nToken,                     /* Maximum difference in token positions */
99576   int isSaveLeft,                 /* Save the left position */
99577   char **pp1,                     /* Left input list */
99578   char **pp2                      /* Right input list */
99579 ){
99580   char *p = (pp ? *pp : 0);
99581   char *p1 = *pp1;
99582   char *p2 = *pp2;
99583
99584   int iCol1 = 0;
99585   int iCol2 = 0;
99586   assert( *p1!=0 && *p2!=0 );
99587   if( *p1==0x01 ){ 
99588     p1++;
99589     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
99590   }
99591   if( *p2==0x01 ){ 
99592     p2++;
99593     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
99594   }
99595
99596   while( 1 ){
99597     if( iCol1==iCol2 ){
99598       char *pSave = p;
99599       sqlite3_int64 iPrev = 0;
99600       sqlite3_int64 iPos1 = 0;
99601       sqlite3_int64 iPos2 = 0;
99602
99603       if( pp && iCol1 ){
99604         *p++ = 0x01;
99605         p += sqlite3Fts3PutVarint(p, iCol1);
99606       }
99607
99608       assert( *p1!=0x00 && *p2!=0x00 && *p1!=0x01 && *p2!=0x01 );
99609       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
99610       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
99611
99612       while( 1 ){
99613         if( iPos2>iPos1 && iPos2<=iPos1+nToken ){
99614           sqlite3_int64 iSave;
99615           if( !pp ){
99616             fts3PoslistCopy(0, &p2);
99617             fts3PoslistCopy(0, &p1);
99618             *pp1 = p1;
99619             *pp2 = p2;
99620             return 1;
99621           }
99622           iSave = isSaveLeft ? iPos1 : iPos2;
99623           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
99624           pSave = 0;
99625         }
99626         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
99627           if( (*p2&0xFE)==0 ) break;
99628           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
99629         }else{
99630           if( (*p1&0xFE)==0 ) break;
99631           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
99632         }
99633       }
99634
99635       if( pSave ){
99636         assert( pp && p );
99637         p = pSave;
99638       }
99639
99640       fts3ColumnlistCopy(0, &p1);
99641       fts3ColumnlistCopy(0, &p2);
99642       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
99643       if( 0==*p1 || 0==*p2 ) break;
99644
99645       p1++;
99646       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
99647       p2++;
99648       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
99649     }
99650
99651     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
99652     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
99653     ** end of the position list, or the 0x01 that precedes the next 
99654     ** column-number in the position list. 
99655     */
99656     else if( iCol1<iCol2 ){
99657       fts3ColumnlistCopy(0, &p1);
99658       if( 0==*p1 ) break;
99659       p1++;
99660       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
99661     }else{
99662       fts3ColumnlistCopy(0, &p2);
99663       if( 0==*p2 ) break;
99664       p2++;
99665       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
99666     }
99667   }
99668
99669   fts3PoslistCopy(0, &p2);
99670   fts3PoslistCopy(0, &p1);
99671   *pp1 = p1;
99672   *pp2 = p2;
99673   if( !pp || *pp==p ){
99674     return 0;
99675   }
99676   *p++ = 0x00;
99677   *pp = p;
99678   return 1;
99679 }
99680
99681 /*
99682 ** Merge two position-lists as required by the NEAR operator.
99683 */
99684 static int fts3PoslistNearMerge(
99685   char **pp,                      /* Output buffer */
99686   char *aTmp,                     /* Temporary buffer space */
99687   int nRight,                     /* Maximum difference in token positions */
99688   int nLeft,                      /* Maximum difference in token positions */
99689   char **pp1,                     /* IN/OUT: Left input list */
99690   char **pp2                      /* IN/OUT: Right input list */
99691 ){
99692   char *p1 = *pp1;
99693   char *p2 = *pp2;
99694
99695   if( !pp ){
99696     if( fts3PoslistPhraseMerge(0, nRight, 0, pp1, pp2) ) return 1;
99697     *pp1 = p1;
99698     *pp2 = p2;
99699     return fts3PoslistPhraseMerge(0, nLeft, 0, pp2, pp1);
99700   }else{
99701     char *pTmp1 = aTmp;
99702     char *pTmp2;
99703     char *aTmp2;
99704     int res = 1;
99705
99706     fts3PoslistPhraseMerge(&pTmp1, nRight, 0, pp1, pp2);
99707     aTmp2 = pTmp2 = pTmp1;
99708     *pp1 = p1;
99709     *pp2 = p2;
99710     fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, pp2, pp1);
99711     if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
99712       fts3PoslistMerge(pp, &aTmp, &aTmp2);
99713     }else if( pTmp1!=aTmp ){
99714       fts3PoslistCopy(pp, &aTmp);
99715     }else if( pTmp2!=aTmp2 ){
99716       fts3PoslistCopy(pp, &aTmp2);
99717     }else{
99718       res = 0;
99719     }
99720
99721     return res;
99722   }
99723 }
99724
99725 /*
99726 ** Values that may be used as the first parameter to fts3DoclistMerge().
99727 */
99728 #define MERGE_NOT        2        /* D + D -> D */
99729 #define MERGE_AND        3        /* D + D -> D */
99730 #define MERGE_OR         4        /* D + D -> D */
99731 #define MERGE_POS_OR     5        /* P + P -> P */
99732 #define MERGE_PHRASE     6        /* P + P -> D */
99733 #define MERGE_POS_PHRASE 7        /* P + P -> P */
99734 #define MERGE_NEAR       8        /* P + P -> D */
99735 #define MERGE_POS_NEAR   9        /* P + P -> P */
99736
99737 /*
99738 ** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
99739 ** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
99740 ** which is guaranteed to be large enough to hold the results. The number
99741 ** of bytes written to aBuffer is stored in *pnBuffer before returning.
99742 **
99743 ** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
99744 ** occurs while allocating a temporary buffer as part of the merge operation,
99745 ** SQLITE_NOMEM is returned.
99746 */
99747 static int fts3DoclistMerge(
99748   int mergetype,                  /* One of the MERGE_XXX constants */
99749   int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
99750   int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
99751   char *aBuffer,                  /* Pre-allocated output buffer */
99752   int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
99753   char *a1,                       /* Buffer containing first doclist */
99754   int n1,                         /* Size of buffer a1 */
99755   char *a2,                       /* Buffer containing second doclist */
99756   int n2                          /* Size of buffer a2 */
99757 ){
99758   sqlite3_int64 i1 = 0;
99759   sqlite3_int64 i2 = 0;
99760   sqlite3_int64 iPrev = 0;
99761
99762   char *p = aBuffer;
99763   char *p1 = a1;
99764   char *p2 = a2;
99765   char *pEnd1 = &a1[n1];
99766   char *pEnd2 = &a2[n2];
99767
99768   assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR 
99769        || mergetype==MERGE_AND    || mergetype==MERGE_NOT
99770        || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
99771        || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
99772   );
99773
99774   if( !aBuffer ){
99775     *pnBuffer = 0;
99776     return SQLITE_NOMEM;
99777   }
99778
99779   /* Read the first docid from each doclist */
99780   fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99781   fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99782
99783   switch( mergetype ){
99784     case MERGE_OR:
99785     case MERGE_POS_OR:
99786       while( p1 || p2 ){
99787         if( p2 && p1 && i1==i2 ){
99788           fts3PutDeltaVarint(&p, &iPrev, i1);
99789           if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
99790           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99791           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99792         }else if( !p2 || (p1 && i1<i2) ){
99793           fts3PutDeltaVarint(&p, &iPrev, i1);
99794           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
99795           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99796         }else{
99797           fts3PutDeltaVarint(&p, &iPrev, i2);
99798           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
99799           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99800         }
99801       }
99802       break;
99803
99804     case MERGE_AND:
99805       while( p1 && p2 ){
99806         if( i1==i2 ){
99807           fts3PutDeltaVarint(&p, &iPrev, i1);
99808           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99809           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99810         }else if( i1<i2 ){
99811           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99812         }else{
99813           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99814         }
99815       }
99816       break;
99817
99818     case MERGE_NOT:
99819       while( p1 ){
99820         if( p2 && i1==i2 ){
99821           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99822           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99823         }else if( !p2 || i1<i2 ){
99824           fts3PutDeltaVarint(&p, &iPrev, i1);
99825           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99826         }else{
99827           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99828         }
99829       }
99830       break;
99831
99832     case MERGE_POS_PHRASE:
99833     case MERGE_PHRASE: {
99834       char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
99835       while( p1 && p2 ){
99836         if( i1==i2 ){
99837           char *pSave = p;
99838           sqlite3_int64 iPrevSave = iPrev;
99839           fts3PutDeltaVarint(&p, &iPrev, i1);
99840           if( 0==fts3PoslistPhraseMerge(ppPos, 1, 0, &p1, &p2) ){
99841             p = pSave;
99842             iPrev = iPrevSave;
99843           }
99844           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99845           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99846         }else if( i1<i2 ){
99847           fts3PoslistCopy(0, &p1);
99848           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99849         }else{
99850           fts3PoslistCopy(0, &p2);
99851           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99852         }
99853       }
99854       break;
99855     }
99856
99857     default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
99858       char *aTmp = 0;
99859       char **ppPos = 0;
99860       if( mergetype==MERGE_POS_NEAR ){
99861         ppPos = &p;
99862         aTmp = sqlite3_malloc(2*(n1+n2+1));
99863         if( !aTmp ){
99864           return SQLITE_NOMEM;
99865         }
99866       }
99867
99868       while( p1 && p2 ){
99869         if( i1==i2 ){
99870           char *pSave = p;
99871           sqlite3_int64 iPrevSave = iPrev;
99872           fts3PutDeltaVarint(&p, &iPrev, i1);
99873
99874           if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
99875             iPrev = iPrevSave;
99876             p = pSave;
99877           }
99878
99879           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99880           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99881         }else if( i1<i2 ){
99882           fts3PoslistCopy(0, &p1);
99883           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99884         }else{
99885           fts3PoslistCopy(0, &p2);
99886           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99887         }
99888       }
99889       sqlite3_free(aTmp);
99890       break;
99891     }
99892   }
99893
99894   *pnBuffer = (int)(p-aBuffer);
99895   return SQLITE_OK;
99896 }
99897
99898 /* 
99899 ** A pointer to an instance of this structure is used as the context 
99900 ** argument to sqlite3Fts3SegReaderIterate()
99901 */
99902 typedef struct TermSelect TermSelect;
99903 struct TermSelect {
99904   int isReqPos;
99905   char *aOutput;                  /* Malloc'd output buffer */
99906   int nOutput;                    /* Size of output in bytes */
99907 };
99908
99909 /*
99910 ** This function is used as the sqlite3Fts3SegReaderIterate() callback when
99911 ** querying the full-text index for a doclist associated with a term or
99912 ** term-prefix.
99913 */
99914 static int fts3TermSelectCb(
99915   Fts3Table *p,                   /* Virtual table object */
99916   void *pContext,                 /* Pointer to TermSelect structure */
99917   char *zTerm,
99918   int nTerm,
99919   char *aDoclist,
99920   int nDoclist
99921 ){
99922   TermSelect *pTS = (TermSelect *)pContext;
99923   int nNew = pTS->nOutput + nDoclist;
99924   char *aNew = sqlite3_malloc(nNew);
99925
99926   UNUSED_PARAMETER(p);
99927   UNUSED_PARAMETER(zTerm);
99928   UNUSED_PARAMETER(nTerm);
99929
99930   if( !aNew ){
99931     return SQLITE_NOMEM;
99932   }
99933
99934   if( pTS->nOutput==0 ){
99935     /* If this is the first term selected, copy the doclist to the output
99936     ** buffer using memcpy(). TODO: Add a way to transfer control of the
99937     ** aDoclist buffer from the caller so as to avoid the memcpy().
99938     */
99939     memcpy(aNew, aDoclist, nDoclist);
99940   }else{
99941     /* The output buffer is not empty. Merge doclist aDoclist with the
99942     ** existing output. This can only happen with prefix-searches (as
99943     ** searches for exact terms return exactly one doclist).
99944     */
99945     int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
99946     fts3DoclistMerge(mergetype, 0, 0,
99947         aNew, &nNew, pTS->aOutput, pTS->nOutput, aDoclist, nDoclist
99948     );
99949   }
99950
99951   sqlite3_free(pTS->aOutput);
99952   pTS->aOutput = aNew;
99953   pTS->nOutput = nNew;
99954
99955   return SQLITE_OK;
99956 }
99957
99958 /*
99959 ** This function retreives the doclist for the specified term (or term
99960 ** prefix) from the database. 
99961 **
99962 ** The returned doclist may be in one of two formats, depending on the 
99963 ** value of parameter isReqPos. If isReqPos is zero, then the doclist is
99964 ** a sorted list of delta-compressed docids. If isReqPos is non-zero, 
99965 ** then the returned list is in the same format as is stored in the
99966 ** database without the found length specifier at the start of on-disk
99967 ** doclists.
99968 */
99969 static int fts3TermSelect(
99970   Fts3Table *p,                   /* Virtual table handle */
99971   int iColumn,                    /* Column to query (or -ve for all columns) */
99972   const char *zTerm,              /* Term to query for */
99973   int nTerm,                      /* Size of zTerm in bytes */
99974   int isPrefix,                   /* True for a prefix search */
99975   int isReqPos,                   /* True to include position lists in output */
99976   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
99977   char **ppOut                    /* OUT: Malloced result buffer */
99978 ){
99979   int i;
99980   TermSelect tsc;
99981   Fts3SegFilter filter;           /* Segment term filter configuration */
99982   Fts3SegReader **apSegment;      /* Array of segments to read data from */
99983   int nSegment = 0;               /* Size of apSegment array */
99984   int nAlloc = 16;                /* Allocated size of segment array */
99985   int rc;                         /* Return code */
99986   sqlite3_stmt *pStmt = 0;        /* SQL statement to scan %_segdir table */
99987   int iAge = 0;                   /* Used to assign ages to segments */
99988
99989   apSegment = (Fts3SegReader **)sqlite3_malloc(sizeof(Fts3SegReader*)*nAlloc);
99990   if( !apSegment ) return SQLITE_NOMEM;
99991   rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &apSegment[0]);
99992   if( rc!=SQLITE_OK ) goto finished;
99993   if( apSegment[0] ){
99994     nSegment = 1;
99995   }
99996
99997   /* Loop through the entire %_segdir table. For each segment, create a
99998   ** Fts3SegReader to iterate through the subset of the segment leaves
99999   ** that may contain a term that matches zTerm/nTerm. For non-prefix
100000   ** searches, this is always a single leaf. For prefix searches, this
100001   ** may be a contiguous block of leaves.
100002   **
100003   ** The code in this loop does not actually load any leaves into memory
100004   ** (unless the root node happens to be a leaf). It simply examines the
100005   ** b-tree structure to determine which leaves need to be inspected.
100006   */
100007   rc = sqlite3Fts3AllSegdirs(p, &pStmt);
100008   while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
100009     Fts3SegReader *pNew = 0;
100010     int nRoot = sqlite3_column_bytes(pStmt, 4);
100011     char const *zRoot = sqlite3_column_blob(pStmt, 4);
100012     if( sqlite3_column_int64(pStmt, 1)==0 ){
100013       /* The entire segment is stored on the root node (which must be a
100014       ** leaf). Do not bother inspecting any data in this case, just
100015       ** create a Fts3SegReader to scan the single leaf. 
100016       */
100017       rc = sqlite3Fts3SegReaderNew(p, iAge, 0, 0, 0, zRoot, nRoot, &pNew);
100018     }else{
100019       int rc2;                    /* Return value of sqlite3Fts3ReadBlock() */
100020       sqlite3_int64 i1;           /* Blockid of leaf that may contain zTerm */
100021       rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &i1);
100022       if( rc==SQLITE_OK ){
100023         sqlite3_int64 i2 = sqlite3_column_int64(pStmt, 2);
100024         rc = sqlite3Fts3SegReaderNew(p, iAge, i1, i2, 0, 0, 0, &pNew);
100025       }
100026
100027       /* The following call to ReadBlock() serves to reset the SQL statement
100028       ** used to retrieve blocks of data from the %_segments table. If it is
100029       ** not reset here, then it may remain classified as an active statement 
100030       ** by SQLite, which may lead to "DROP TABLE" or "DETACH" commands 
100031       ** failing.
100032       */ 
100033       rc2 = sqlite3Fts3ReadBlock(p, 0, 0, 0);
100034       if( rc==SQLITE_OK ){
100035         rc = rc2;
100036       }
100037     }
100038     iAge++;
100039
100040     /* If a new Fts3SegReader was allocated, add it to the apSegment array. */
100041     assert( pNew!=0 || rc!=SQLITE_OK );
100042     if( pNew ){
100043       if( nSegment==nAlloc ){
100044         Fts3SegReader **pArray;
100045         nAlloc += 16;
100046         pArray = (Fts3SegReader **)sqlite3_realloc(
100047             apSegment, nAlloc*sizeof(Fts3SegReader *)
100048         );
100049         if( !pArray ){
100050           sqlite3Fts3SegReaderFree(p, pNew);
100051           rc = SQLITE_NOMEM;
100052           goto finished;
100053         }
100054         apSegment = pArray;
100055       }
100056       apSegment[nSegment++] = pNew;
100057     }
100058   }
100059   if( rc!=SQLITE_DONE ){
100060     assert( rc!=SQLITE_OK );
100061     goto finished;
100062   }
100063
100064   memset(&tsc, 0, sizeof(TermSelect));
100065   tsc.isReqPos = isReqPos;
100066
100067   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY 
100068         | (isPrefix ? FTS3_SEGMENT_PREFIX : 0)
100069         | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
100070         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
100071   filter.iCol = iColumn;
100072   filter.zTerm = zTerm;
100073   filter.nTerm = nTerm;
100074
100075   rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment, &filter,
100076       fts3TermSelectCb, (void *)&tsc
100077   );
100078
100079   if( rc==SQLITE_OK ){
100080     *ppOut = tsc.aOutput;
100081     *pnOut = tsc.nOutput;
100082   }else{
100083     sqlite3_free(tsc.aOutput);
100084   }
100085
100086 finished:
100087   sqlite3_reset(pStmt);
100088   for(i=0; i<nSegment; i++){
100089     sqlite3Fts3SegReaderFree(p, apSegment[i]);
100090   }
100091   sqlite3_free(apSegment);
100092   return rc;
100093 }
100094
100095
100096 /* 
100097 ** Return a DocList corresponding to the phrase *pPhrase.
100098 */
100099 static int fts3PhraseSelect(
100100   Fts3Table *p,                   /* Virtual table handle */
100101   Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
100102   int isReqPos,                   /* True if output should contain positions */
100103   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
100104   int *pnOut                      /* OUT: Size of buffer at *paOut */
100105 ){
100106   char *pOut = 0;
100107   int nOut = 0;
100108   int rc = SQLITE_OK;
100109   int ii;
100110   int iCol = pPhrase->iColumn;
100111   int isTermPos = (pPhrase->nToken>1 || isReqPos);
100112
100113   for(ii=0; ii<pPhrase->nToken; ii++){
100114     struct PhraseToken *pTok = &pPhrase->aToken[ii];
100115     char *z = pTok->z;            /* Next token of the phrase */
100116     int n = pTok->n;              /* Size of z in bytes */
100117     int isPrefix = pTok->isPrefix;/* True if token is a prefix */
100118     char *pList;                  /* Pointer to token doclist */
100119     int nList;                    /* Size of buffer at pList */
100120
100121     rc = fts3TermSelect(p, iCol, z, n, isPrefix, isTermPos, &nList, &pList);
100122     if( rc!=SQLITE_OK ) break;
100123
100124     if( ii==0 ){
100125       pOut = pList;
100126       nOut = nList;
100127     }else{
100128       /* Merge the new term list and the current output. If this is the
100129       ** last term in the phrase, and positions are not required in the
100130       ** output of this function, the positions can be dropped as part
100131       ** of this merge. Either way, the result of this merge will be
100132       ** smaller than nList bytes. The code in fts3DoclistMerge() is written
100133       ** so that it is safe to use pList as the output as well as an input
100134       ** in this case.
100135       */
100136       int mergetype = MERGE_POS_PHRASE;
100137       if( ii==pPhrase->nToken-1 && !isReqPos ){
100138         mergetype = MERGE_PHRASE;
100139       }
100140       fts3DoclistMerge(mergetype, 0, 0, pList, &nOut, pOut, nOut, pList, nList);
100141       sqlite3_free(pOut);
100142       pOut = pList;
100143     }
100144     assert( nOut==0 || pOut!=0 );
100145   }
100146
100147   if( rc==SQLITE_OK ){
100148     *paOut = pOut;
100149     *pnOut = nOut;
100150   }else{
100151     sqlite3_free(pOut);
100152   }
100153   return rc;
100154 }
100155
100156 /*
100157 ** Evaluate the full-text expression pExpr against fts3 table pTab. Store
100158 ** the resulting doclist in *paOut and *pnOut.
100159 */
100160 static int evalFts3Expr(
100161   Fts3Table *p,                   /* Virtual table handle */
100162   Fts3Expr *pExpr,                /* Parsed fts3 expression */
100163   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
100164   int *pnOut,                     /* OUT: Size of buffer at *paOut */
100165   int isReqPos                    /* Require positions in output buffer */
100166 ){
100167   int rc = SQLITE_OK;             /* Return code */
100168
100169   /* Zero the output parameters. */
100170   *paOut = 0;
100171   *pnOut = 0;
100172
100173   if( pExpr ){
100174     assert( pExpr->eType==FTSQUERY_PHRASE 
100175          || pExpr->eType==FTSQUERY_NEAR 
100176          || isReqPos==0
100177     );
100178     if( pExpr->eType==FTSQUERY_PHRASE ){
100179       rc = fts3PhraseSelect(p, pExpr->pPhrase, 
100180           isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
100181           paOut, pnOut
100182       );
100183     }else{
100184       char *aLeft;
100185       char *aRight;
100186       int nLeft;
100187       int nRight;
100188
100189       if( 0==(rc = evalFts3Expr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
100190        && 0==(rc = evalFts3Expr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
100191       ){
100192         assert( pExpr->eType==FTSQUERY_NEAR || pExpr->eType==FTSQUERY_OR     
100193             || pExpr->eType==FTSQUERY_AND  || pExpr->eType==FTSQUERY_NOT
100194         );
100195         switch( pExpr->eType ){
100196           case FTSQUERY_NEAR: {
100197             Fts3Expr *pLeft;
100198             Fts3Expr *pRight;
100199             int mergetype = isReqPos ? MERGE_POS_NEAR : MERGE_NEAR;
100200             int nParam1;
100201             int nParam2;
100202             char *aBuffer;
100203            
100204             if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
100205               mergetype = MERGE_POS_NEAR;
100206             }
100207             pLeft = pExpr->pLeft;
100208             while( pLeft->eType==FTSQUERY_NEAR ){ 
100209               pLeft=pLeft->pRight;
100210             }
100211             pRight = pExpr->pRight;
100212             assert( pRight->eType==FTSQUERY_PHRASE );
100213             assert( pLeft->eType==FTSQUERY_PHRASE );
100214
100215             nParam1 = pExpr->nNear+1;
100216             nParam2 = nParam1+pLeft->pPhrase->nToken+pRight->pPhrase->nToken-2;
100217             aBuffer = sqlite3_malloc(nLeft+nRight+1);
100218             rc = fts3DoclistMerge(mergetype, nParam1, nParam2, aBuffer,
100219                 pnOut, aLeft, nLeft, aRight, nRight
100220             );
100221             if( rc!=SQLITE_OK ){
100222               sqlite3_free(aBuffer);
100223             }else{
100224               *paOut = aBuffer;
100225             }
100226             sqlite3_free(aLeft);
100227             break;
100228           }
100229
100230           case FTSQUERY_OR: {
100231             /* Allocate a buffer for the output. The maximum size is the
100232             ** sum of the sizes of the two input buffers. The +1 term is
100233             ** so that a buffer of zero bytes is never allocated - this can
100234             ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
100235             */
100236             char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
100237             rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
100238                 aLeft, nLeft, aRight, nRight
100239             );
100240             *paOut = aBuffer;
100241             sqlite3_free(aLeft);
100242             break;
100243           }
100244
100245           default: {
100246             assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
100247             fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
100248                 aLeft, nLeft, aRight, nRight
100249             );
100250             *paOut = aLeft;
100251             break;
100252           }
100253         }
100254       }
100255       sqlite3_free(aRight);
100256     }
100257   }
100258
100259   return rc;
100260 }
100261
100262 /*
100263 ** This is the xFilter interface for the virtual table.  See
100264 ** the virtual table xFilter method documentation for additional
100265 ** information.
100266 **
100267 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
100268 ** the %_content table.
100269 **
100270 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
100271 ** in the %_content table.
100272 **
100273 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
100274 ** column on the left-hand side of the MATCH operator is column
100275 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
100276 ** side of the MATCH operator.
100277 */
100278 /* TODO(shess) Upgrade the cursor initialization and destruction to
100279 ** account for fts3FilterMethod() being called multiple times on the
100280 ** same cursor. The current solution is very fragile. Apply fix to
100281 ** fts3 as appropriate.
100282 */
100283 static int fts3FilterMethod(
100284   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
100285   int idxNum,                     /* Strategy index */
100286   const char *idxStr,             /* Unused */
100287   int nVal,                       /* Number of elements in apVal */
100288   sqlite3_value **apVal           /* Arguments for the indexing scheme */
100289 ){
100290   const char *azSql[] = {
100291     "SELECT * FROM %Q.'%q_content' WHERE docid = ?", /* non-full-table-scan */
100292     "SELECT * FROM %Q.'%q_content'",                 /* full-table-scan */
100293   };
100294   int rc;                         /* Return code */
100295   char *zSql;                     /* SQL statement used to access %_content */
100296   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
100297   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
100298
100299   UNUSED_PARAMETER(idxStr);
100300   UNUSED_PARAMETER(nVal);
100301
100302   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
100303   assert( nVal==0 || nVal==1 );
100304   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
100305
100306   /* In case the cursor has been used before, clear it now. */
100307   sqlite3_finalize(pCsr->pStmt);
100308   sqlite3_free(pCsr->aDoclist);
100309   sqlite3Fts3ExprFree(pCsr->pExpr);
100310   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
100311
100312   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
100313   ** statement loops through all rows of the %_content table. For a
100314   ** full-text query or docid lookup, the statement retrieves a single
100315   ** row by docid.
100316   */
100317   zSql = sqlite3_mprintf(azSql[idxNum==FTS3_FULLSCAN_SEARCH], p->zDb, p->zName);
100318   if( !zSql ){
100319     rc = SQLITE_NOMEM;
100320   }else{
100321     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
100322     sqlite3_free(zSql);
100323   }
100324   if( rc!=SQLITE_OK ) return rc;
100325   pCsr->eSearch = (i16)idxNum;
100326
100327   if( idxNum==FTS3_DOCID_SEARCH ){
100328     rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
100329   }else if( idxNum!=FTS3_FULLSCAN_SEARCH ){
100330     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
100331     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
100332
100333     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
100334       return SQLITE_NOMEM;
100335     }
100336
100337     rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn, 
100338         iCol, zQuery, -1, &pCsr->pExpr
100339     );
100340     if( rc!=SQLITE_OK ) return rc;
100341
100342     rc = evalFts3Expr(p, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
100343     pCsr->pNextId = pCsr->aDoclist;
100344     pCsr->iPrevId = 0;
100345   }
100346
100347   if( rc!=SQLITE_OK ) return rc;
100348   return fts3NextMethod(pCursor);
100349 }
100350
100351 /* 
100352 ** This is the xEof method of the virtual table. SQLite calls this 
100353 ** routine to find out if it has reached the end of a result set.
100354 */
100355 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
100356   return ((Fts3Cursor *)pCursor)->isEof;
100357 }
100358
100359 /* 
100360 ** This is the xRowid method. The SQLite core calls this routine to
100361 ** retrieve the rowid for the current row of the result set. fts3
100362 ** exposes %_content.docid as the rowid for the virtual table. The
100363 ** rowid should be written to *pRowid.
100364 */
100365 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
100366   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
100367   if( pCsr->aDoclist ){
100368     *pRowid = pCsr->iPrevId;
100369   }else{
100370     *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
100371   }
100372   return SQLITE_OK;
100373 }
100374
100375 /* 
100376 ** This is the xColumn method, called by SQLite to request a value from
100377 ** the row that the supplied cursor currently points to.
100378 */
100379 static int fts3ColumnMethod(
100380   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
100381   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
100382   int iCol                        /* Index of column to read value from */
100383 ){
100384   int rc;                         /* Return Code */
100385   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
100386   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
100387
100388   /* The column value supplied by SQLite must be in range. */
100389   assert( iCol>=0 && iCol<=p->nColumn+1 );
100390
100391   if( iCol==p->nColumn+1 ){
100392     /* This call is a request for the "docid" column. Since "docid" is an 
100393     ** alias for "rowid", use the xRowid() method to obtain the value.
100394     */
100395     sqlite3_int64 iRowid;
100396     rc = fts3RowidMethod(pCursor, &iRowid);
100397     sqlite3_result_int64(pContext, iRowid);
100398   }else if( iCol==p->nColumn ){
100399     /* The extra column whose name is the same as the table.
100400     ** Return a blob which is a pointer to the cursor.
100401     */
100402     sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
100403     rc = SQLITE_OK;
100404   }else{
100405     rc = fts3CursorSeek(0, pCsr);
100406     if( rc==SQLITE_OK ){
100407       sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
100408     }
100409   }
100410   return rc;
100411 }
100412
100413 /* 
100414 ** This function is the implementation of the xUpdate callback used by 
100415 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
100416 ** inserted, updated or deleted.
100417 */
100418 static int fts3UpdateMethod(
100419   sqlite3_vtab *pVtab,            /* Virtual table handle */
100420   int nArg,                       /* Size of argument array */
100421   sqlite3_value **apVal,          /* Array of arguments */
100422   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
100423 ){
100424   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
100425 }
100426
100427 /*
100428 ** Implementation of xSync() method. Flush the contents of the pending-terms
100429 ** hash-table to the database.
100430 */
100431 static int fts3SyncMethod(sqlite3_vtab *pVtab){
100432   return sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
100433 }
100434
100435 /*
100436 ** Implementation of xBegin() method. This is a no-op.
100437 */
100438 static int fts3BeginMethod(sqlite3_vtab *pVtab){
100439   UNUSED_PARAMETER(pVtab);
100440   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
100441   return SQLITE_OK;
100442 }
100443
100444 /*
100445 ** Implementation of xCommit() method. This is a no-op. The contents of
100446 ** the pending-terms hash-table have already been flushed into the database
100447 ** by fts3SyncMethod().
100448 */
100449 static int fts3CommitMethod(sqlite3_vtab *pVtab){
100450   UNUSED_PARAMETER(pVtab);
100451   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
100452   return SQLITE_OK;
100453 }
100454
100455 /*
100456 ** Implementation of xRollback(). Discard the contents of the pending-terms
100457 ** hash-table. Any changes made to the database are reverted by SQLite.
100458 */
100459 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
100460   sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
100461   return SQLITE_OK;
100462 }
100463
100464 /*
100465 ** Load the doclist associated with expression pExpr to pExpr->aDoclist.
100466 ** The loaded doclist contains positions as well as the document ids.
100467 ** This is used by the matchinfo(), snippet() and offsets() auxillary
100468 ** functions.
100469 */
100470 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *pTab, Fts3Expr *pExpr){
100471   return evalFts3Expr(pTab, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
100472 }
100473
100474 /*
100475 ** After ExprLoadDoclist() (see above) has been called, this function is
100476 ** used to iterate through the position lists that make up the doclist
100477 ** stored in pExpr->aDoclist.
100478 */
100479 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
100480   Fts3Expr *pExpr,                /* Access this expressions doclist */
100481   sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
100482   int iCol                        /* Column of requested pos-list */
100483 ){
100484   assert( pExpr->isLoaded );
100485   if( pExpr->aDoclist ){
100486     char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
100487     char *pCsr = pExpr->pCurrent;
100488
100489     assert( pCsr );
100490     while( pCsr<pEnd ){
100491       if( pExpr->iCurrent<iDocid ){
100492         fts3PoslistCopy(0, &pCsr);
100493         fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
100494         pExpr->pCurrent = pCsr;
100495       }else{
100496         if( pExpr->iCurrent==iDocid ){
100497           int iThis = 0;
100498           if( iCol<0 ){
100499             /* If iCol is negative, return a pointer to the start of the
100500             ** position-list (instead of a pointer to the start of a list
100501             ** of offsets associated with a specific column).
100502             */
100503             return pCsr;
100504           }
100505           while( iThis<iCol ){
100506             fts3ColumnlistCopy(0, &pCsr);
100507             if( *pCsr==0x00 ) return 0;
100508             pCsr++;
100509             pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
100510           }
100511           if( iCol==iThis ) return pCsr;
100512         }
100513         return 0;
100514       }
100515     }
100516   }
100517
100518   return 0;
100519 }
100520
100521 /*
100522 ** Helper function used by the implementation of the overloaded snippet(),
100523 ** offsets() and optimize() SQL functions.
100524 **
100525 ** If the value passed as the third argument is a blob of size
100526 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
100527 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
100528 ** message is written to context pContext and SQLITE_ERROR returned. The
100529 ** string passed via zFunc is used as part of the error message.
100530 */
100531 static int fts3FunctionArg(
100532   sqlite3_context *pContext,      /* SQL function call context */
100533   const char *zFunc,              /* Function name */
100534   sqlite3_value *pVal,            /* argv[0] passed to function */
100535   Fts3Cursor **ppCsr         /* OUT: Store cursor handle here */
100536 ){
100537   Fts3Cursor *pRet;
100538   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
100539    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
100540   ){
100541     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
100542     sqlite3_result_error(pContext, zErr, -1);
100543     sqlite3_free(zErr);
100544     return SQLITE_ERROR;
100545   }
100546   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
100547   *ppCsr = pRet;
100548   return SQLITE_OK;
100549 }
100550
100551 /*
100552 ** Implementation of the snippet() function for FTS3
100553 */
100554 static void fts3SnippetFunc(
100555   sqlite3_context *pContext,      /* SQLite function call context */
100556   int nVal,                       /* Size of apVal[] array */
100557   sqlite3_value **apVal           /* Array of arguments */
100558 ){
100559   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100560   const char *zStart = "<b>";
100561   const char *zEnd = "</b>";
100562   const char *zEllipsis = "<b>...</b>";
100563
100564   /* There must be at least one argument passed to this function (otherwise
100565   ** the non-overloaded version would have been called instead of this one).
100566   */
100567   assert( nVal>=1 );
100568
100569   if( nVal>4 ){
100570     sqlite3_result_error(pContext, 
100571         "wrong number of arguments to function snippet()", -1);
100572     return;
100573   }
100574   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
100575
100576   switch( nVal ){
100577     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
100578     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
100579     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
100580   }
100581   if( !zEllipsis || !zEnd || !zStart ){
100582     sqlite3_result_error_nomem(pContext);
100583   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
100584     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis);
100585   }
100586 }
100587
100588 /*
100589 ** Implementation of the snippet2() function for FTS3
100590 */
100591 static void fts3Snippet2Func(
100592   sqlite3_context *pContext,      /* SQLite function call context */
100593   int nVal,                       /* Size of apVal[] array */
100594   sqlite3_value **apVal           /* Array of arguments */
100595 ){
100596   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100597   const char *zStart = "<b>";
100598   const char *zEnd = "</b>";
100599   const char *zEllipsis = "<b>...</b>";
100600   int iCol = -1;
100601   int nToken = 10;
100602
100603   /* There must be at least one argument passed to this function (otherwise
100604   ** the non-overloaded version would have been called instead of this one).
100605   */
100606   assert( nVal>=1 );
100607
100608   if( nVal>6 ){
100609     sqlite3_result_error(pContext, 
100610         "wrong number of arguments to function snippet()", -1);
100611     return;
100612   }
100613   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
100614
100615   switch( nVal ){
100616     case 6: nToken = sqlite3_value_int(apVal[5]);
100617     case 5: iCol = sqlite3_value_int(apVal[4]);
100618     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
100619     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
100620     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
100621   }
100622   if( !zEllipsis || !zEnd || !zStart ){
100623     sqlite3_result_error_nomem(pContext);
100624   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
100625     sqlite3Fts3Snippet2(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
100626   }
100627 }
100628
100629 /*
100630 ** Implementation of the offsets() function for FTS3
100631 */
100632 static void fts3OffsetsFunc(
100633   sqlite3_context *pContext,      /* SQLite function call context */
100634   int nVal,                       /* Size of argument array */
100635   sqlite3_value **apVal           /* Array of arguments */
100636 ){
100637   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100638
100639   UNUSED_PARAMETER(nVal);
100640
100641   assert( nVal==1 );
100642   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
100643   assert( pCsr );
100644   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
100645     sqlite3Fts3Offsets(pContext, pCsr);
100646   }
100647 }
100648
100649 /* 
100650 ** Implementation of the special optimize() function for FTS3. This 
100651 ** function merges all segments in the database to a single segment.
100652 ** Example usage is:
100653 **
100654 **   SELECT optimize(t) FROM t LIMIT 1;
100655 **
100656 ** where 't' is the name of an FTS3 table.
100657 */
100658 static void fts3OptimizeFunc(
100659   sqlite3_context *pContext,      /* SQLite function call context */
100660   int nVal,                       /* Size of argument array */
100661   sqlite3_value **apVal           /* Array of arguments */
100662 ){
100663   int rc;                         /* Return code */
100664   Fts3Table *p;                   /* Virtual table handle */
100665   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
100666
100667   UNUSED_PARAMETER(nVal);
100668
100669   assert( nVal==1 );
100670   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
100671   p = (Fts3Table *)pCursor->base.pVtab;
100672   assert( p );
100673
100674   rc = sqlite3Fts3Optimize(p);
100675
100676   switch( rc ){
100677     case SQLITE_OK:
100678       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
100679       break;
100680     case SQLITE_DONE:
100681       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
100682       break;
100683     default:
100684       sqlite3_result_error_code(pContext, rc);
100685       break;
100686   }
100687 }
100688
100689 /*
100690 ** Implementation of the matchinfo() function for FTS3
100691 */
100692 static void fts3MatchinfoFunc(
100693   sqlite3_context *pContext,      /* SQLite function call context */
100694   int nVal,                       /* Size of argument array */
100695   sqlite3_value **apVal           /* Array of arguments */
100696 ){
100697   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100698
100699   if( nVal!=1 ){
100700     sqlite3_result_error(pContext,
100701         "wrong number of arguments to function matchinfo()", -1);
100702     return;
100703   }
100704
100705   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
100706     sqlite3Fts3Matchinfo(pContext, pCsr);
100707   }
100708 }
100709
100710 /*
100711 ** This routine implements the xFindFunction method for the FTS3
100712 ** virtual table.
100713 */
100714 static int fts3FindFunctionMethod(
100715   sqlite3_vtab *pVtab,            /* Virtual table handle */
100716   int nArg,                       /* Number of SQL function arguments */
100717   const char *zName,              /* Name of SQL function */
100718   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
100719   void **ppArg                    /* Unused */
100720 ){
100721   struct Overloaded {
100722     const char *zName;
100723     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
100724   } aOverload[] = {
100725     { "snippet", fts3SnippetFunc },
100726     { "snippet2", fts3Snippet2Func },
100727     { "offsets", fts3OffsetsFunc },
100728     { "optimize", fts3OptimizeFunc },
100729     { "matchinfo", fts3MatchinfoFunc },
100730   };
100731   int i;                          /* Iterator variable */
100732
100733   UNUSED_PARAMETER(pVtab);
100734   UNUSED_PARAMETER(nArg);
100735   UNUSED_PARAMETER(ppArg);
100736
100737   for(i=0; i<SizeofArray(aOverload); i++){
100738     if( strcmp(zName, aOverload[i].zName)==0 ){
100739       *pxFunc = aOverload[i].xFunc;
100740       return 1;
100741     }
100742   }
100743
100744   /* No function of the specified name was found. Return 0. */
100745   return 0;
100746 }
100747
100748 /*
100749 ** Implementation of FTS3 xRename method. Rename an fts3 table.
100750 */
100751 static int fts3RenameMethod(
100752   sqlite3_vtab *pVtab,            /* Virtual table handle */
100753   const char *zName               /* New name of table */
100754 ){
100755   Fts3Table *p = (Fts3Table *)pVtab;     
100756   int rc = SQLITE_NOMEM;          /* Return Code */
100757   char *zSql;                     /* SQL script to run to rename tables */
100758  
100759   zSql = sqlite3_mprintf(
100760     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
100761     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
100762     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
100763     , p->zDb, p->zName, zName 
100764     , p->zDb, p->zName, zName 
100765     , p->zDb, p->zName, zName
100766   );
100767   if( zSql ){
100768     rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
100769     sqlite3_free(zSql);
100770   }
100771   return rc;
100772 }
100773
100774 static const sqlite3_module fts3Module = {
100775   /* iVersion      */ 0,
100776   /* xCreate       */ fts3CreateMethod,
100777   /* xConnect      */ fts3ConnectMethod,
100778   /* xBestIndex    */ fts3BestIndexMethod,
100779   /* xDisconnect   */ fts3DisconnectMethod,
100780   /* xDestroy      */ fts3DestroyMethod,
100781   /* xOpen         */ fts3OpenMethod,
100782   /* xClose        */ fulltextClose,
100783   /* xFilter       */ fts3FilterMethod,
100784   /* xNext         */ fts3NextMethod,
100785   /* xEof          */ fts3EofMethod,
100786   /* xColumn       */ fts3ColumnMethod,
100787   /* xRowid        */ fts3RowidMethod,
100788   /* xUpdate       */ fts3UpdateMethod,
100789   /* xBegin        */ fts3BeginMethod,
100790   /* xSync         */ fts3SyncMethod,
100791   /* xCommit       */ fts3CommitMethod,
100792   /* xRollback     */ fts3RollbackMethod,
100793   /* xFindFunction */ fts3FindFunctionMethod,
100794   /* xRename */       fts3RenameMethod,
100795 };
100796
100797 /*
100798 ** This function is registered as the module destructor (called when an
100799 ** FTS3 enabled database connection is closed). It frees the memory
100800 ** allocated for the tokenizer hash table.
100801 */
100802 static void hashDestroy(void *p){
100803   Fts3Hash *pHash = (Fts3Hash *)p;
100804   sqlite3Fts3HashClear(pHash);
100805   sqlite3_free(pHash);
100806 }
100807
100808 /*
100809 ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
100810 ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
100811 ** two forward declarations are for functions declared in these files
100812 ** used to retrieve the respective implementations.
100813 **
100814 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
100815 ** to by the argument to point a the "simple" tokenizer implementation.
100816 ** Function ...PorterTokenizerModule() sets *pModule to point to the
100817 ** porter tokenizer/stemmer implementation.
100818 */
100819 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
100820 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
100821 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
100822
100823 /*
100824 ** Initialise the fts3 extension. If this extension is built as part
100825 ** of the sqlite library, then this function is called directly by
100826 ** SQLite. If fts3 is built as a dynamically loadable extension, this
100827 ** function is called by the sqlite3_extension_init() entry point.
100828 */
100829 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
100830   int rc = SQLITE_OK;
100831   Fts3Hash *pHash = 0;
100832   const sqlite3_tokenizer_module *pSimple = 0;
100833   const sqlite3_tokenizer_module *pPorter = 0;
100834
100835 #ifdef SQLITE_ENABLE_ICU
100836   const sqlite3_tokenizer_module *pIcu = 0;
100837   sqlite3Fts3IcuTokenizerModule(&pIcu);
100838 #endif
100839
100840   sqlite3Fts3SimpleTokenizerModule(&pSimple);
100841   sqlite3Fts3PorterTokenizerModule(&pPorter);
100842
100843   /* Allocate and initialise the hash-table used to store tokenizers. */
100844   pHash = sqlite3_malloc(sizeof(Fts3Hash));
100845   if( !pHash ){
100846     rc = SQLITE_NOMEM;
100847   }else{
100848     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
100849   }
100850
100851   /* Load the built-in tokenizers into the hash table */
100852   if( rc==SQLITE_OK ){
100853     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
100854      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
100855 #ifdef SQLITE_ENABLE_ICU
100856      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
100857 #endif
100858     ){
100859       rc = SQLITE_NOMEM;
100860     }
100861   }
100862
100863 #ifdef SQLITE_TEST
100864   if( rc==SQLITE_OK ){
100865     rc = sqlite3Fts3ExprInitTestInterface(db);
100866   }
100867 #endif
100868
100869   /* Create the virtual table wrapper around the hash-table and overload 
100870   ** the two scalar functions. If this is successful, register the
100871   ** module with sqlite.
100872   */
100873   if( SQLITE_OK==rc 
100874    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
100875    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
100876    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet2", -1))
100877    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
100878    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", -1))
100879    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
100880   ){
100881     return sqlite3_create_module_v2(
100882         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
100883     );
100884   }
100885
100886   /* An error has occurred. Delete the hash table and return the error code. */
100887   assert( rc!=SQLITE_OK );
100888   if( pHash ){
100889     sqlite3Fts3HashClear(pHash);
100890     sqlite3_free(pHash);
100891   }
100892   return rc;
100893 }
100894
100895 #if !SQLITE_CORE
100896 SQLITE_API int sqlite3_extension_init(
100897   sqlite3 *db, 
100898   char **pzErrMsg,
100899   const sqlite3_api_routines *pApi
100900 ){
100901   SQLITE_EXTENSION_INIT2(pApi)
100902   return sqlite3Fts3Init(db);
100903 }
100904 #endif
100905
100906 #endif
100907
100908 /************** End of fts3.c ************************************************/
100909 /************** Begin file fts3_expr.c ***************************************/
100910 /*
100911 ** 2008 Nov 28
100912 **
100913 ** The author disclaims copyright to this source code.  In place of
100914 ** a legal notice, here is a blessing:
100915 **
100916 **    May you do good and not evil.
100917 **    May you find forgiveness for yourself and forgive others.
100918 **    May you share freely, never taking more than you give.
100919 **
100920 ******************************************************************************
100921 **
100922 ** This module contains code that implements a parser for fts3 query strings
100923 ** (the right-hand argument to the MATCH operator). Because the supported 
100924 ** syntax is relatively simple, the whole tokenizer/parser system is
100925 ** hand-coded. 
100926 */
100927 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
100928
100929 /*
100930 ** By default, this module parses the legacy syntax that has been 
100931 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
100932 ** is defined, then it uses the new syntax. The differences between
100933 ** the new and the old syntaxes are:
100934 **
100935 **  a) The new syntax supports parenthesis. The old does not.
100936 **
100937 **  b) The new syntax supports the AND and NOT operators. The old does not.
100938 **
100939 **  c) The old syntax supports the "-" token qualifier. This is not 
100940 **     supported by the new syntax (it is replaced by the NOT operator).
100941 **
100942 **  d) When using the old syntax, the OR operator has a greater precedence
100943 **     than an implicit AND. When using the new, both implicity and explicit
100944 **     AND operators have a higher precedence than OR.
100945 **
100946 ** If compiled with SQLITE_TEST defined, then this module exports the
100947 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
100948 ** to zero causes the module to use the old syntax. If it is set to 
100949 ** non-zero the new syntax is activated. This is so both syntaxes can
100950 ** be tested using a single build of testfixture.
100951 **
100952 ** The following describes the syntax supported by the fts3 MATCH
100953 ** operator in a similar format to that used by the lemon parser
100954 ** generator. This module does not use actually lemon, it uses a
100955 ** custom parser.
100956 **
100957 **   query ::= andexpr (OR andexpr)*.
100958 **
100959 **   andexpr ::= notexpr (AND? notexpr)*.
100960 **
100961 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
100962 **   notexpr ::= LP query RP.
100963 **
100964 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
100965 **
100966 **   distance_opt ::= .
100967 **   distance_opt ::= / INTEGER.
100968 **
100969 **   phrase ::= TOKEN.
100970 **   phrase ::= COLUMN:TOKEN.
100971 **   phrase ::= "TOKEN TOKEN TOKEN...".
100972 */
100973
100974 #ifdef SQLITE_TEST
100975 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
100976 #else
100977 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
100978 #  define sqlite3_fts3_enable_parentheses 1
100979 # else
100980 #  define sqlite3_fts3_enable_parentheses 0
100981 # endif
100982 #endif
100983
100984 /*
100985 ** Default span for NEAR operators.
100986 */
100987 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
100988
100989
100990 typedef struct ParseContext ParseContext;
100991 struct ParseContext {
100992   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
100993   const char **azCol;                 /* Array of column names for fts3 table */
100994   int nCol;                           /* Number of entries in azCol[] */
100995   int iDefaultCol;                    /* Default column to query */
100996   sqlite3_context *pCtx;              /* Write error message here */
100997   int nNest;                          /* Number of nested brackets */
100998 };
100999
101000 /*
101001 ** This function is equivalent to the standard isspace() function. 
101002 **
101003 ** The standard isspace() can be awkward to use safely, because although it
101004 ** is defined to accept an argument of type int, its behaviour when passed
101005 ** an integer that falls outside of the range of the unsigned char type
101006 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
101007 ** is defined to accept an argument of type char, and always returns 0 for
101008 ** any values that fall outside of the range of the unsigned char type (i.e.
101009 ** negative values).
101010 */
101011 static int fts3isspace(char c){
101012   return (c&0x80)==0 ? isspace(c) : 0;
101013 }
101014
101015 /*
101016 ** Extract the next token from buffer z (length n) using the tokenizer
101017 ** and other information (column names etc.) in pParse. Create an Fts3Expr
101018 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
101019 ** single token and set *ppExpr to point to it. If the end of the buffer is
101020 ** reached before a token is found, set *ppExpr to zero. It is the
101021 ** responsibility of the caller to eventually deallocate the allocated 
101022 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
101023 **
101024 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
101025 ** fails.
101026 */
101027 static int getNextToken(
101028   ParseContext *pParse,                   /* fts3 query parse context */
101029   int iCol,                               /* Value for Fts3Phrase.iColumn */
101030   const char *z, int n,                   /* Input string */
101031   Fts3Expr **ppExpr,                      /* OUT: expression */
101032   int *pnConsumed                         /* OUT: Number of bytes consumed */
101033 ){
101034   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
101035   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
101036   int rc;
101037   sqlite3_tokenizer_cursor *pCursor;
101038   Fts3Expr *pRet = 0;
101039   int nConsumed = 0;
101040
101041   rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
101042   if( rc==SQLITE_OK ){
101043     const char *zToken;
101044     int nToken, iStart, iEnd, iPosition;
101045     int nByte;                               /* total space to allocate */
101046
101047     pCursor->pTokenizer = pTokenizer;
101048     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
101049
101050     if( rc==SQLITE_OK ){
101051       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
101052       pRet = (Fts3Expr *)sqlite3_malloc(nByte);
101053       if( !pRet ){
101054         rc = SQLITE_NOMEM;
101055       }else{
101056         memset(pRet, 0, nByte);
101057         pRet->eType = FTSQUERY_PHRASE;
101058         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
101059         pRet->pPhrase->nToken = 1;
101060         pRet->pPhrase->iColumn = iCol;
101061         pRet->pPhrase->aToken[0].n = nToken;
101062         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
101063         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
101064
101065         if( iEnd<n && z[iEnd]=='*' ){
101066           pRet->pPhrase->aToken[0].isPrefix = 1;
101067           iEnd++;
101068         }
101069         if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
101070           pRet->pPhrase->isNot = 1;
101071         }
101072       }
101073       nConsumed = iEnd;
101074     }
101075
101076     pModule->xClose(pCursor);
101077   }
101078   
101079   *pnConsumed = nConsumed;
101080   *ppExpr = pRet;
101081   return rc;
101082 }
101083
101084
101085 /*
101086 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
101087 ** then free the old allocation.
101088 */
101089 static void *fts3ReallocOrFree(void *pOrig, int nNew){
101090   void *pRet = sqlite3_realloc(pOrig, nNew);
101091   if( !pRet ){
101092     sqlite3_free(pOrig);
101093   }
101094   return pRet;
101095 }
101096
101097 /*
101098 ** Buffer zInput, length nInput, contains the contents of a quoted string
101099 ** that appeared as part of an fts3 query expression. Neither quote character
101100 ** is included in the buffer. This function attempts to tokenize the entire
101101 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
101102 ** containing the results.
101103 **
101104 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
101105 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
101106 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
101107 ** to 0.
101108 */
101109 static int getNextString(
101110   ParseContext *pParse,                   /* fts3 query parse context */
101111   const char *zInput, int nInput,         /* Input string */
101112   Fts3Expr **ppExpr                       /* OUT: expression */
101113 ){
101114   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
101115   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
101116   int rc;
101117   Fts3Expr *p = 0;
101118   sqlite3_tokenizer_cursor *pCursor = 0;
101119   char *zTemp = 0;
101120   int nTemp = 0;
101121
101122   rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
101123   if( rc==SQLITE_OK ){
101124     int ii;
101125     pCursor->pTokenizer = pTokenizer;
101126     for(ii=0; rc==SQLITE_OK; ii++){
101127       const char *zToken;
101128       int nToken, iBegin, iEnd, iPos;
101129       rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
101130       if( rc==SQLITE_OK ){
101131         int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
101132         p = fts3ReallocOrFree(p, nByte+ii*sizeof(struct PhraseToken));
101133         zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
101134         if( !p || !zTemp ){
101135           goto no_mem;
101136         }
101137         if( ii==0 ){
101138           memset(p, 0, nByte);
101139           p->pPhrase = (Fts3Phrase *)&p[1];
101140         }
101141         p->pPhrase = (Fts3Phrase *)&p[1];
101142         p->pPhrase->nToken = ii+1;
101143         p->pPhrase->aToken[ii].n = nToken;
101144         memcpy(&zTemp[nTemp], zToken, nToken);
101145         nTemp += nToken;
101146         if( iEnd<nInput && zInput[iEnd]=='*' ){
101147           p->pPhrase->aToken[ii].isPrefix = 1;
101148         }else{
101149           p->pPhrase->aToken[ii].isPrefix = 0;
101150         }
101151       }
101152     }
101153
101154     pModule->xClose(pCursor);
101155     pCursor = 0;
101156   }
101157
101158   if( rc==SQLITE_DONE ){
101159     int jj;
101160     char *zNew = NULL;
101161     int nNew = 0;
101162     int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
101163     nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(struct PhraseToken);
101164     p = fts3ReallocOrFree(p, nByte + nTemp);
101165     if( !p ){
101166       goto no_mem;
101167     }
101168     if( zTemp ){
101169       zNew = &(((char *)p)[nByte]);
101170       memcpy(zNew, zTemp, nTemp);
101171     }else{
101172       memset(p, 0, nByte+nTemp);
101173     }
101174     p->pPhrase = (Fts3Phrase *)&p[1];
101175     for(jj=0; jj<p->pPhrase->nToken; jj++){
101176       p->pPhrase->aToken[jj].z = &zNew[nNew];
101177       nNew += p->pPhrase->aToken[jj].n;
101178     }
101179     sqlite3_free(zTemp);
101180     p->eType = FTSQUERY_PHRASE;
101181     p->pPhrase->iColumn = pParse->iDefaultCol;
101182     rc = SQLITE_OK;
101183   }
101184
101185   *ppExpr = p;
101186   return rc;
101187 no_mem:
101188
101189   if( pCursor ){
101190     pModule->xClose(pCursor);
101191   }
101192   sqlite3_free(zTemp);
101193   sqlite3_free(p);
101194   *ppExpr = 0;
101195   return SQLITE_NOMEM;
101196 }
101197
101198 /*
101199 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
101200 ** call fts3ExprParse(). So this forward declaration is required.
101201 */
101202 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
101203
101204 /*
101205 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
101206 ** structure, or set to 0 if the end of the input buffer is reached.
101207 **
101208 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
101209 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
101210 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
101211 */
101212 static int getNextNode(
101213   ParseContext *pParse,                   /* fts3 query parse context */
101214   const char *z, int n,                   /* Input string */
101215   Fts3Expr **ppExpr,                      /* OUT: expression */
101216   int *pnConsumed                         /* OUT: Number of bytes consumed */
101217 ){
101218   static const struct Fts3Keyword {
101219     char *z;                              /* Keyword text */
101220     unsigned char n;                      /* Length of the keyword */
101221     unsigned char parenOnly;              /* Only valid in paren mode */
101222     unsigned char eType;                  /* Keyword code */
101223   } aKeyword[] = {
101224     { "OR" ,  2, 0, FTSQUERY_OR   },
101225     { "AND",  3, 1, FTSQUERY_AND  },
101226     { "NOT",  3, 1, FTSQUERY_NOT  },
101227     { "NEAR", 4, 0, FTSQUERY_NEAR }
101228   };
101229   int ii;
101230   int iCol;
101231   int iColLen;
101232   int rc;
101233   Fts3Expr *pRet = 0;
101234
101235   const char *zInput = z;
101236   int nInput = n;
101237
101238   /* Skip over any whitespace before checking for a keyword, an open or
101239   ** close bracket, or a quoted string. 
101240   */
101241   while( nInput>0 && fts3isspace(*zInput) ){
101242     nInput--;
101243     zInput++;
101244   }
101245   if( nInput==0 ){
101246     return SQLITE_DONE;
101247   }
101248
101249   /* See if we are dealing with a keyword. */
101250   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
101251     const struct Fts3Keyword *pKey = &aKeyword[ii];
101252
101253     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
101254       continue;
101255     }
101256
101257     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
101258       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
101259       int nKey = pKey->n;
101260       char cNext;
101261
101262       /* If this is a "NEAR" keyword, check for an explicit nearness. */
101263       if( pKey->eType==FTSQUERY_NEAR ){
101264         assert( nKey==4 );
101265         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
101266           nNear = 0;
101267           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
101268             nNear = nNear * 10 + (zInput[nKey] - '0');
101269           }
101270         }
101271       }
101272
101273       /* At this point this is probably a keyword. But for that to be true,
101274       ** the next byte must contain either whitespace, an open or close
101275       ** parenthesis, a quote character, or EOF. 
101276       */
101277       cNext = zInput[nKey];
101278       if( fts3isspace(cNext) 
101279        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
101280       ){
101281         pRet = (Fts3Expr *)sqlite3_malloc(sizeof(Fts3Expr));
101282         if( !pRet ){
101283           return SQLITE_NOMEM;
101284         }
101285         memset(pRet, 0, sizeof(Fts3Expr));
101286         pRet->eType = pKey->eType;
101287         pRet->nNear = nNear;
101288         *ppExpr = pRet;
101289         *pnConsumed = (int)((zInput - z) + nKey);
101290         return SQLITE_OK;
101291       }
101292
101293       /* Turns out that wasn't a keyword after all. This happens if the
101294       ** user has supplied a token such as "ORacle". Continue.
101295       */
101296     }
101297   }
101298
101299   /* Check for an open bracket. */
101300   if( sqlite3_fts3_enable_parentheses ){
101301     if( *zInput=='(' ){
101302       int nConsumed;
101303       int rc;
101304       pParse->nNest++;
101305       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
101306       if( rc==SQLITE_OK && !*ppExpr ){
101307         rc = SQLITE_DONE;
101308       }
101309       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
101310       return rc;
101311     }
101312   
101313     /* Check for a close bracket. */
101314     if( *zInput==')' ){
101315       pParse->nNest--;
101316       *pnConsumed = (int)((zInput - z) + 1);
101317       return SQLITE_DONE;
101318     }
101319   }
101320
101321   /* See if we are dealing with a quoted phrase. If this is the case, then
101322   ** search for the closing quote and pass the whole string to getNextString()
101323   ** for processing. This is easy to do, as fts3 has no syntax for escaping
101324   ** a quote character embedded in a string.
101325   */
101326   if( *zInput=='"' ){
101327     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
101328     *pnConsumed = (int)((zInput - z) + ii + 1);
101329     if( ii==nInput ){
101330       return SQLITE_ERROR;
101331     }
101332     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
101333   }
101334
101335
101336   /* If control flows to this point, this must be a regular token, or 
101337   ** the end of the input. Read a regular token using the sqlite3_tokenizer
101338   ** interface. Before doing so, figure out if there is an explicit
101339   ** column specifier for the token. 
101340   **
101341   ** TODO: Strangely, it is not possible to associate a column specifier
101342   ** with a quoted phrase, only with a single token. Not sure if this was
101343   ** an implementation artifact or an intentional decision when fts3 was
101344   ** first implemented. Whichever it was, this module duplicates the 
101345   ** limitation.
101346   */
101347   iCol = pParse->iDefaultCol;
101348   iColLen = 0;
101349   for(ii=0; ii<pParse->nCol; ii++){
101350     const char *zStr = pParse->azCol[ii];
101351     int nStr = (int)strlen(zStr);
101352     if( nInput>nStr && zInput[nStr]==':' 
101353      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
101354     ){
101355       iCol = ii;
101356       iColLen = (int)((zInput - z) + nStr + 1);
101357       break;
101358     }
101359   }
101360   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
101361   *pnConsumed += iColLen;
101362   return rc;
101363 }
101364
101365 /*
101366 ** The argument is an Fts3Expr structure for a binary operator (any type
101367 ** except an FTSQUERY_PHRASE). Return an integer value representing the
101368 ** precedence of the operator. Lower values have a higher precedence (i.e.
101369 ** group more tightly). For example, in the C language, the == operator
101370 ** groups more tightly than ||, and would therefore have a higher precedence.
101371 **
101372 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
101373 ** is defined), the order of the operators in precedence from highest to
101374 ** lowest is:
101375 **
101376 **   NEAR
101377 **   NOT
101378 **   AND (including implicit ANDs)
101379 **   OR
101380 **
101381 ** Note that when using the old query syntax, the OR operator has a higher
101382 ** precedence than the AND operator.
101383 */
101384 static int opPrecedence(Fts3Expr *p){
101385   assert( p->eType!=FTSQUERY_PHRASE );
101386   if( sqlite3_fts3_enable_parentheses ){
101387     return p->eType;
101388   }else if( p->eType==FTSQUERY_NEAR ){
101389     return 1;
101390   }else if( p->eType==FTSQUERY_OR ){
101391     return 2;
101392   }
101393   assert( p->eType==FTSQUERY_AND );
101394   return 3;
101395 }
101396
101397 /*
101398 ** Argument ppHead contains a pointer to the current head of a query 
101399 ** expression tree being parsed. pPrev is the expression node most recently
101400 ** inserted into the tree. This function adds pNew, which is always a binary
101401 ** operator node, into the expression tree based on the relative precedence
101402 ** of pNew and the existing nodes of the tree. This may result in the head
101403 ** of the tree changing, in which case *ppHead is set to the new root node.
101404 */
101405 static void insertBinaryOperator(
101406   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
101407   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
101408   Fts3Expr *pNew           /* New binary node to insert into expression tree */
101409 ){
101410   Fts3Expr *pSplit = pPrev;
101411   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
101412     pSplit = pSplit->pParent;
101413   }
101414
101415   if( pSplit->pParent ){
101416     assert( pSplit->pParent->pRight==pSplit );
101417     pSplit->pParent->pRight = pNew;
101418     pNew->pParent = pSplit->pParent;
101419   }else{
101420     *ppHead = pNew;
101421   }
101422   pNew->pLeft = pSplit;
101423   pSplit->pParent = pNew;
101424 }
101425
101426 /*
101427 ** Parse the fts3 query expression found in buffer z, length n. This function
101428 ** returns either when the end of the buffer is reached or an unmatched 
101429 ** closing bracket - ')' - is encountered.
101430 **
101431 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
101432 ** parsed form of the expression and *pnConsumed is set to the number of
101433 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
101434 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
101435 */
101436 static int fts3ExprParse(
101437   ParseContext *pParse,                   /* fts3 query parse context */
101438   const char *z, int n,                   /* Text of MATCH query */
101439   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
101440   int *pnConsumed                         /* OUT: Number of bytes consumed */
101441 ){
101442   Fts3Expr *pRet = 0;
101443   Fts3Expr *pPrev = 0;
101444   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
101445   int nIn = n;
101446   const char *zIn = z;
101447   int rc = SQLITE_OK;
101448   int isRequirePhrase = 1;
101449
101450   while( rc==SQLITE_OK ){
101451     Fts3Expr *p = 0;
101452     int nByte = 0;
101453     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
101454     if( rc==SQLITE_OK ){
101455       int isPhrase;
101456
101457       if( !sqlite3_fts3_enable_parentheses 
101458        && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot 
101459       ){
101460         /* Create an implicit NOT operator. */
101461         Fts3Expr *pNot = sqlite3_malloc(sizeof(Fts3Expr));
101462         if( !pNot ){
101463           sqlite3Fts3ExprFree(p);
101464           rc = SQLITE_NOMEM;
101465           goto exprparse_out;
101466         }
101467         memset(pNot, 0, sizeof(Fts3Expr));
101468         pNot->eType = FTSQUERY_NOT;
101469         pNot->pRight = p;
101470         if( pNotBranch ){
101471           pNot->pLeft = pNotBranch;
101472         }
101473         pNotBranch = pNot;
101474         p = pPrev;
101475       }else{
101476         int eType = p->eType;
101477         assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
101478         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
101479
101480         /* The isRequirePhrase variable is set to true if a phrase or
101481         ** an expression contained in parenthesis is required. If a
101482         ** binary operator (AND, OR, NOT or NEAR) is encounted when
101483         ** isRequirePhrase is set, this is a syntax error.
101484         */
101485         if( !isPhrase && isRequirePhrase ){
101486           sqlite3Fts3ExprFree(p);
101487           rc = SQLITE_ERROR;
101488           goto exprparse_out;
101489         }
101490   
101491         if( isPhrase && !isRequirePhrase ){
101492           /* Insert an implicit AND operator. */
101493           Fts3Expr *pAnd;
101494           assert( pRet && pPrev );
101495           pAnd = sqlite3_malloc(sizeof(Fts3Expr));
101496           if( !pAnd ){
101497             sqlite3Fts3ExprFree(p);
101498             rc = SQLITE_NOMEM;
101499             goto exprparse_out;
101500           }
101501           memset(pAnd, 0, sizeof(Fts3Expr));
101502           pAnd->eType = FTSQUERY_AND;
101503           insertBinaryOperator(&pRet, pPrev, pAnd);
101504           pPrev = pAnd;
101505         }
101506
101507         /* This test catches attempts to make either operand of a NEAR
101508         ** operator something other than a phrase. For example, either of
101509         ** the following:
101510         **
101511         **    (bracketed expression) NEAR phrase
101512         **    phrase NEAR (bracketed expression)
101513         **
101514         ** Return an error in either case.
101515         */
101516         if( pPrev && (
101517             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
101518          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
101519         )){
101520           sqlite3Fts3ExprFree(p);
101521           rc = SQLITE_ERROR;
101522           goto exprparse_out;
101523         }
101524   
101525         if( isPhrase ){
101526           if( pRet ){
101527             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
101528             pPrev->pRight = p;
101529             p->pParent = pPrev;
101530           }else{
101531             pRet = p;
101532           }
101533         }else{
101534           insertBinaryOperator(&pRet, pPrev, p);
101535         }
101536         isRequirePhrase = !isPhrase;
101537       }
101538       assert( nByte>0 );
101539     }
101540     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
101541     nIn -= nByte;
101542     zIn += nByte;
101543     pPrev = p;
101544   }
101545
101546   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
101547     rc = SQLITE_ERROR;
101548   }
101549
101550   if( rc==SQLITE_DONE ){
101551     rc = SQLITE_OK;
101552     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
101553       if( !pRet ){
101554         rc = SQLITE_ERROR;
101555       }else{
101556         Fts3Expr *pIter = pNotBranch;
101557         while( pIter->pLeft ){
101558           pIter = pIter->pLeft;
101559         }
101560         pIter->pLeft = pRet;
101561         pRet = pNotBranch;
101562       }
101563     }
101564   }
101565   *pnConsumed = n - nIn;
101566
101567 exprparse_out:
101568   if( rc!=SQLITE_OK ){
101569     sqlite3Fts3ExprFree(pRet);
101570     sqlite3Fts3ExprFree(pNotBranch);
101571     pRet = 0;
101572   }
101573   *ppExpr = pRet;
101574   return rc;
101575 }
101576
101577 /*
101578 ** Parameters z and n contain a pointer to and length of a buffer containing
101579 ** an fts3 query expression, respectively. This function attempts to parse the
101580 ** query expression and create a tree of Fts3Expr structures representing the
101581 ** parsed expression. If successful, *ppExpr is set to point to the head
101582 ** of the parsed expression tree and SQLITE_OK is returned. If an error
101583 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
101584 ** error) is returned and *ppExpr is set to 0.
101585 **
101586 ** If parameter n is a negative number, then z is assumed to point to a
101587 ** nul-terminated string and the length is determined using strlen().
101588 **
101589 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
101590 ** use to normalize query tokens while parsing the expression. The azCol[]
101591 ** array, which is assumed to contain nCol entries, should contain the names
101592 ** of each column in the target fts3 table, in order from left to right. 
101593 ** Column names must be nul-terminated strings.
101594 **
101595 ** The iDefaultCol parameter should be passed the index of the table column
101596 ** that appears on the left-hand-side of the MATCH operator (the default
101597 ** column to match against for tokens for which a column name is not explicitly
101598 ** specified as part of the query string), or -1 if tokens may by default
101599 ** match any table column.
101600 */
101601 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
101602   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
101603   char **azCol,                       /* Array of column names for fts3 table */
101604   int nCol,                           /* Number of entries in azCol[] */
101605   int iDefaultCol,                    /* Default column to query */
101606   const char *z, int n,               /* Text of MATCH query */
101607   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
101608 ){
101609   int nParsed;
101610   int rc;
101611   ParseContext sParse;
101612   sParse.pTokenizer = pTokenizer;
101613   sParse.azCol = (const char **)azCol;
101614   sParse.nCol = nCol;
101615   sParse.iDefaultCol = iDefaultCol;
101616   sParse.nNest = 0;
101617   if( z==0 ){
101618     *ppExpr = 0;
101619     return SQLITE_OK;
101620   }
101621   if( n<0 ){
101622     n = (int)strlen(z);
101623   }
101624   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
101625
101626   /* Check for mismatched parenthesis */
101627   if( rc==SQLITE_OK && sParse.nNest ){
101628     rc = SQLITE_ERROR;
101629     sqlite3Fts3ExprFree(*ppExpr);
101630     *ppExpr = 0;
101631   }
101632
101633   return rc;
101634 }
101635
101636 /*
101637 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
101638 */
101639 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
101640   if( p ){
101641     sqlite3Fts3ExprFree(p->pLeft);
101642     sqlite3Fts3ExprFree(p->pRight);
101643     sqlite3_free(p->aDoclist);
101644     sqlite3_free(p);
101645   }
101646 }
101647
101648 /****************************************************************************
101649 *****************************************************************************
101650 ** Everything after this point is just test code.
101651 */
101652
101653 #ifdef SQLITE_TEST
101654
101655
101656 /*
101657 ** Function to query the hash-table of tokenizers (see README.tokenizers).
101658 */
101659 static int queryTestTokenizer(
101660   sqlite3 *db, 
101661   const char *zName,  
101662   const sqlite3_tokenizer_module **pp
101663 ){
101664   int rc;
101665   sqlite3_stmt *pStmt;
101666   const char zSql[] = "SELECT fts3_tokenizer(?)";
101667
101668   *pp = 0;
101669   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
101670   if( rc!=SQLITE_OK ){
101671     return rc;
101672   }
101673
101674   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
101675   if( SQLITE_ROW==sqlite3_step(pStmt) ){
101676     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
101677       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
101678     }
101679   }
101680
101681   return sqlite3_finalize(pStmt);
101682 }
101683
101684 /*
101685 ** This function is part of the test interface for the query parser. It
101686 ** writes a text representation of the query expression pExpr into the
101687 ** buffer pointed to by argument zBuf. It is assumed that zBuf is large 
101688 ** enough to store the required text representation.
101689 */
101690 static void exprToString(Fts3Expr *pExpr, char *zBuf){
101691   switch( pExpr->eType ){
101692     case FTSQUERY_PHRASE: {
101693       Fts3Phrase *pPhrase = pExpr->pPhrase;
101694       int i;
101695       zBuf += sprintf(zBuf, "PHRASE %d %d", pPhrase->iColumn, pPhrase->isNot);
101696       for(i=0; i<pPhrase->nToken; i++){
101697         zBuf += sprintf(zBuf," %.*s",pPhrase->aToken[i].n,pPhrase->aToken[i].z);
101698         zBuf += sprintf(zBuf,"%s", (pPhrase->aToken[i].isPrefix?"+":""));
101699       }
101700       return;
101701     }
101702
101703     case FTSQUERY_NEAR:
101704       zBuf += sprintf(zBuf, "NEAR/%d ", pExpr->nNear);
101705       break;
101706     case FTSQUERY_NOT:
101707       zBuf += sprintf(zBuf, "NOT ");
101708       break;
101709     case FTSQUERY_AND:
101710       zBuf += sprintf(zBuf, "AND ");
101711       break;
101712     case FTSQUERY_OR:
101713       zBuf += sprintf(zBuf, "OR ");
101714       break;
101715   }
101716
101717   zBuf += sprintf(zBuf, "{");
101718   exprToString(pExpr->pLeft, zBuf);
101719   zBuf += strlen(zBuf);
101720   zBuf += sprintf(zBuf, "} ");
101721
101722   zBuf += sprintf(zBuf, "{");
101723   exprToString(pExpr->pRight, zBuf);
101724   zBuf += strlen(zBuf);
101725   zBuf += sprintf(zBuf, "}");
101726 }
101727
101728 /*
101729 ** This is the implementation of a scalar SQL function used to test the 
101730 ** expression parser. It should be called as follows:
101731 **
101732 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
101733 **
101734 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
101735 ** to parse the query expression (see README.tokenizers). The second argument
101736 ** is the query expression to parse. Each subsequent argument is the name
101737 ** of a column of the fts3 table that the query expression may refer to.
101738 ** For example:
101739 **
101740 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
101741 */
101742 static void fts3ExprTest(
101743   sqlite3_context *context,
101744   int argc,
101745   sqlite3_value **argv
101746 ){
101747   sqlite3_tokenizer_module const *pModule = 0;
101748   sqlite3_tokenizer *pTokenizer = 0;
101749   int rc;
101750   char **azCol = 0;
101751   const char *zExpr;
101752   int nExpr;
101753   int nCol;
101754   int ii;
101755   Fts3Expr *pExpr;
101756   sqlite3 *db = sqlite3_context_db_handle(context);
101757
101758   if( argc<3 ){
101759     sqlite3_result_error(context, 
101760         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
101761     );
101762     return;
101763   }
101764
101765   rc = queryTestTokenizer(db,
101766                           (const char *)sqlite3_value_text(argv[0]), &pModule);
101767   if( rc==SQLITE_NOMEM ){
101768     sqlite3_result_error_nomem(context);
101769     goto exprtest_out;
101770   }else if( !pModule ){
101771     sqlite3_result_error(context, "No such tokenizer module", -1);
101772     goto exprtest_out;
101773   }
101774
101775   rc = pModule->xCreate(0, 0, &pTokenizer);
101776   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
101777   if( rc==SQLITE_NOMEM ){
101778     sqlite3_result_error_nomem(context);
101779     goto exprtest_out;
101780   }
101781   pTokenizer->pModule = pModule;
101782
101783   zExpr = (const char *)sqlite3_value_text(argv[1]);
101784   nExpr = sqlite3_value_bytes(argv[1]);
101785   nCol = argc-2;
101786   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
101787   if( !azCol ){
101788     sqlite3_result_error_nomem(context);
101789     goto exprtest_out;
101790   }
101791   for(ii=0; ii<nCol; ii++){
101792     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
101793   }
101794
101795   rc = sqlite3Fts3ExprParse(
101796       pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
101797   );
101798   if( rc==SQLITE_NOMEM ){
101799     sqlite3_result_error_nomem(context);
101800     goto exprtest_out;
101801   }else if( rc==SQLITE_OK ){
101802     char zBuf[4096];
101803     exprToString(pExpr, zBuf);
101804     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
101805     sqlite3Fts3ExprFree(pExpr);
101806   }else{
101807     sqlite3_result_error(context, "Error parsing expression", -1);
101808   }
101809
101810 exprtest_out:
101811   if( pModule && pTokenizer ){
101812     rc = pModule->xDestroy(pTokenizer);
101813   }
101814   sqlite3_free(azCol);
101815 }
101816
101817 /*
101818 ** Register the query expression parser test function fts3_exprtest() 
101819 ** with database connection db. 
101820 */
101821 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
101822   return sqlite3_create_function(
101823       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
101824   );
101825 }
101826
101827 #endif
101828 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
101829
101830 /************** End of fts3_expr.c *******************************************/
101831 /************** Begin file fts3_hash.c ***************************************/
101832 /*
101833 ** 2001 September 22
101834 **
101835 ** The author disclaims copyright to this source code.  In place of
101836 ** a legal notice, here is a blessing:
101837 **
101838 **    May you do good and not evil.
101839 **    May you find forgiveness for yourself and forgive others.
101840 **    May you share freely, never taking more than you give.
101841 **
101842 *************************************************************************
101843 ** This is the implementation of generic hash-tables used in SQLite.
101844 ** We've modified it slightly to serve as a standalone hash table
101845 ** implementation for the full-text indexing module.
101846 */
101847
101848 /*
101849 ** The code in this file is only compiled if:
101850 **
101851 **     * The FTS3 module is being built as an extension
101852 **       (in which case SQLITE_CORE is not defined), or
101853 **
101854 **     * The FTS3 module is being built into the core of
101855 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
101856 */
101857 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
101858
101859
101860
101861 /*
101862 ** Malloc and Free functions
101863 */
101864 static void *fts3HashMalloc(int n){
101865   void *p = sqlite3_malloc(n);
101866   if( p ){
101867     memset(p, 0, n);
101868   }
101869   return p;
101870 }
101871 static void fts3HashFree(void *p){
101872   sqlite3_free(p);
101873 }
101874
101875 /* Turn bulk memory into a hash table object by initializing the
101876 ** fields of the Hash structure.
101877 **
101878 ** "pNew" is a pointer to the hash table that is to be initialized.
101879 ** keyClass is one of the constants 
101880 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
101881 ** determines what kind of key the hash table will use.  "copyKey" is
101882 ** true if the hash table should make its own private copy of keys and
101883 ** false if it should just use the supplied pointer.
101884 */
101885 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
101886   assert( pNew!=0 );
101887   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
101888   pNew->keyClass = keyClass;
101889   pNew->copyKey = copyKey;
101890   pNew->first = 0;
101891   pNew->count = 0;
101892   pNew->htsize = 0;
101893   pNew->ht = 0;
101894 }
101895
101896 /* Remove all entries from a hash table.  Reclaim all memory.
101897 ** Call this routine to delete a hash table or to reset a hash table
101898 ** to the empty state.
101899 */
101900 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
101901   Fts3HashElem *elem;         /* For looping over all elements of the table */
101902
101903   assert( pH!=0 );
101904   elem = pH->first;
101905   pH->first = 0;
101906   fts3HashFree(pH->ht);
101907   pH->ht = 0;
101908   pH->htsize = 0;
101909   while( elem ){
101910     Fts3HashElem *next_elem = elem->next;
101911     if( pH->copyKey && elem->pKey ){
101912       fts3HashFree(elem->pKey);
101913     }
101914     fts3HashFree(elem);
101915     elem = next_elem;
101916   }
101917   pH->count = 0;
101918 }
101919
101920 /*
101921 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
101922 */
101923 static int fts3StrHash(const void *pKey, int nKey){
101924   const char *z = (const char *)pKey;
101925   int h = 0;
101926   if( nKey<=0 ) nKey = (int) strlen(z);
101927   while( nKey > 0  ){
101928     h = (h<<3) ^ h ^ *z++;
101929     nKey--;
101930   }
101931   return h & 0x7fffffff;
101932 }
101933 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
101934   if( n1!=n2 ) return 1;
101935   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
101936 }
101937
101938 /*
101939 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
101940 */
101941 static int fts3BinHash(const void *pKey, int nKey){
101942   int h = 0;
101943   const char *z = (const char *)pKey;
101944   while( nKey-- > 0 ){
101945     h = (h<<3) ^ h ^ *(z++);
101946   }
101947   return h & 0x7fffffff;
101948 }
101949 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
101950   if( n1!=n2 ) return 1;
101951   return memcmp(pKey1,pKey2,n1);
101952 }
101953
101954 /*
101955 ** Return a pointer to the appropriate hash function given the key class.
101956 **
101957 ** The C syntax in this function definition may be unfamilar to some 
101958 ** programmers, so we provide the following additional explanation:
101959 **
101960 ** The name of the function is "ftsHashFunction".  The function takes a
101961 ** single parameter "keyClass".  The return value of ftsHashFunction()
101962 ** is a pointer to another function.  Specifically, the return value
101963 ** of ftsHashFunction() is a pointer to a function that takes two parameters
101964 ** with types "const void*" and "int" and returns an "int".
101965 */
101966 static int (*ftsHashFunction(int keyClass))(const void*,int){
101967   if( keyClass==FTS3_HASH_STRING ){
101968     return &fts3StrHash;
101969   }else{
101970     assert( keyClass==FTS3_HASH_BINARY );
101971     return &fts3BinHash;
101972   }
101973 }
101974
101975 /*
101976 ** Return a pointer to the appropriate hash function given the key class.
101977 **
101978 ** For help in interpreted the obscure C code in the function definition,
101979 ** see the header comment on the previous function.
101980 */
101981 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
101982   if( keyClass==FTS3_HASH_STRING ){
101983     return &fts3StrCompare;
101984   }else{
101985     assert( keyClass==FTS3_HASH_BINARY );
101986     return &fts3BinCompare;
101987   }
101988 }
101989
101990 /* Link an element into the hash table
101991 */
101992 static void fts3HashInsertElement(
101993   Fts3Hash *pH,            /* The complete hash table */
101994   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
101995   Fts3HashElem *pNew       /* The element to be inserted */
101996 ){
101997   Fts3HashElem *pHead;     /* First element already in pEntry */
101998   pHead = pEntry->chain;
101999   if( pHead ){
102000     pNew->next = pHead;
102001     pNew->prev = pHead->prev;
102002     if( pHead->prev ){ pHead->prev->next = pNew; }
102003     else             { pH->first = pNew; }
102004     pHead->prev = pNew;
102005   }else{
102006     pNew->next = pH->first;
102007     if( pH->first ){ pH->first->prev = pNew; }
102008     pNew->prev = 0;
102009     pH->first = pNew;
102010   }
102011   pEntry->count++;
102012   pEntry->chain = pNew;
102013 }
102014
102015
102016 /* Resize the hash table so that it cantains "new_size" buckets.
102017 ** "new_size" must be a power of 2.  The hash table might fail 
102018 ** to resize if sqliteMalloc() fails.
102019 **
102020 ** Return non-zero if a memory allocation error occurs.
102021 */
102022 static int fts3Rehash(Fts3Hash *pH, int new_size){
102023   struct _fts3ht *new_ht;          /* The new hash table */
102024   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
102025   int (*xHash)(const void*,int);   /* The hash function */
102026
102027   assert( (new_size & (new_size-1))==0 );
102028   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
102029   if( new_ht==0 ) return 1;
102030   fts3HashFree(pH->ht);
102031   pH->ht = new_ht;
102032   pH->htsize = new_size;
102033   xHash = ftsHashFunction(pH->keyClass);
102034   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
102035     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
102036     next_elem = elem->next;
102037     fts3HashInsertElement(pH, &new_ht[h], elem);
102038   }
102039   return 0;
102040 }
102041
102042 /* This function (for internal use only) locates an element in an
102043 ** hash table that matches the given key.  The hash for this key has
102044 ** already been computed and is passed as the 4th parameter.
102045 */
102046 static Fts3HashElem *fts3FindElementByHash(
102047   const Fts3Hash *pH, /* The pH to be searched */
102048   const void *pKey,   /* The key we are searching for */
102049   int nKey,
102050   int h               /* The hash for this key. */
102051 ){
102052   Fts3HashElem *elem;            /* Used to loop thru the element list */
102053   int count;                     /* Number of elements left to test */
102054   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
102055
102056   if( pH->ht ){
102057     struct _fts3ht *pEntry = &pH->ht[h];
102058     elem = pEntry->chain;
102059     count = pEntry->count;
102060     xCompare = ftsCompareFunction(pH->keyClass);
102061     while( count-- && elem ){
102062       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
102063         return elem;
102064       }
102065       elem = elem->next;
102066     }
102067   }
102068   return 0;
102069 }
102070
102071 /* Remove a single entry from the hash table given a pointer to that
102072 ** element and a hash on the element's key.
102073 */
102074 static void fts3RemoveElementByHash(
102075   Fts3Hash *pH,         /* The pH containing "elem" */
102076   Fts3HashElem* elem,   /* The element to be removed from the pH */
102077   int h                 /* Hash value for the element */
102078 ){
102079   struct _fts3ht *pEntry;
102080   if( elem->prev ){
102081     elem->prev->next = elem->next; 
102082   }else{
102083     pH->first = elem->next;
102084   }
102085   if( elem->next ){
102086     elem->next->prev = elem->prev;
102087   }
102088   pEntry = &pH->ht[h];
102089   if( pEntry->chain==elem ){
102090     pEntry->chain = elem->next;
102091   }
102092   pEntry->count--;
102093   if( pEntry->count<=0 ){
102094     pEntry->chain = 0;
102095   }
102096   if( pH->copyKey && elem->pKey ){
102097     fts3HashFree(elem->pKey);
102098   }
102099   fts3HashFree( elem );
102100   pH->count--;
102101   if( pH->count<=0 ){
102102     assert( pH->first==0 );
102103     assert( pH->count==0 );
102104     fts3HashClear(pH);
102105   }
102106 }
102107
102108 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
102109   const Fts3Hash *pH, 
102110   const void *pKey, 
102111   int nKey
102112 ){
102113   int h;                          /* A hash on key */
102114   int (*xHash)(const void*,int);  /* The hash function */
102115
102116   if( pH==0 || pH->ht==0 ) return 0;
102117   xHash = ftsHashFunction(pH->keyClass);
102118   assert( xHash!=0 );
102119   h = (*xHash)(pKey,nKey);
102120   assert( (pH->htsize & (pH->htsize-1))==0 );
102121   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
102122 }
102123
102124 /* 
102125 ** Attempt to locate an element of the hash table pH with a key
102126 ** that matches pKey,nKey.  Return the data for this element if it is
102127 ** found, or NULL if there is no match.
102128 */
102129 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
102130   Fts3HashElem *pElem;            /* The element that matches key (if any) */
102131
102132   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
102133   return pElem ? pElem->data : 0;
102134 }
102135
102136 /* Insert an element into the hash table pH.  The key is pKey,nKey
102137 ** and the data is "data".
102138 **
102139 ** If no element exists with a matching key, then a new
102140 ** element is created.  A copy of the key is made if the copyKey
102141 ** flag is set.  NULL is returned.
102142 **
102143 ** If another element already exists with the same key, then the
102144 ** new data replaces the old data and the old data is returned.
102145 ** The key is not copied in this instance.  If a malloc fails, then
102146 ** the new data is returned and the hash table is unchanged.
102147 **
102148 ** If the "data" parameter to this function is NULL, then the
102149 ** element corresponding to "key" is removed from the hash table.
102150 */
102151 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
102152   Fts3Hash *pH,        /* The hash table to insert into */
102153   const void *pKey,    /* The key */
102154   int nKey,            /* Number of bytes in the key */
102155   void *data           /* The data */
102156 ){
102157   int hraw;                 /* Raw hash value of the key */
102158   int h;                    /* the hash of the key modulo hash table size */
102159   Fts3HashElem *elem;       /* Used to loop thru the element list */
102160   Fts3HashElem *new_elem;   /* New element added to the pH */
102161   int (*xHash)(const void*,int);  /* The hash function */
102162
102163   assert( pH!=0 );
102164   xHash = ftsHashFunction(pH->keyClass);
102165   assert( xHash!=0 );
102166   hraw = (*xHash)(pKey, nKey);
102167   assert( (pH->htsize & (pH->htsize-1))==0 );
102168   h = hraw & (pH->htsize-1);
102169   elem = fts3FindElementByHash(pH,pKey,nKey,h);
102170   if( elem ){
102171     void *old_data = elem->data;
102172     if( data==0 ){
102173       fts3RemoveElementByHash(pH,elem,h);
102174     }else{
102175       elem->data = data;
102176     }
102177     return old_data;
102178   }
102179   if( data==0 ) return 0;
102180   if( (pH->htsize==0 && fts3Rehash(pH,8))
102181    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
102182   ){
102183     pH->count = 0;
102184     return data;
102185   }
102186   assert( pH->htsize>0 );
102187   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
102188   if( new_elem==0 ) return data;
102189   if( pH->copyKey && pKey!=0 ){
102190     new_elem->pKey = fts3HashMalloc( nKey );
102191     if( new_elem->pKey==0 ){
102192       fts3HashFree(new_elem);
102193       return data;
102194     }
102195     memcpy((void*)new_elem->pKey, pKey, nKey);
102196   }else{
102197     new_elem->pKey = (void*)pKey;
102198   }
102199   new_elem->nKey = nKey;
102200   pH->count++;
102201   assert( pH->htsize>0 );
102202   assert( (pH->htsize & (pH->htsize-1))==0 );
102203   h = hraw & (pH->htsize-1);
102204   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
102205   new_elem->data = data;
102206   return 0;
102207 }
102208
102209 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
102210
102211 /************** End of fts3_hash.c *******************************************/
102212 /************** Begin file fts3_porter.c *************************************/
102213 /*
102214 ** 2006 September 30
102215 **
102216 ** The author disclaims copyright to this source code.  In place of
102217 ** a legal notice, here is a blessing:
102218 **
102219 **    May you do good and not evil.
102220 **    May you find forgiveness for yourself and forgive others.
102221 **    May you share freely, never taking more than you give.
102222 **
102223 *************************************************************************
102224 ** Implementation of the full-text-search tokenizer that implements
102225 ** a Porter stemmer.
102226 */
102227
102228 /*
102229 ** The code in this file is only compiled if:
102230 **
102231 **     * The FTS3 module is being built as an extension
102232 **       (in which case SQLITE_CORE is not defined), or
102233 **
102234 **     * The FTS3 module is being built into the core of
102235 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
102236 */
102237 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
102238
102239
102240
102241
102242 /*
102243 ** Class derived from sqlite3_tokenizer
102244 */
102245 typedef struct porter_tokenizer {
102246   sqlite3_tokenizer base;      /* Base class */
102247 } porter_tokenizer;
102248
102249 /*
102250 ** Class derived from sqlit3_tokenizer_cursor
102251 */
102252 typedef struct porter_tokenizer_cursor {
102253   sqlite3_tokenizer_cursor base;
102254   const char *zInput;          /* input we are tokenizing */
102255   int nInput;                  /* size of the input */
102256   int iOffset;                 /* current position in zInput */
102257   int iToken;                  /* index of next token to be returned */
102258   char *zToken;                /* storage for current token */
102259   int nAllocated;              /* space allocated to zToken buffer */
102260 } porter_tokenizer_cursor;
102261
102262
102263 /*
102264 ** Create a new tokenizer instance.
102265 */
102266 static int porterCreate(
102267   int argc, const char * const *argv,
102268   sqlite3_tokenizer **ppTokenizer
102269 ){
102270   porter_tokenizer *t;
102271
102272   UNUSED_PARAMETER(argc);
102273   UNUSED_PARAMETER(argv);
102274
102275   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
102276   if( t==NULL ) return SQLITE_NOMEM;
102277   memset(t, 0, sizeof(*t));
102278   *ppTokenizer = &t->base;
102279   return SQLITE_OK;
102280 }
102281
102282 /*
102283 ** Destroy a tokenizer
102284 */
102285 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
102286   sqlite3_free(pTokenizer);
102287   return SQLITE_OK;
102288 }
102289
102290 /*
102291 ** Prepare to begin tokenizing a particular string.  The input
102292 ** string to be tokenized is zInput[0..nInput-1].  A cursor
102293 ** used to incrementally tokenize this string is returned in 
102294 ** *ppCursor.
102295 */
102296 static int porterOpen(
102297   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
102298   const char *zInput, int nInput,        /* String to be tokenized */
102299   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
102300 ){
102301   porter_tokenizer_cursor *c;
102302
102303   UNUSED_PARAMETER(pTokenizer);
102304
102305   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
102306   if( c==NULL ) return SQLITE_NOMEM;
102307
102308   c->zInput = zInput;
102309   if( zInput==0 ){
102310     c->nInput = 0;
102311   }else if( nInput<0 ){
102312     c->nInput = (int)strlen(zInput);
102313   }else{
102314     c->nInput = nInput;
102315   }
102316   c->iOffset = 0;                 /* start tokenizing at the beginning */
102317   c->iToken = 0;
102318   c->zToken = NULL;               /* no space allocated, yet. */
102319   c->nAllocated = 0;
102320
102321   *ppCursor = &c->base;
102322   return SQLITE_OK;
102323 }
102324
102325 /*
102326 ** Close a tokenization cursor previously opened by a call to
102327 ** porterOpen() above.
102328 */
102329 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
102330   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
102331   sqlite3_free(c->zToken);
102332   sqlite3_free(c);
102333   return SQLITE_OK;
102334 }
102335 /*
102336 ** Vowel or consonant
102337 */
102338 static const char cType[] = {
102339    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
102340    1, 1, 1, 2, 1
102341 };
102342
102343 /*
102344 ** isConsonant() and isVowel() determine if their first character in
102345 ** the string they point to is a consonant or a vowel, according
102346 ** to Porter ruls.  
102347 **
102348 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
102349 ** 'Y' is a consonant unless it follows another consonant,
102350 ** in which case it is a vowel.
102351 **
102352 ** In these routine, the letters are in reverse order.  So the 'y' rule
102353 ** is that 'y' is a consonant unless it is followed by another
102354 ** consonent.
102355 */
102356 static int isVowel(const char*);
102357 static int isConsonant(const char *z){
102358   int j;
102359   char x = *z;
102360   if( x==0 ) return 0;
102361   assert( x>='a' && x<='z' );
102362   j = cType[x-'a'];
102363   if( j<2 ) return j;
102364   return z[1]==0 || isVowel(z + 1);
102365 }
102366 static int isVowel(const char *z){
102367   int j;
102368   char x = *z;
102369   if( x==0 ) return 0;
102370   assert( x>='a' && x<='z' );
102371   j = cType[x-'a'];
102372   if( j<2 ) return 1-j;
102373   return isConsonant(z + 1);
102374 }
102375
102376 /*
102377 ** Let any sequence of one or more vowels be represented by V and let
102378 ** C be sequence of one or more consonants.  Then every word can be
102379 ** represented as:
102380 **
102381 **           [C] (VC){m} [V]
102382 **
102383 ** In prose:  A word is an optional consonant followed by zero or
102384 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
102385 ** number of vowel consonant pairs.  This routine computes the value
102386 ** of m for the first i bytes of a word.
102387 **
102388 ** Return true if the m-value for z is 1 or more.  In other words,
102389 ** return true if z contains at least one vowel that is followed
102390 ** by a consonant.
102391 **
102392 ** In this routine z[] is in reverse order.  So we are really looking
102393 ** for an instance of of a consonant followed by a vowel.
102394 */
102395 static int m_gt_0(const char *z){
102396   while( isVowel(z) ){ z++; }
102397   if( *z==0 ) return 0;
102398   while( isConsonant(z) ){ z++; }
102399   return *z!=0;
102400 }
102401
102402 /* Like mgt0 above except we are looking for a value of m which is
102403 ** exactly 1
102404 */
102405 static int m_eq_1(const char *z){
102406   while( isVowel(z) ){ z++; }
102407   if( *z==0 ) return 0;
102408   while( isConsonant(z) ){ z++; }
102409   if( *z==0 ) return 0;
102410   while( isVowel(z) ){ z++; }
102411   if( *z==0 ) return 1;
102412   while( isConsonant(z) ){ z++; }
102413   return *z==0;
102414 }
102415
102416 /* Like mgt0 above except we are looking for a value of m>1 instead
102417 ** or m>0
102418 */
102419 static int m_gt_1(const char *z){
102420   while( isVowel(z) ){ z++; }
102421   if( *z==0 ) return 0;
102422   while( isConsonant(z) ){ z++; }
102423   if( *z==0 ) return 0;
102424   while( isVowel(z) ){ z++; }
102425   if( *z==0 ) return 0;
102426   while( isConsonant(z) ){ z++; }
102427   return *z!=0;
102428 }
102429
102430 /*
102431 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
102432 */
102433 static int hasVowel(const char *z){
102434   while( isConsonant(z) ){ z++; }
102435   return *z!=0;
102436 }
102437
102438 /*
102439 ** Return TRUE if the word ends in a double consonant.
102440 **
102441 ** The text is reversed here. So we are really looking at
102442 ** the first two characters of z[].
102443 */
102444 static int doubleConsonant(const char *z){
102445   return isConsonant(z) && z[0]==z[1];
102446 }
102447
102448 /*
102449 ** Return TRUE if the word ends with three letters which
102450 ** are consonant-vowel-consonent and where the final consonant
102451 ** is not 'w', 'x', or 'y'.
102452 **
102453 ** The word is reversed here.  So we are really checking the
102454 ** first three letters and the first one cannot be in [wxy].
102455 */
102456 static int star_oh(const char *z){
102457   return
102458     isConsonant(z) &&
102459     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
102460     isVowel(z+1) &&
102461     isConsonant(z+2);
102462 }
102463
102464 /*
102465 ** If the word ends with zFrom and xCond() is true for the stem
102466 ** of the word that preceeds the zFrom ending, then change the 
102467 ** ending to zTo.
102468 **
102469 ** The input word *pz and zFrom are both in reverse order.  zTo
102470 ** is in normal order. 
102471 **
102472 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
102473 ** match.  Not that TRUE is returned even if xCond() fails and
102474 ** no substitution occurs.
102475 */
102476 static int stem(
102477   char **pz,             /* The word being stemmed (Reversed) */
102478   const char *zFrom,     /* If the ending matches this... (Reversed) */
102479   const char *zTo,       /* ... change the ending to this (not reversed) */
102480   int (*xCond)(const char*)   /* Condition that must be true */
102481 ){
102482   char *z = *pz;
102483   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
102484   if( *zFrom!=0 ) return 0;
102485   if( xCond && !xCond(z) ) return 1;
102486   while( *zTo ){
102487     *(--z) = *(zTo++);
102488   }
102489   *pz = z;
102490   return 1;
102491 }
102492
102493 /*
102494 ** This is the fallback stemmer used when the porter stemmer is
102495 ** inappropriate.  The input word is copied into the output with
102496 ** US-ASCII case folding.  If the input word is too long (more
102497 ** than 20 bytes if it contains no digits or more than 6 bytes if
102498 ** it contains digits) then word is truncated to 20 or 6 bytes
102499 ** by taking 10 or 3 bytes from the beginning and end.
102500 */
102501 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
102502   int i, mx, j;
102503   int hasDigit = 0;
102504   for(i=0; i<nIn; i++){
102505     char c = zIn[i];
102506     if( c>='A' && c<='Z' ){
102507       zOut[i] = c - 'A' + 'a';
102508     }else{
102509       if( c>='0' && c<='9' ) hasDigit = 1;
102510       zOut[i] = c;
102511     }
102512   }
102513   mx = hasDigit ? 3 : 10;
102514   if( nIn>mx*2 ){
102515     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
102516       zOut[j] = zOut[i];
102517     }
102518     i = j;
102519   }
102520   zOut[i] = 0;
102521   *pnOut = i;
102522 }
102523
102524
102525 /*
102526 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
102527 ** zOut is at least big enough to hold nIn bytes.  Write the actual
102528 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
102529 **
102530 ** Any upper-case characters in the US-ASCII character set ([A-Z])
102531 ** are converted to lower case.  Upper-case UTF characters are
102532 ** unchanged.
102533 **
102534 ** Words that are longer than about 20 bytes are stemmed by retaining
102535 ** a few bytes from the beginning and the end of the word.  If the
102536 ** word contains digits, 3 bytes are taken from the beginning and
102537 ** 3 bytes from the end.  For long words without digits, 10 bytes
102538 ** are taken from each end.  US-ASCII case folding still applies.
102539 ** 
102540 ** If the input word contains not digits but does characters not 
102541 ** in [a-zA-Z] then no stemming is attempted and this routine just 
102542 ** copies the input into the input into the output with US-ASCII
102543 ** case folding.
102544 **
102545 ** Stemming never increases the length of the word.  So there is
102546 ** no chance of overflowing the zOut buffer.
102547 */
102548 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
102549   int i, j;
102550   char zReverse[28];
102551   char *z, *z2;
102552   if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
102553     /* The word is too big or too small for the porter stemmer.
102554     ** Fallback to the copy stemmer */
102555     copy_stemmer(zIn, nIn, zOut, pnOut);
102556     return;
102557   }
102558   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
102559     char c = zIn[i];
102560     if( c>='A' && c<='Z' ){
102561       zReverse[j] = c + 'a' - 'A';
102562     }else if( c>='a' && c<='z' ){
102563       zReverse[j] = c;
102564     }else{
102565       /* The use of a character not in [a-zA-Z] means that we fallback
102566       ** to the copy stemmer */
102567       copy_stemmer(zIn, nIn, zOut, pnOut);
102568       return;
102569     }
102570   }
102571   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
102572   z = &zReverse[j+1];
102573
102574
102575   /* Step 1a */
102576   if( z[0]=='s' ){
102577     if(
102578      !stem(&z, "sess", "ss", 0) &&
102579      !stem(&z, "sei", "i", 0)  &&
102580      !stem(&z, "ss", "ss", 0)
102581     ){
102582       z++;
102583     }
102584   }
102585
102586   /* Step 1b */  
102587   z2 = z;
102588   if( stem(&z, "dee", "ee", m_gt_0) ){
102589     /* Do nothing.  The work was all in the test */
102590   }else if( 
102591      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
102592       && z!=z2
102593   ){
102594      if( stem(&z, "ta", "ate", 0) ||
102595          stem(&z, "lb", "ble", 0) ||
102596          stem(&z, "zi", "ize", 0) ){
102597        /* Do nothing.  The work was all in the test */
102598      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
102599        z++;
102600      }else if( m_eq_1(z) && star_oh(z) ){
102601        *(--z) = 'e';
102602      }
102603   }
102604
102605   /* Step 1c */
102606   if( z[0]=='y' && hasVowel(z+1) ){
102607     z[0] = 'i';
102608   }
102609
102610   /* Step 2 */
102611   switch( z[1] ){
102612    case 'a':
102613      stem(&z, "lanoita", "ate", m_gt_0) ||
102614      stem(&z, "lanoit", "tion", m_gt_0);
102615      break;
102616    case 'c':
102617      stem(&z, "icne", "ence", m_gt_0) ||
102618      stem(&z, "icna", "ance", m_gt_0);
102619      break;
102620    case 'e':
102621      stem(&z, "rezi", "ize", m_gt_0);
102622      break;
102623    case 'g':
102624      stem(&z, "igol", "log", m_gt_0);
102625      break;
102626    case 'l':
102627      stem(&z, "ilb", "ble", m_gt_0) ||
102628      stem(&z, "illa", "al", m_gt_0) ||
102629      stem(&z, "iltne", "ent", m_gt_0) ||
102630      stem(&z, "ile", "e", m_gt_0) ||
102631      stem(&z, "ilsuo", "ous", m_gt_0);
102632      break;
102633    case 'o':
102634      stem(&z, "noitazi", "ize", m_gt_0) ||
102635      stem(&z, "noita", "ate", m_gt_0) ||
102636      stem(&z, "rota", "ate", m_gt_0);
102637      break;
102638    case 's':
102639      stem(&z, "msila", "al", m_gt_0) ||
102640      stem(&z, "ssenevi", "ive", m_gt_0) ||
102641      stem(&z, "ssenluf", "ful", m_gt_0) ||
102642      stem(&z, "ssensuo", "ous", m_gt_0);
102643      break;
102644    case 't':
102645      stem(&z, "itila", "al", m_gt_0) ||
102646      stem(&z, "itivi", "ive", m_gt_0) ||
102647      stem(&z, "itilib", "ble", m_gt_0);
102648      break;
102649   }
102650
102651   /* Step 3 */
102652   switch( z[0] ){
102653    case 'e':
102654      stem(&z, "etaci", "ic", m_gt_0) ||
102655      stem(&z, "evita", "", m_gt_0)   ||
102656      stem(&z, "ezila", "al", m_gt_0);
102657      break;
102658    case 'i':
102659      stem(&z, "itici", "ic", m_gt_0);
102660      break;
102661    case 'l':
102662      stem(&z, "laci", "ic", m_gt_0) ||
102663      stem(&z, "luf", "", m_gt_0);
102664      break;
102665    case 's':
102666      stem(&z, "ssen", "", m_gt_0);
102667      break;
102668   }
102669
102670   /* Step 4 */
102671   switch( z[1] ){
102672    case 'a':
102673      if( z[0]=='l' && m_gt_1(z+2) ){
102674        z += 2;
102675      }
102676      break;
102677    case 'c':
102678      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
102679        z += 4;
102680      }
102681      break;
102682    case 'e':
102683      if( z[0]=='r' && m_gt_1(z+2) ){
102684        z += 2;
102685      }
102686      break;
102687    case 'i':
102688      if( z[0]=='c' && m_gt_1(z+2) ){
102689        z += 2;
102690      }
102691      break;
102692    case 'l':
102693      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
102694        z += 4;
102695      }
102696      break;
102697    case 'n':
102698      if( z[0]=='t' ){
102699        if( z[2]=='a' ){
102700          if( m_gt_1(z+3) ){
102701            z += 3;
102702          }
102703        }else if( z[2]=='e' ){
102704          stem(&z, "tneme", "", m_gt_1) ||
102705          stem(&z, "tnem", "", m_gt_1) ||
102706          stem(&z, "tne", "", m_gt_1);
102707        }
102708      }
102709      break;
102710    case 'o':
102711      if( z[0]=='u' ){
102712        if( m_gt_1(z+2) ){
102713          z += 2;
102714        }
102715      }else if( z[3]=='s' || z[3]=='t' ){
102716        stem(&z, "noi", "", m_gt_1);
102717      }
102718      break;
102719    case 's':
102720      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
102721        z += 3;
102722      }
102723      break;
102724    case 't':
102725      stem(&z, "eta", "", m_gt_1) ||
102726      stem(&z, "iti", "", m_gt_1);
102727      break;
102728    case 'u':
102729      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
102730        z += 3;
102731      }
102732      break;
102733    case 'v':
102734    case 'z':
102735      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
102736        z += 3;
102737      }
102738      break;
102739   }
102740
102741   /* Step 5a */
102742   if( z[0]=='e' ){
102743     if( m_gt_1(z+1) ){
102744       z++;
102745     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
102746       z++;
102747     }
102748   }
102749
102750   /* Step 5b */
102751   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
102752     z++;
102753   }
102754
102755   /* z[] is now the stemmed word in reverse order.  Flip it back
102756   ** around into forward order and return.
102757   */
102758   *pnOut = i = (int)strlen(z);
102759   zOut[i] = 0;
102760   while( *z ){
102761     zOut[--i] = *(z++);
102762   }
102763 }
102764
102765 /*
102766 ** Characters that can be part of a token.  We assume any character
102767 ** whose value is greater than 0x80 (any UTF character) can be
102768 ** part of a token.  In other words, delimiters all must have
102769 ** values of 0x7f or lower.
102770 */
102771 static const char porterIdChar[] = {
102772 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
102773     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
102774     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
102775     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
102776     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
102777     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
102778 };
102779 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
102780
102781 /*
102782 ** Extract the next token from a tokenization cursor.  The cursor must
102783 ** have been opened by a prior call to porterOpen().
102784 */
102785 static int porterNext(
102786   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
102787   const char **pzToken,               /* OUT: *pzToken is the token text */
102788   int *pnBytes,                       /* OUT: Number of bytes in token */
102789   int *piStartOffset,                 /* OUT: Starting offset of token */
102790   int *piEndOffset,                   /* OUT: Ending offset of token */
102791   int *piPosition                     /* OUT: Position integer of token */
102792 ){
102793   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
102794   const char *z = c->zInput;
102795
102796   while( c->iOffset<c->nInput ){
102797     int iStartOffset, ch;
102798
102799     /* Scan past delimiter characters */
102800     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
102801       c->iOffset++;
102802     }
102803
102804     /* Count non-delimiter characters. */
102805     iStartOffset = c->iOffset;
102806     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
102807       c->iOffset++;
102808     }
102809
102810     if( c->iOffset>iStartOffset ){
102811       int n = c->iOffset-iStartOffset;
102812       if( n>c->nAllocated ){
102813         c->nAllocated = n+20;
102814         c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
102815         if( c->zToken==NULL ) return SQLITE_NOMEM;
102816       }
102817       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
102818       *pzToken = c->zToken;
102819       *piStartOffset = iStartOffset;
102820       *piEndOffset = c->iOffset;
102821       *piPosition = c->iToken++;
102822       return SQLITE_OK;
102823     }
102824   }
102825   return SQLITE_DONE;
102826 }
102827
102828 /*
102829 ** The set of routines that implement the porter-stemmer tokenizer
102830 */
102831 static const sqlite3_tokenizer_module porterTokenizerModule = {
102832   0,
102833   porterCreate,
102834   porterDestroy,
102835   porterOpen,
102836   porterClose,
102837   porterNext,
102838 };
102839
102840 /*
102841 ** Allocate a new porter tokenizer.  Return a pointer to the new
102842 ** tokenizer in *ppModule
102843 */
102844 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
102845   sqlite3_tokenizer_module const**ppModule
102846 ){
102847   *ppModule = &porterTokenizerModule;
102848 }
102849
102850 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
102851
102852 /************** End of fts3_porter.c *****************************************/
102853 /************** Begin file fts3_tokenizer.c **********************************/
102854 /*
102855 ** 2007 June 22
102856 **
102857 ** The author disclaims copyright to this source code.  In place of
102858 ** a legal notice, here is a blessing:
102859 **
102860 **    May you do good and not evil.
102861 **    May you find forgiveness for yourself and forgive others.
102862 **    May you share freely, never taking more than you give.
102863 **
102864 ******************************************************************************
102865 **
102866 ** This is part of an SQLite module implementing full-text search.
102867 ** This particular file implements the generic tokenizer interface.
102868 */
102869
102870 /*
102871 ** The code in this file is only compiled if:
102872 **
102873 **     * The FTS3 module is being built as an extension
102874 **       (in which case SQLITE_CORE is not defined), or
102875 **
102876 **     * The FTS3 module is being built into the core of
102877 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
102878 */
102879 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
102880
102881 #ifndef SQLITE_CORE
102882   SQLITE_EXTENSION_INIT1
102883 #endif
102884
102885
102886 /*
102887 ** Implementation of the SQL scalar function for accessing the underlying 
102888 ** hash table. This function may be called as follows:
102889 **
102890 **   SELECT <function-name>(<key-name>);
102891 **   SELECT <function-name>(<key-name>, <pointer>);
102892 **
102893 ** where <function-name> is the name passed as the second argument
102894 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
102895 **
102896 ** If the <pointer> argument is specified, it must be a blob value
102897 ** containing a pointer to be stored as the hash data corresponding
102898 ** to the string <key-name>. If <pointer> is not specified, then
102899 ** the string <key-name> must already exist in the has table. Otherwise,
102900 ** an error is returned.
102901 **
102902 ** Whether or not the <pointer> argument is specified, the value returned
102903 ** is a blob containing the pointer stored as the hash data corresponding
102904 ** to string <key-name> (after the hash-table is updated, if applicable).
102905 */
102906 static void scalarFunc(
102907   sqlite3_context *context,
102908   int argc,
102909   sqlite3_value **argv
102910 ){
102911   Fts3Hash *pHash;
102912   void *pPtr = 0;
102913   const unsigned char *zName;
102914   int nName;
102915
102916   assert( argc==1 || argc==2 );
102917
102918   pHash = (Fts3Hash *)sqlite3_user_data(context);
102919
102920   zName = sqlite3_value_text(argv[0]);
102921   nName = sqlite3_value_bytes(argv[0])+1;
102922
102923   if( argc==2 ){
102924     void *pOld;
102925     int n = sqlite3_value_bytes(argv[1]);
102926     if( n!=sizeof(pPtr) ){
102927       sqlite3_result_error(context, "argument type mismatch", -1);
102928       return;
102929     }
102930     pPtr = *(void **)sqlite3_value_blob(argv[1]);
102931     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
102932     if( pOld==pPtr ){
102933       sqlite3_result_error(context, "out of memory", -1);
102934       return;
102935     }
102936   }else{
102937     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
102938     if( !pPtr ){
102939       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
102940       sqlite3_result_error(context, zErr, -1);
102941       sqlite3_free(zErr);
102942       return;
102943     }
102944   }
102945
102946   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
102947 }
102948
102949 static int fts3IsIdChar(char c){
102950   static const char isFtsIdChar[] = {
102951       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
102952       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
102953       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
102954       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
102955       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
102956       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
102957       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
102958       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
102959   };
102960   return (c&0x80 || isFtsIdChar[(int)(c)]);
102961 }
102962
102963 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
102964   const char *z1;
102965   const char *z2 = 0;
102966
102967   /* Find the start of the next token. */
102968   z1 = zStr;
102969   while( z2==0 ){
102970     char c = *z1;
102971     switch( c ){
102972       case '\0': return 0;        /* No more tokens here */
102973       case '\'':
102974       case '"':
102975       case '`': {
102976         z2 = z1;
102977         while( *++z2 && (*z2!=c || *++z2==c) );
102978         break;
102979       }
102980       case '[':
102981         z2 = &z1[1];
102982         while( *z2 && z2[0]!=']' ) z2++;
102983         if( *z2 ) z2++;
102984         break;
102985
102986       default:
102987         if( fts3IsIdChar(*z1) ){
102988           z2 = &z1[1];
102989           while( fts3IsIdChar(*z2) ) z2++;
102990         }else{
102991           z1++;
102992         }
102993     }
102994   }
102995
102996   *pn = (int)(z2-z1);
102997   return z1;
102998 }
102999
103000 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
103001   Fts3Hash *pHash,                /* Tokenizer hash table */
103002   const char *zArg,               /* Possible tokenizer specification */
103003   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
103004   const char **pzTokenizer,       /* OUT: Set to zArg if is tokenizer */
103005   char **pzErr                    /* OUT: Set to malloced error message */
103006 ){
103007   int rc;
103008   char *z = (char *)zArg;
103009   int n;
103010   char *zCopy;
103011   char *zEnd;                     /* Pointer to nul-term of zCopy */
103012   sqlite3_tokenizer_module *m;
103013
103014   if( !z ){
103015     zCopy = sqlite3_mprintf("simple");
103016   }else{
103017     if( sqlite3_strnicmp(z, "tokenize", 8) || fts3IsIdChar(z[8])){
103018       return SQLITE_OK;
103019     }
103020     zCopy = sqlite3_mprintf("%s", &z[8]);
103021     *pzTokenizer = zArg;
103022   }
103023   if( !zCopy ){
103024     return SQLITE_NOMEM;
103025   }
103026
103027   zEnd = &zCopy[strlen(zCopy)];
103028
103029   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
103030   z[n] = '\0';
103031   sqlite3Fts3Dequote(z);
103032
103033   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, z, (int)strlen(z)+1);
103034   if( !m ){
103035     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
103036     rc = SQLITE_ERROR;
103037   }else{
103038     char const **aArg = 0;
103039     int iArg = 0;
103040     z = &z[n+1];
103041     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
103042       int nNew = sizeof(char *)*(iArg+1);
103043       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
103044       if( !aNew ){
103045         sqlite3_free(zCopy);
103046         sqlite3_free((void *)aArg);
103047         return SQLITE_NOMEM;
103048       }
103049       aArg = aNew;
103050       aArg[iArg++] = z;
103051       z[n] = '\0';
103052       sqlite3Fts3Dequote(z);
103053       z = &z[n+1];
103054     }
103055     rc = m->xCreate(iArg, aArg, ppTok);
103056     assert( rc!=SQLITE_OK || *ppTok );
103057     if( rc!=SQLITE_OK ){
103058       *pzErr = sqlite3_mprintf("unknown tokenizer");
103059     }else{
103060       (*ppTok)->pModule = m; 
103061     }
103062     sqlite3_free((void *)aArg);
103063   }
103064
103065   sqlite3_free(zCopy);
103066   return rc;
103067 }
103068
103069
103070 #ifdef SQLITE_TEST
103071
103072
103073 /*
103074 ** Implementation of a special SQL scalar function for testing tokenizers 
103075 ** designed to be used in concert with the Tcl testing framework. This
103076 ** function must be called with two arguments:
103077 **
103078 **   SELECT <function-name>(<key-name>, <input-string>);
103079 **   SELECT <function-name>(<key-name>, <pointer>);
103080 **
103081 ** where <function-name> is the name passed as the second argument
103082 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
103083 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
103084 **
103085 ** The return value is a string that may be interpreted as a Tcl
103086 ** list. For each token in the <input-string>, three elements are
103087 ** added to the returned list. The first is the token position, the 
103088 ** second is the token text (folded, stemmed, etc.) and the third is the
103089 ** substring of <input-string> associated with the token. For example, 
103090 ** using the built-in "simple" tokenizer:
103091 **
103092 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
103093 **
103094 ** will return the string:
103095 **
103096 **   "{0 i I 1 dont don't 2 see see 3 how how}"
103097 **   
103098 */
103099 static void testFunc(
103100   sqlite3_context *context,
103101   int argc,
103102   sqlite3_value **argv
103103 ){
103104   Fts3Hash *pHash;
103105   sqlite3_tokenizer_module *p;
103106   sqlite3_tokenizer *pTokenizer = 0;
103107   sqlite3_tokenizer_cursor *pCsr = 0;
103108
103109   const char *zErr = 0;
103110
103111   const char *zName;
103112   int nName;
103113   const char *zInput;
103114   int nInput;
103115
103116   const char *zArg = 0;
103117
103118   const char *zToken;
103119   int nToken;
103120   int iStart;
103121   int iEnd;
103122   int iPos;
103123
103124   Tcl_Obj *pRet;
103125
103126   assert( argc==2 || argc==3 );
103127
103128   nName = sqlite3_value_bytes(argv[0]);
103129   zName = (const char *)sqlite3_value_text(argv[0]);
103130   nInput = sqlite3_value_bytes(argv[argc-1]);
103131   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
103132
103133   if( argc==3 ){
103134     zArg = (const char *)sqlite3_value_text(argv[1]);
103135   }
103136
103137   pHash = (Fts3Hash *)sqlite3_user_data(context);
103138   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
103139
103140   if( !p ){
103141     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
103142     sqlite3_result_error(context, zErr, -1);
103143     sqlite3_free(zErr);
103144     return;
103145   }
103146
103147   pRet = Tcl_NewObj();
103148   Tcl_IncrRefCount(pRet);
103149
103150   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
103151     zErr = "error in xCreate()";
103152     goto finish;
103153   }
103154   pTokenizer->pModule = p;
103155   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
103156     zErr = "error in xOpen()";
103157     goto finish;
103158   }
103159   pCsr->pTokenizer = pTokenizer;
103160
103161   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
103162     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
103163     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
103164     zToken = &zInput[iStart];
103165     nToken = iEnd-iStart;
103166     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
103167   }
103168
103169   if( SQLITE_OK!=p->xClose(pCsr) ){
103170     zErr = "error in xClose()";
103171     goto finish;
103172   }
103173   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
103174     zErr = "error in xDestroy()";
103175     goto finish;
103176   }
103177
103178 finish:
103179   if( zErr ){
103180     sqlite3_result_error(context, zErr, -1);
103181   }else{
103182     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
103183   }
103184   Tcl_DecrRefCount(pRet);
103185 }
103186
103187 static
103188 int registerTokenizer(
103189   sqlite3 *db, 
103190   char *zName, 
103191   const sqlite3_tokenizer_module *p
103192 ){
103193   int rc;
103194   sqlite3_stmt *pStmt;
103195   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
103196
103197   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
103198   if( rc!=SQLITE_OK ){
103199     return rc;
103200   }
103201
103202   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
103203   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
103204   sqlite3_step(pStmt);
103205
103206   return sqlite3_finalize(pStmt);
103207 }
103208
103209 static
103210 int queryTokenizer(
103211   sqlite3 *db, 
103212   char *zName,  
103213   const sqlite3_tokenizer_module **pp
103214 ){
103215   int rc;
103216   sqlite3_stmt *pStmt;
103217   const char zSql[] = "SELECT fts3_tokenizer(?)";
103218
103219   *pp = 0;
103220   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
103221   if( rc!=SQLITE_OK ){
103222     return rc;
103223   }
103224
103225   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
103226   if( SQLITE_ROW==sqlite3_step(pStmt) ){
103227     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
103228       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
103229     }
103230   }
103231
103232   return sqlite3_finalize(pStmt);
103233 }
103234
103235 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
103236
103237 /*
103238 ** Implementation of the scalar function fts3_tokenizer_internal_test().
103239 ** This function is used for testing only, it is not included in the
103240 ** build unless SQLITE_TEST is defined.
103241 **
103242 ** The purpose of this is to test that the fts3_tokenizer() function
103243 ** can be used as designed by the C-code in the queryTokenizer and
103244 ** registerTokenizer() functions above. These two functions are repeated
103245 ** in the README.tokenizer file as an example, so it is important to
103246 ** test them.
103247 **
103248 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
103249 ** function with no arguments. An assert() will fail if a problem is
103250 ** detected. i.e.:
103251 **
103252 **     SELECT fts3_tokenizer_internal_test();
103253 **
103254 */
103255 static void intTestFunc(
103256   sqlite3_context *context,
103257   int argc,
103258   sqlite3_value **argv
103259 ){
103260   int rc;
103261   const sqlite3_tokenizer_module *p1;
103262   const sqlite3_tokenizer_module *p2;
103263   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
103264
103265   UNUSED_PARAMETER(argc);
103266   UNUSED_PARAMETER(argv);
103267
103268   /* Test the query function */
103269   sqlite3Fts3SimpleTokenizerModule(&p1);
103270   rc = queryTokenizer(db, "simple", &p2);
103271   assert( rc==SQLITE_OK );
103272   assert( p1==p2 );
103273   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
103274   assert( rc==SQLITE_ERROR );
103275   assert( p2==0 );
103276   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
103277
103278   /* Test the storage function */
103279   rc = registerTokenizer(db, "nosuchtokenizer", p1);
103280   assert( rc==SQLITE_OK );
103281   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
103282   assert( rc==SQLITE_OK );
103283   assert( p2==p1 );
103284
103285   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
103286 }
103287
103288 #endif
103289
103290 /*
103291 ** Set up SQL objects in database db used to access the contents of
103292 ** the hash table pointed to by argument pHash. The hash table must
103293 ** been initialised to use string keys, and to take a private copy 
103294 ** of the key when a value is inserted. i.e. by a call similar to:
103295 **
103296 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
103297 **
103298 ** This function adds a scalar function (see header comment above
103299 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
103300 ** defined at compilation time, a temporary virtual table (see header 
103301 ** comment above struct HashTableVtab) to the database schema. Both 
103302 ** provide read/write access to the contents of *pHash.
103303 **
103304 ** The third argument to this function, zName, is used as the name
103305 ** of both the scalar and, if created, the virtual table.
103306 */
103307 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
103308   sqlite3 *db, 
103309   Fts3Hash *pHash, 
103310   const char *zName
103311 ){
103312   int rc = SQLITE_OK;
103313   void *p = (void *)pHash;
103314   const int any = SQLITE_ANY;
103315
103316 #ifdef SQLITE_TEST
103317   char *zTest = 0;
103318   char *zTest2 = 0;
103319   void *pdb = (void *)db;
103320   zTest = sqlite3_mprintf("%s_test", zName);
103321   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
103322   if( !zTest || !zTest2 ){
103323     rc = SQLITE_NOMEM;
103324   }
103325 #endif
103326
103327   if( SQLITE_OK!=rc
103328    || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
103329    || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
103330 #ifdef SQLITE_TEST
103331    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
103332    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
103333    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
103334 #endif
103335    );
103336
103337 #ifdef SQLITE_TEST
103338   sqlite3_free(zTest);
103339   sqlite3_free(zTest2);
103340 #endif
103341
103342   return rc;
103343 }
103344
103345 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
103346
103347 /************** End of fts3_tokenizer.c **************************************/
103348 /************** Begin file fts3_tokenizer1.c *********************************/
103349 /*
103350 ** 2006 Oct 10
103351 **
103352 ** The author disclaims copyright to this source code.  In place of
103353 ** a legal notice, here is a blessing:
103354 **
103355 **    May you do good and not evil.
103356 **    May you find forgiveness for yourself and forgive others.
103357 **    May you share freely, never taking more than you give.
103358 **
103359 ******************************************************************************
103360 **
103361 ** Implementation of the "simple" full-text-search tokenizer.
103362 */
103363
103364 /*
103365 ** The code in this file is only compiled if:
103366 **
103367 **     * The FTS3 module is being built as an extension
103368 **       (in which case SQLITE_CORE is not defined), or
103369 **
103370 **     * The FTS3 module is being built into the core of
103371 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
103372 */
103373 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
103374
103375
103376
103377
103378 typedef struct simple_tokenizer {
103379   sqlite3_tokenizer base;
103380   char delim[128];             /* flag ASCII delimiters */
103381 } simple_tokenizer;
103382
103383 typedef struct simple_tokenizer_cursor {
103384   sqlite3_tokenizer_cursor base;
103385   const char *pInput;          /* input we are tokenizing */
103386   int nBytes;                  /* size of the input */
103387   int iOffset;                 /* current position in pInput */
103388   int iToken;                  /* index of next token to be returned */
103389   char *pToken;                /* storage for current token */
103390   int nTokenAllocated;         /* space allocated to zToken buffer */
103391 } simple_tokenizer_cursor;
103392
103393
103394 static int simpleDelim(simple_tokenizer *t, unsigned char c){
103395   return c<0x80 && t->delim[c];
103396 }
103397
103398 /*
103399 ** Create a new tokenizer instance.
103400 */
103401 static int simpleCreate(
103402   int argc, const char * const *argv,
103403   sqlite3_tokenizer **ppTokenizer
103404 ){
103405   simple_tokenizer *t;
103406
103407   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
103408   if( t==NULL ) return SQLITE_NOMEM;
103409   memset(t, 0, sizeof(*t));
103410
103411   /* TODO(shess) Delimiters need to remain the same from run to run,
103412   ** else we need to reindex.  One solution would be a meta-table to
103413   ** track such information in the database, then we'd only want this
103414   ** information on the initial create.
103415   */
103416   if( argc>1 ){
103417     int i, n = (int)strlen(argv[1]);
103418     for(i=0; i<n; i++){
103419       unsigned char ch = argv[1][i];
103420       /* We explicitly don't support UTF-8 delimiters for now. */
103421       if( ch>=0x80 ){
103422         sqlite3_free(t);
103423         return SQLITE_ERROR;
103424       }
103425       t->delim[ch] = 1;
103426     }
103427   } else {
103428     /* Mark non-alphanumeric ASCII characters as delimiters */
103429     int i;
103430     for(i=1; i<0x80; i++){
103431       t->delim[i] = !isalnum(i) ? -1 : 0;
103432     }
103433   }
103434
103435   *ppTokenizer = &t->base;
103436   return SQLITE_OK;
103437 }
103438
103439 /*
103440 ** Destroy a tokenizer
103441 */
103442 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
103443   sqlite3_free(pTokenizer);
103444   return SQLITE_OK;
103445 }
103446
103447 /*
103448 ** Prepare to begin tokenizing a particular string.  The input
103449 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
103450 ** used to incrementally tokenize this string is returned in 
103451 ** *ppCursor.
103452 */
103453 static int simpleOpen(
103454   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
103455   const char *pInput, int nBytes,        /* String to be tokenized */
103456   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
103457 ){
103458   simple_tokenizer_cursor *c;
103459
103460   UNUSED_PARAMETER(pTokenizer);
103461
103462   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
103463   if( c==NULL ) return SQLITE_NOMEM;
103464
103465   c->pInput = pInput;
103466   if( pInput==0 ){
103467     c->nBytes = 0;
103468   }else if( nBytes<0 ){
103469     c->nBytes = (int)strlen(pInput);
103470   }else{
103471     c->nBytes = nBytes;
103472   }
103473   c->iOffset = 0;                 /* start tokenizing at the beginning */
103474   c->iToken = 0;
103475   c->pToken = NULL;               /* no space allocated, yet. */
103476   c->nTokenAllocated = 0;
103477
103478   *ppCursor = &c->base;
103479   return SQLITE_OK;
103480 }
103481
103482 /*
103483 ** Close a tokenization cursor previously opened by a call to
103484 ** simpleOpen() above.
103485 */
103486 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
103487   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
103488   sqlite3_free(c->pToken);
103489   sqlite3_free(c);
103490   return SQLITE_OK;
103491 }
103492
103493 /*
103494 ** Extract the next token from a tokenization cursor.  The cursor must
103495 ** have been opened by a prior call to simpleOpen().
103496 */
103497 static int simpleNext(
103498   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
103499   const char **ppToken,               /* OUT: *ppToken is the token text */
103500   int *pnBytes,                       /* OUT: Number of bytes in token */
103501   int *piStartOffset,                 /* OUT: Starting offset of token */
103502   int *piEndOffset,                   /* OUT: Ending offset of token */
103503   int *piPosition                     /* OUT: Position integer of token */
103504 ){
103505   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
103506   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
103507   unsigned char *p = (unsigned char *)c->pInput;
103508
103509   while( c->iOffset<c->nBytes ){
103510     int iStartOffset;
103511
103512     /* Scan past delimiter characters */
103513     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
103514       c->iOffset++;
103515     }
103516
103517     /* Count non-delimiter characters. */
103518     iStartOffset = c->iOffset;
103519     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
103520       c->iOffset++;
103521     }
103522
103523     if( c->iOffset>iStartOffset ){
103524       int i, n = c->iOffset-iStartOffset;
103525       if( n>c->nTokenAllocated ){
103526         c->nTokenAllocated = n+20;
103527         c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
103528         if( c->pToken==NULL ) return SQLITE_NOMEM;
103529       }
103530       for(i=0; i<n; i++){
103531         /* TODO(shess) This needs expansion to handle UTF-8
103532         ** case-insensitivity.
103533         */
103534         unsigned char ch = p[iStartOffset+i];
103535         c->pToken[i] = (char)(ch<0x80 ? tolower(ch) : ch);
103536       }
103537       *ppToken = c->pToken;
103538       *pnBytes = n;
103539       *piStartOffset = iStartOffset;
103540       *piEndOffset = c->iOffset;
103541       *piPosition = c->iToken++;
103542
103543       return SQLITE_OK;
103544     }
103545   }
103546   return SQLITE_DONE;
103547 }
103548
103549 /*
103550 ** The set of routines that implement the simple tokenizer
103551 */
103552 static const sqlite3_tokenizer_module simpleTokenizerModule = {
103553   0,
103554   simpleCreate,
103555   simpleDestroy,
103556   simpleOpen,
103557   simpleClose,
103558   simpleNext,
103559 };
103560
103561 /*
103562 ** Allocate a new simple tokenizer.  Return a pointer to the new
103563 ** tokenizer in *ppModule
103564 */
103565 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
103566   sqlite3_tokenizer_module const**ppModule
103567 ){
103568   *ppModule = &simpleTokenizerModule;
103569 }
103570
103571 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
103572
103573 /************** End of fts3_tokenizer1.c *************************************/
103574 /************** Begin file fts3_write.c **************************************/
103575 /*
103576 ** 2009 Oct 23
103577 **
103578 ** The author disclaims copyright to this source code.  In place of
103579 ** a legal notice, here is a blessing:
103580 **
103581 **    May you do good and not evil.
103582 **    May you find forgiveness for yourself and forgive others.
103583 **    May you share freely, never taking more than you give.
103584 **
103585 ******************************************************************************
103586 **
103587 ** This file is part of the SQLite FTS3 extension module. Specifically,
103588 ** this file contains code to insert, update and delete rows from FTS3
103589 ** tables. It also contains code to merge FTS3 b-tree segments. Some
103590 ** of the sub-routines used to merge segments are also used by the query 
103591 ** code in fts3.c.
103592 */
103593
103594 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
103595
103596
103597 typedef struct PendingList PendingList;
103598 typedef struct SegmentNode SegmentNode;
103599 typedef struct SegmentWriter SegmentWriter;
103600
103601 /*
103602 ** Data structure used while accumulating terms in the pending-terms hash
103603 ** table. The hash table entry maps from term (a string) to a malloc'd
103604 ** instance of this structure.
103605 */
103606 struct PendingList {
103607   int nData;
103608   char *aData;
103609   int nSpace;
103610   sqlite3_int64 iLastDocid;
103611   sqlite3_int64 iLastCol;
103612   sqlite3_int64 iLastPos;
103613 };
103614
103615 /*
103616 ** An instance of this structure is used to iterate through the terms on
103617 ** a contiguous set of segment b-tree leaf nodes. Although the details of
103618 ** this structure are only manipulated by code in this file, opaque handles
103619 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
103620 ** terms when querying the full-text index. See functions:
103621 **
103622 **   sqlite3Fts3SegReaderNew()
103623 **   sqlite3Fts3SegReaderFree()
103624 **   sqlite3Fts3SegReaderIterate()
103625 **
103626 ** Methods used to manipulate Fts3SegReader structures:
103627 **
103628 **   fts3SegReaderNext()
103629 **   fts3SegReaderFirstDocid()
103630 **   fts3SegReaderNextDocid()
103631 */
103632 struct Fts3SegReader {
103633   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
103634   sqlite3_int64 iStartBlock;
103635   sqlite3_int64 iEndBlock;
103636   sqlite3_stmt *pStmt;            /* SQL Statement to access leaf nodes */
103637   char *aNode;                    /* Pointer to node data (or NULL) */
103638   int nNode;                      /* Size of buffer at aNode (or 0) */
103639   int nTermAlloc;                 /* Allocated size of zTerm buffer */
103640   Fts3HashElem **ppNextElem;
103641
103642   /* Variables set by fts3SegReaderNext(). These may be read directly
103643   ** by the caller. They are valid from the time SegmentReaderNew() returns
103644   ** until SegmentReaderNext() returns something other than SQLITE_OK
103645   ** (i.e. SQLITE_DONE).
103646   */
103647   int nTerm;                      /* Number of bytes in current term */
103648   char *zTerm;                    /* Pointer to current term */
103649   char *aDoclist;                 /* Pointer to doclist of current entry */
103650   int nDoclist;                   /* Size of doclist in current entry */
103651
103652   /* The following variables are used to iterate through the current doclist */
103653   char *pOffsetList;
103654   sqlite3_int64 iDocid;
103655 };
103656
103657 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
103658
103659 /*
103660 ** An instance of this structure is used to create a segment b-tree in the
103661 ** database. The internal details of this type are only accessed by the
103662 ** following functions:
103663 **
103664 **   fts3SegWriterAdd()
103665 **   fts3SegWriterFlush()
103666 **   fts3SegWriterFree()
103667 */
103668 struct SegmentWriter {
103669   SegmentNode *pTree;             /* Pointer to interior tree structure */
103670   sqlite3_int64 iFirst;           /* First slot in %_segments written */
103671   sqlite3_int64 iFree;            /* Next free slot in %_segments */
103672   char *zTerm;                    /* Pointer to previous term buffer */
103673   int nTerm;                      /* Number of bytes in zTerm */
103674   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
103675   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
103676   int nSize;                      /* Size of allocation at aData */
103677   int nData;                      /* Bytes of data in aData */
103678   char *aData;                    /* Pointer to block from malloc() */
103679 };
103680
103681 /*
103682 ** Type SegmentNode is used by the following three functions to create
103683 ** the interior part of the segment b+-tree structures (everything except
103684 ** the leaf nodes). These functions and type are only ever used by code
103685 ** within the fts3SegWriterXXX() family of functions described above.
103686 **
103687 **   fts3NodeAddTerm()
103688 **   fts3NodeWrite()
103689 **   fts3NodeFree()
103690 */
103691 struct SegmentNode {
103692   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
103693   SegmentNode *pRight;            /* Pointer to right-sibling */
103694   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
103695   int nEntry;                     /* Number of terms written to node so far */
103696   char *zTerm;                    /* Pointer to previous term buffer */
103697   int nTerm;                      /* Number of bytes in zTerm */
103698   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
103699   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
103700   int nData;                      /* Bytes of valid data so far */
103701   char *aData;                    /* Node data */
103702 };
103703
103704 /*
103705 ** Valid values for the second argument to fts3SqlStmt().
103706 */
103707 #define SQL_DELETE_CONTENT             0
103708 #define SQL_IS_EMPTY                   1
103709 #define SQL_DELETE_ALL_CONTENT         2 
103710 #define SQL_DELETE_ALL_SEGMENTS        3
103711 #define SQL_DELETE_ALL_SEGDIR          4
103712 #define SQL_SELECT_CONTENT_BY_ROWID    5
103713 #define SQL_NEXT_SEGMENT_INDEX         6
103714 #define SQL_INSERT_SEGMENTS            7
103715 #define SQL_NEXT_SEGMENTS_ID           8
103716 #define SQL_INSERT_SEGDIR              9
103717 #define SQL_SELECT_LEVEL              10
103718 #define SQL_SELECT_ALL_LEVEL          11
103719 #define SQL_SELECT_LEVEL_COUNT        12
103720 #define SQL_SELECT_SEGDIR_COUNT_MAX   13
103721 #define SQL_DELETE_SEGDIR_BY_LEVEL    14
103722 #define SQL_DELETE_SEGMENTS_RANGE     15
103723 #define SQL_CONTENT_INSERT            16
103724 #define SQL_GET_BLOCK                 17
103725
103726 /*
103727 ** This function is used to obtain an SQLite prepared statement handle
103728 ** for the statement identified by the second argument. If successful,
103729 ** *pp is set to the requested statement handle and SQLITE_OK returned.
103730 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
103731 **
103732 ** If argument apVal is not NULL, then it must point to an array with
103733 ** at least as many entries as the requested statement has bound 
103734 ** parameters. The values are bound to the statements parameters before
103735 ** returning.
103736 */
103737 static int fts3SqlStmt(
103738   Fts3Table *p,                   /* Virtual table handle */
103739   int eStmt,                      /* One of the SQL_XXX constants above */
103740   sqlite3_stmt **pp,              /* OUT: Statement handle */
103741   sqlite3_value **apVal           /* Values to bind to statement */
103742 ){
103743   const char *azSql[] = {
103744 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
103745 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
103746 /* 2  */  "DELETE FROM %Q.'%q_content'",
103747 /* 3  */  "DELETE FROM %Q.'%q_segments'",
103748 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
103749 /* 5  */  "SELECT * FROM %Q.'%q_content' WHERE rowid=?",
103750 /* 6  */  "SELECT coalesce(max(idx)+1, 0) FROM %Q.'%q_segdir' WHERE level=?",
103751 /* 7  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
103752 /* 8  */  "SELECT coalesce(max(blockid)+1, 1) FROM %Q.'%q_segments'",
103753 /* 9  */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
103754
103755           /* Return segments in order from oldest to newest.*/ 
103756 /* 10 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
103757             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
103758 /* 11 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
103759             "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
103760
103761 /* 12 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
103762 /* 13 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
103763
103764 /* 14 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
103765 /* 15 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
103766 /* 16 */  "INSERT INTO %Q.'%q_content' VALUES(%z)",
103767 /* 17 */  "SELECT block FROM %Q.'%q_segments' WHERE blockid = ?",
103768   };
103769   int rc = SQLITE_OK;
103770   sqlite3_stmt *pStmt;
103771
103772   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
103773   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
103774   
103775   pStmt = p->aStmt[eStmt];
103776   if( !pStmt ){
103777     char *zSql;
103778     if( eStmt==SQL_CONTENT_INSERT ){
103779       int i;                      /* Iterator variable */  
103780       char *zVarlist;             /* The "?, ?, ..." string */
103781       zVarlist = (char *)sqlite3_malloc(2*p->nColumn+2);
103782       if( !zVarlist ){
103783         *pp = 0;
103784         return SQLITE_NOMEM;
103785       }
103786       zVarlist[0] = '?';
103787       zVarlist[p->nColumn*2+1] = '\0';
103788       for(i=1; i<=p->nColumn; i++){
103789         zVarlist[i*2-1] = ',';
103790         zVarlist[i*2] = '?';
103791       }
103792       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, zVarlist);
103793     }else{
103794       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
103795     }
103796     if( !zSql ){
103797       rc = SQLITE_NOMEM;
103798     }else{
103799       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
103800       sqlite3_free(zSql);
103801       assert( rc==SQLITE_OK || pStmt==0 );
103802       p->aStmt[eStmt] = pStmt;
103803     }
103804   }
103805   if( apVal ){
103806     int i;
103807     int nParam = sqlite3_bind_parameter_count(pStmt);
103808     for(i=0; rc==SQLITE_OK && i<nParam; i++){
103809       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
103810     }
103811   }
103812   *pp = pStmt;
103813   return rc;
103814 }
103815
103816 /*
103817 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
103818 ** array apVal[] to the SQL statement identified by eStmt, the statement
103819 ** is executed.
103820 **
103821 ** Returns SQLITE_OK if the statement is successfully executed, or an
103822 ** SQLite error code otherwise.
103823 */
103824 static int fts3SqlExec(Fts3Table *p, int eStmt, sqlite3_value **apVal){
103825   sqlite3_stmt *pStmt;
103826   int rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
103827   if( rc==SQLITE_OK ){
103828     sqlite3_step(pStmt);
103829     rc = sqlite3_reset(pStmt);
103830   }
103831   return rc;
103832 }
103833
103834
103835 /*
103836 ** Read a single block from the %_segments table. If the specified block
103837 ** does not exist, return SQLITE_CORRUPT. If some other error (malloc, IO 
103838 ** etc.) occurs, return the appropriate SQLite error code.
103839 **
103840 ** Otherwise, if successful, set *pzBlock to point to a buffer containing
103841 ** the block read from the database, and *pnBlock to the size of the read
103842 ** block in bytes.
103843 **
103844 ** WARNING: The returned buffer is only valid until the next call to 
103845 ** sqlite3Fts3ReadBlock().
103846 */
103847 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
103848   Fts3Table *p,
103849   sqlite3_int64 iBlock,
103850   char const **pzBlock,
103851   int *pnBlock
103852 ){
103853   sqlite3_stmt *pStmt;
103854   int rc = fts3SqlStmt(p, SQL_GET_BLOCK, &pStmt, 0);
103855   if( rc!=SQLITE_OK ) return rc;
103856   sqlite3_reset(pStmt);
103857
103858   if( pzBlock ){
103859     sqlite3_bind_int64(pStmt, 1, iBlock);
103860     rc = sqlite3_step(pStmt); 
103861     if( rc!=SQLITE_ROW ){
103862       return (rc==SQLITE_DONE ? SQLITE_CORRUPT : rc);
103863     }
103864   
103865     *pnBlock = sqlite3_column_bytes(pStmt, 0);
103866     *pzBlock = (char *)sqlite3_column_blob(pStmt, 0);
103867     if( sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
103868       return SQLITE_CORRUPT;
103869     }
103870   }
103871   return SQLITE_OK;
103872 }
103873
103874 /*
103875 ** Set *ppStmt to a statement handle that may be used to iterate through
103876 ** all rows in the %_segdir table, from oldest to newest. If successful,
103877 ** return SQLITE_OK. If an error occurs while preparing the statement, 
103878 ** return an SQLite error code.
103879 **
103880 ** There is only ever one instance of this SQL statement compiled for
103881 ** each FTS3 table.
103882 **
103883 ** The statement returns the following columns from the %_segdir table:
103884 **
103885 **   0: idx
103886 **   1: start_block
103887 **   2: leaves_end_block
103888 **   3: end_block
103889 **   4: root
103890 */
103891 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, sqlite3_stmt **ppStmt){
103892   return fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, ppStmt, 0);
103893 }
103894
103895
103896 /*
103897 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
103898 ** if successful, or an SQLite error code otherwise.
103899 **
103900 ** This function also serves to allocate the PendingList structure itself.
103901 ** For example, to create a new PendingList structure containing two
103902 ** varints:
103903 **
103904 **   PendingList *p = 0;
103905 **   fts3PendingListAppendVarint(&p, 1);
103906 **   fts3PendingListAppendVarint(&p, 2);
103907 */
103908 static int fts3PendingListAppendVarint(
103909   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
103910   sqlite3_int64 i                 /* Value to append to data */
103911 ){
103912   PendingList *p = *pp;
103913
103914   /* Allocate or grow the PendingList as required. */
103915   if( !p ){
103916     p = sqlite3_malloc(sizeof(*p) + 100);
103917     if( !p ){
103918       return SQLITE_NOMEM;
103919     }
103920     p->nSpace = 100;
103921     p->aData = (char *)&p[1];
103922     p->nData = 0;
103923   }
103924   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
103925     int nNew = p->nSpace * 2;
103926     p = sqlite3_realloc(p, sizeof(*p) + nNew);
103927     if( !p ){
103928       sqlite3_free(*pp);
103929       *pp = 0;
103930       return SQLITE_NOMEM;
103931     }
103932     p->nSpace = nNew;
103933     p->aData = (char *)&p[1];
103934   }
103935
103936   /* Append the new serialized varint to the end of the list. */
103937   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
103938   p->aData[p->nData] = '\0';
103939   *pp = p;
103940   return SQLITE_OK;
103941 }
103942
103943 /*
103944 ** Add a docid/column/position entry to a PendingList structure. Non-zero
103945 ** is returned if the structure is sqlite3_realloced as part of adding
103946 ** the entry. Otherwise, zero.
103947 **
103948 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
103949 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
103950 ** it is set to SQLITE_OK.
103951 */
103952 static int fts3PendingListAppend(
103953   PendingList **pp,               /* IN/OUT: PendingList structure */
103954   sqlite3_int64 iDocid,           /* Docid for entry to add */
103955   sqlite3_int64 iCol,             /* Column for entry to add */
103956   sqlite3_int64 iPos,             /* Position of term for entry to add */
103957   int *pRc                        /* OUT: Return code */
103958 ){
103959   PendingList *p = *pp;
103960   int rc = SQLITE_OK;
103961
103962   assert( !p || p->iLastDocid<=iDocid );
103963
103964   if( !p || p->iLastDocid!=iDocid ){
103965     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
103966     if( p ){
103967       assert( p->nData<p->nSpace );
103968       assert( p->aData[p->nData]==0 );
103969       p->nData++;
103970     }
103971     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
103972       goto pendinglistappend_out;
103973     }
103974     p->iLastCol = -1;
103975     p->iLastPos = 0;
103976     p->iLastDocid = iDocid;
103977   }
103978   if( iCol>0 && p->iLastCol!=iCol ){
103979     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
103980      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
103981     ){
103982       goto pendinglistappend_out;
103983     }
103984     p->iLastCol = iCol;
103985     p->iLastPos = 0;
103986   }
103987   if( iCol>=0 ){
103988     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
103989     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
103990     if( rc==SQLITE_OK ){
103991       p->iLastPos = iPos;
103992     }
103993   }
103994
103995  pendinglistappend_out:
103996   *pRc = rc;
103997   if( p!=*pp ){
103998     *pp = p;
103999     return 1;
104000   }
104001   return 0;
104002 }
104003
104004 /*
104005 ** Tokenize the nul-terminated string zText and add all tokens to the
104006 ** pending-terms hash-table. The docid used is that currently stored in
104007 ** p->iPrevDocid, and the column is specified by argument iCol.
104008 **
104009 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
104010 */
104011 static int fts3PendingTermsAdd(Fts3Table *p, const char *zText, int iCol){
104012   int rc;
104013   int iStart;
104014   int iEnd;
104015   int iPos;
104016
104017   char const *zToken;
104018   int nToken;
104019
104020   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
104021   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
104022   sqlite3_tokenizer_cursor *pCsr;
104023   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
104024       const char**,int*,int*,int*,int*);
104025
104026   assert( pTokenizer && pModule );
104027
104028   rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
104029   if( rc!=SQLITE_OK ){
104030     return rc;
104031   }
104032   pCsr->pTokenizer = pTokenizer;
104033
104034   xNext = pModule->xNext;
104035   while( SQLITE_OK==rc
104036       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
104037   ){
104038     PendingList *pList;
104039
104040     /* Positions cannot be negative; we use -1 as a terminator internally.
104041     ** Tokens must have a non-zero length.
104042     */
104043     if( iPos<0 || !zToken || nToken<=0 ){
104044       rc = SQLITE_ERROR;
104045       break;
104046     }
104047
104048     pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
104049     if( pList ){
104050       p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
104051     }
104052     if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
104053       if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
104054         /* Malloc failed while inserting the new entry. This can only 
104055         ** happen if there was no previous entry for this token.
104056         */
104057         assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
104058         sqlite3_free(pList);
104059         rc = SQLITE_NOMEM;
104060       }
104061     }
104062     if( rc==SQLITE_OK ){
104063       p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
104064     }
104065   }
104066
104067   pModule->xClose(pCsr);
104068   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
104069 }
104070
104071 /* 
104072 ** Calling this function indicates that subsequent calls to 
104073 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
104074 ** contents of the document with docid iDocid.
104075 */
104076 static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
104077   /* TODO(shess) Explore whether partially flushing the buffer on
104078   ** forced-flush would provide better performance.  I suspect that if
104079   ** we ordered the doclists by size and flushed the largest until the
104080   ** buffer was half empty, that would let the less frequent terms
104081   ** generate longer doclists.
104082   */
104083   if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
104084     int rc = sqlite3Fts3PendingTermsFlush(p);
104085     if( rc!=SQLITE_OK ) return rc;
104086   }
104087   p->iPrevDocid = iDocid;
104088   return SQLITE_OK;
104089 }
104090
104091 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
104092   Fts3HashElem *pElem;
104093   for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
104094     sqlite3_free(fts3HashData(pElem));
104095   }
104096   fts3HashClear(&p->pendingTerms);
104097   p->nPendingData = 0;
104098 }
104099
104100 /*
104101 ** This function is called by the xUpdate() method as part of an INSERT
104102 ** operation. It adds entries for each term in the new record to the
104103 ** pendingTerms hash table.
104104 **
104105 ** Argument apVal is the same as the similarly named argument passed to
104106 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
104107 */
104108 static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal){
104109   int i;                          /* Iterator variable */
104110   for(i=2; i<p->nColumn+2; i++){
104111     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
104112     if( zText ){
104113       int rc = fts3PendingTermsAdd(p, zText, i-2);
104114       if( rc!=SQLITE_OK ){
104115         return rc;
104116       }
104117     }
104118   }
104119   return SQLITE_OK;
104120 }
104121
104122 /*
104123 ** This function is called by the xUpdate() method for an INSERT operation.
104124 ** The apVal parameter is passed a copy of the apVal argument passed by
104125 ** SQLite to the xUpdate() method. i.e:
104126 **
104127 **   apVal[0]                Not used for INSERT.
104128 **   apVal[1]                rowid
104129 **   apVal[2]                Left-most user-defined column
104130 **   ...
104131 **   apVal[p->nColumn+1]     Right-most user-defined column
104132 **   apVal[p->nColumn+2]     Hidden column with same name as table
104133 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
104134 */
104135 static int fts3InsertData(
104136   Fts3Table *p,                   /* Full-text table */
104137   sqlite3_value **apVal,          /* Array of values to insert */
104138   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
104139 ){
104140   int rc;                         /* Return code */
104141   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
104142
104143   /* Locate the statement handle used to insert data into the %_content
104144   ** table. The SQL for this statement is:
104145   **
104146   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
104147   **
104148   ** The statement features N '?' variables, where N is the number of user
104149   ** defined columns in the FTS3 table, plus one for the docid field.
104150   */
104151   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
104152   if( rc!=SQLITE_OK ){
104153     return rc;
104154   }
104155
104156   /* There is a quirk here. The users INSERT statement may have specified
104157   ** a value for the "rowid" field, for the "docid" field, or for both.
104158   ** Which is a problem, since "rowid" and "docid" are aliases for the
104159   ** same value. For example:
104160   **
104161   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
104162   **
104163   ** In FTS3, this is an error. It is an error to specify non-NULL values
104164   ** for both docid and some other rowid alias.
104165   */
104166   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
104167     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
104168      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
104169     ){
104170       /* A rowid/docid conflict. */
104171       return SQLITE_ERROR;
104172     }
104173     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
104174     if( rc!=SQLITE_OK ) return rc;
104175   }
104176
104177   /* Execute the statement to insert the record. Set *piDocid to the 
104178   ** new docid value. 
104179   */
104180   sqlite3_step(pContentInsert);
104181   rc = sqlite3_reset(pContentInsert);
104182
104183   *piDocid = sqlite3_last_insert_rowid(p->db);
104184   return rc;
104185 }
104186
104187
104188
104189 /*
104190 ** Remove all data from the FTS3 table. Clear the hash table containing
104191 ** pending terms.
104192 */
104193 static int fts3DeleteAll(Fts3Table *p){
104194   int rc;                         /* Return code */
104195
104196   /* Discard the contents of the pending-terms hash table. */
104197   sqlite3Fts3PendingTermsClear(p);
104198
104199   /* Delete everything from the %_content, %_segments and %_segdir tables. */
104200   rc = fts3SqlExec(p, SQL_DELETE_ALL_CONTENT, 0);
104201   if( rc==SQLITE_OK ){
104202     rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGMENTS, 0);
104203   }
104204   if( rc==SQLITE_OK ){
104205     rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGDIR, 0);
104206   }
104207   return rc;
104208 }
104209
104210 /*
104211 ** The first element in the apVal[] array is assumed to contain the docid
104212 ** (an integer) of a row about to be deleted. Remove all terms from the
104213 ** full-text index.
104214 */
104215 static int fts3DeleteTerms(Fts3Table *p, sqlite3_value **apVal){
104216   int rc;
104217   sqlite3_stmt *pSelect;
104218
104219   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
104220   if( rc==SQLITE_OK ){
104221     if( SQLITE_ROW==sqlite3_step(pSelect) ){
104222       int i;
104223       for(i=1; i<=p->nColumn; i++){
104224         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
104225         rc = fts3PendingTermsAdd(p, zText, -1);
104226         if( rc!=SQLITE_OK ){
104227           sqlite3_reset(pSelect);
104228           return rc;
104229         }
104230       }
104231     }
104232     rc = sqlite3_reset(pSelect);
104233   }else{
104234     sqlite3_reset(pSelect);
104235   }
104236   return rc;
104237 }
104238
104239 /*
104240 ** Forward declaration to account for the circular dependency between
104241 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
104242 */
104243 static int fts3SegmentMerge(Fts3Table *, int);
104244
104245 /* 
104246 ** This function allocates a new level iLevel index in the segdir table.
104247 ** Usually, indexes are allocated within a level sequentially starting
104248 ** with 0, so the allocated index is one greater than the value returned
104249 ** by:
104250 **
104251 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
104252 **
104253 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
104254 ** level, they are merged into a single level (iLevel+1) segment and the 
104255 ** allocated index is 0.
104256 **
104257 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
104258 ** returned. Otherwise, an SQLite error code is returned.
104259 */
104260 static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
104261   int rc;                         /* Return Code */
104262   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
104263   int iNext = 0;                  /* Result of query pNextIdx */
104264
104265   /* Set variable iNext to the next available segdir index at level iLevel. */
104266   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
104267   if( rc==SQLITE_OK ){
104268     sqlite3_bind_int(pNextIdx, 1, iLevel);
104269     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
104270       iNext = sqlite3_column_int(pNextIdx, 0);
104271     }
104272     rc = sqlite3_reset(pNextIdx);
104273   }
104274
104275   if( rc==SQLITE_OK ){
104276     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
104277     ** full, merge all segments in level iLevel into a single iLevel+1
104278     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
104279     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
104280     */
104281     if( iNext>=FTS3_MERGE_COUNT ){
104282       rc = fts3SegmentMerge(p, iLevel);
104283       *piIdx = 0;
104284     }else{
104285       *piIdx = iNext;
104286     }
104287   }
104288
104289   return rc;
104290 }
104291
104292 /*
104293 ** Move the iterator passed as the first argument to the next term in the
104294 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
104295 ** SQLITE_DONE. Otherwise, an SQLite error code.
104296 */
104297 static int fts3SegReaderNext(Fts3SegReader *pReader){
104298   char *pNext;                    /* Cursor variable */
104299   int nPrefix;                    /* Number of bytes in term prefix */
104300   int nSuffix;                    /* Number of bytes in term suffix */
104301
104302   if( !pReader->aDoclist ){
104303     pNext = pReader->aNode;
104304   }else{
104305     pNext = &pReader->aDoclist[pReader->nDoclist];
104306   }
104307
104308   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
104309     int rc;
104310     if( fts3SegReaderIsPending(pReader) ){
104311       Fts3HashElem *pElem = *(pReader->ppNextElem);
104312       if( pElem==0 ){
104313         pReader->aNode = 0;
104314       }else{
104315         PendingList *pList = (PendingList *)fts3HashData(pElem);
104316         pReader->zTerm = (char *)fts3HashKey(pElem);
104317         pReader->nTerm = fts3HashKeysize(pElem);
104318         pReader->nNode = pReader->nDoclist = pList->nData + 1;
104319         pReader->aNode = pReader->aDoclist = pList->aData;
104320         pReader->ppNextElem++;
104321         assert( pReader->aNode );
104322       }
104323       return SQLITE_OK;
104324     }
104325     if( !pReader->pStmt ){
104326       pReader->aNode = 0;
104327       return SQLITE_OK;
104328     }
104329     rc = sqlite3_step(pReader->pStmt);
104330     if( rc!=SQLITE_ROW ){
104331       pReader->aNode = 0;
104332       return (rc==SQLITE_DONE ? SQLITE_OK : rc);
104333     }
104334     pReader->nNode = sqlite3_column_bytes(pReader->pStmt, 0);
104335     pReader->aNode = (char *)sqlite3_column_blob(pReader->pStmt, 0);
104336     pNext = pReader->aNode;
104337   }
104338   
104339   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
104340   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
104341
104342   if( nPrefix+nSuffix>pReader->nTermAlloc ){
104343     int nNew = (nPrefix+nSuffix)*2;
104344     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
104345     if( !zNew ){
104346       return SQLITE_NOMEM;
104347     }
104348     pReader->zTerm = zNew;
104349     pReader->nTermAlloc = nNew;
104350   }
104351   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
104352   pReader->nTerm = nPrefix+nSuffix;
104353   pNext += nSuffix;
104354   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
104355   assert( pNext<&pReader->aNode[pReader->nNode] );
104356   pReader->aDoclist = pNext;
104357   pReader->pOffsetList = 0;
104358   return SQLITE_OK;
104359 }
104360
104361 /*
104362 ** Set the SegReader to point to the first docid in the doclist associated
104363 ** with the current term.
104364 */
104365 static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
104366   int n;
104367   assert( pReader->aDoclist );
104368   assert( !pReader->pOffsetList );
104369   n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
104370   pReader->pOffsetList = &pReader->aDoclist[n];
104371 }
104372
104373 /*
104374 ** Advance the SegReader to point to the next docid in the doclist
104375 ** associated with the current term.
104376 ** 
104377 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
104378 ** *ppOffsetList is set to point to the first column-offset list
104379 ** in the doclist entry (i.e. immediately past the docid varint).
104380 ** *pnOffsetList is set to the length of the set of column-offset
104381 ** lists, not including the nul-terminator byte. For example:
104382 */
104383 static void fts3SegReaderNextDocid(
104384   Fts3SegReader *pReader,
104385   char **ppOffsetList,
104386   int *pnOffsetList
104387 ){
104388   char *p = pReader->pOffsetList;
104389   char c = 0;
104390
104391   /* Pointer p currently points at the first byte of an offset list. The
104392   ** following two lines advance it to point one byte past the end of
104393   ** the same offset list.
104394   */
104395   while( *p | c ) c = *p++ & 0x80;
104396   p++;
104397
104398   /* If required, populate the output variables with a pointer to and the
104399   ** size of the previous offset-list.
104400   */
104401   if( ppOffsetList ){
104402     *ppOffsetList = pReader->pOffsetList;
104403     *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
104404   }
104405
104406   /* If there are no more entries in the doclist, set pOffsetList to
104407   ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
104408   ** Fts3SegReader.pOffsetList to point to the next offset list before
104409   ** returning.
104410   */
104411   if( p>=&pReader->aDoclist[pReader->nDoclist] ){
104412     pReader->pOffsetList = 0;
104413   }else{
104414     sqlite3_int64 iDelta;
104415     pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
104416     pReader->iDocid += iDelta;
104417   }
104418 }
104419
104420 /*
104421 ** Free all allocations associated with the iterator passed as the 
104422 ** second argument.
104423 */
104424 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *p, Fts3SegReader *pReader){
104425   if( pReader ){
104426     if( pReader->pStmt ){
104427       /* Move the leaf-range SELECT statement to the aLeavesStmt[] array,
104428       ** so that it can be reused when required by another query.
104429       */
104430       assert( p->nLeavesStmt<p->nLeavesTotal );
104431       sqlite3_reset(pReader->pStmt);
104432       p->aLeavesStmt[p->nLeavesStmt++] = pReader->pStmt;
104433     }
104434     if( !fts3SegReaderIsPending(pReader) ){
104435       sqlite3_free(pReader->zTerm);
104436     }
104437     sqlite3_free(pReader);
104438   }
104439 }
104440
104441 /*
104442 ** Allocate a new SegReader object.
104443 */
104444 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
104445   Fts3Table *p,                   /* Virtual table handle */
104446   int iAge,                       /* Segment "age". */
104447   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
104448   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
104449   sqlite3_int64 iEndBlock,        /* Final block of segment */
104450   const char *zRoot,              /* Buffer containing root node */
104451   int nRoot,                      /* Size of buffer containing root node */
104452   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
104453 ){
104454   int rc = SQLITE_OK;             /* Return code */
104455   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
104456   int nExtra = 0;                 /* Bytes to allocate segment root node */
104457
104458   if( iStartLeaf==0 ){
104459     nExtra = nRoot;
104460   }
104461
104462   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
104463   if( !pReader ){
104464     return SQLITE_NOMEM;
104465   }
104466   memset(pReader, 0, sizeof(Fts3SegReader));
104467   pReader->iStartBlock = iStartLeaf;
104468   pReader->iIdx = iAge;
104469   pReader->iEndBlock = iEndBlock;
104470
104471   if( nExtra ){
104472     /* The entire segment is stored in the root node. */
104473     pReader->aNode = (char *)&pReader[1];
104474     pReader->nNode = nRoot;
104475     memcpy(pReader->aNode, zRoot, nRoot);
104476   }else{
104477     /* If the text of the SQL statement to iterate through a contiguous
104478     ** set of entries in the %_segments table has not yet been composed,
104479     ** compose it now.
104480     */
104481     if( !p->zSelectLeaves ){
104482       p->zSelectLeaves = sqlite3_mprintf(
104483           "SELECT block FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ? "
104484           "ORDER BY blockid", p->zDb, p->zName
104485       );
104486       if( !p->zSelectLeaves ){
104487         rc = SQLITE_NOMEM;
104488         goto finished;
104489       }
104490     }
104491
104492     /* If there are no free statements in the aLeavesStmt[] array, prepare
104493     ** a new statement now. Otherwise, reuse a prepared statement from
104494     ** aLeavesStmt[].
104495     */
104496     if( p->nLeavesStmt==0 ){
104497       if( p->nLeavesTotal==p->nLeavesAlloc ){
104498         int nNew = p->nLeavesAlloc + 16;
104499         sqlite3_stmt **aNew = (sqlite3_stmt **)sqlite3_realloc(
104500             p->aLeavesStmt, nNew*sizeof(sqlite3_stmt *)
104501         );
104502         if( !aNew ){
104503           rc = SQLITE_NOMEM;
104504           goto finished;
104505         }
104506         p->nLeavesAlloc = nNew;
104507         p->aLeavesStmt = aNew;
104508       }
104509       rc = sqlite3_prepare_v2(p->db, p->zSelectLeaves, -1, &pReader->pStmt, 0);
104510       if( rc!=SQLITE_OK ){
104511         goto finished;
104512       }
104513       p->nLeavesTotal++;
104514     }else{
104515       pReader->pStmt = p->aLeavesStmt[--p->nLeavesStmt];
104516     }
104517
104518     /* Bind the start and end leaf blockids to the prepared SQL statement. */
104519     sqlite3_bind_int64(pReader->pStmt, 1, iStartLeaf);
104520     sqlite3_bind_int64(pReader->pStmt, 2, iEndLeaf);
104521   }
104522   rc = fts3SegReaderNext(pReader);
104523
104524  finished:
104525   if( rc==SQLITE_OK ){
104526     *ppReader = pReader;
104527   }else{
104528     sqlite3Fts3SegReaderFree(p, pReader);
104529   }
104530   return rc;
104531 }
104532
104533 /*
104534 ** This is a comparison function used as a qsort() callback when sorting
104535 ** an array of pending terms by term. This occurs as part of flushing
104536 ** the contents of the pending-terms hash table to the database.
104537 */
104538 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
104539   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
104540   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
104541   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
104542   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
104543
104544   int n = (n1<n2 ? n1 : n2);
104545   int c = memcmp(z1, z2, n);
104546   if( c==0 ){
104547     c = n1 - n2;
104548   }
104549   return c;
104550 }
104551
104552 /*
104553 ** This function is used to allocate an Fts3SegReader that iterates through
104554 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
104555 */
104556 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
104557   Fts3Table *p,                   /* Virtual table handle */
104558   const char *zTerm,              /* Term to search for */
104559   int nTerm,                      /* Size of buffer zTerm */
104560   int isPrefix,                   /* True for a term-prefix query */
104561   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
104562 ){
104563   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
104564   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
104565   int nElem = 0;                  /* Size of array at aElem */
104566   int rc = SQLITE_OK;             /* Return Code */
104567
104568   if( isPrefix ){
104569     int nAlloc = 0;               /* Size of allocated array at aElem */
104570     Fts3HashElem *pE = 0;         /* Iterator variable */
104571
104572     for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
104573       char *zKey = (char *)fts3HashKey(pE);
104574       int nKey = fts3HashKeysize(pE);
104575       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
104576         if( nElem==nAlloc ){
104577           Fts3HashElem **aElem2;
104578           nAlloc += 16;
104579           aElem2 = (Fts3HashElem **)sqlite3_realloc(
104580               aElem, nAlloc*sizeof(Fts3HashElem *)
104581           );
104582           if( !aElem2 ){
104583             rc = SQLITE_NOMEM;
104584             nElem = 0;
104585             break;
104586           }
104587           aElem = aElem2;
104588         }
104589         aElem[nElem++] = pE;
104590       }
104591     }
104592
104593     /* If more than one term matches the prefix, sort the Fts3HashElem
104594     ** objects in term order using qsort(). This uses the same comparison
104595     ** callback as is used when flushing terms to disk.
104596     */
104597     if( nElem>1 ){
104598       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
104599     }
104600
104601   }else{
104602     Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
104603     if( pE ){
104604       aElem = &pE;
104605       nElem = 1;
104606     }
104607   }
104608
104609   if( nElem>0 ){
104610     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
104611     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
104612     if( !pReader ){
104613       rc = SQLITE_NOMEM;
104614     }else{
104615       memset(pReader, 0, nByte);
104616       pReader->iIdx = 0x7FFFFFFF;
104617       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
104618       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
104619       fts3SegReaderNext(pReader);
104620     }
104621   }
104622
104623   if( isPrefix ){
104624     sqlite3_free(aElem);
104625   }
104626   *ppReader = pReader;
104627   return rc;
104628 }
104629
104630
104631 /*
104632 ** The second argument to this function is expected to be a statement of
104633 ** the form:
104634 **
104635 **   SELECT 
104636 **     idx,                  -- col 0
104637 **     start_block,          -- col 1
104638 **     leaves_end_block,     -- col 2
104639 **     end_block,            -- col 3
104640 **     root                  -- col 4
104641 **   FROM %_segdir ...
104642 **
104643 ** This function allocates and initializes a Fts3SegReader structure to
104644 ** iterate through the terms stored in the segment identified by the
104645 ** current row that pStmt is pointing to. 
104646 **
104647 ** If successful, the Fts3SegReader is left pointing to the first term
104648 ** in the segment and SQLITE_OK is returned. Otherwise, an SQLite error
104649 ** code is returned.
104650 */
104651 static int fts3SegReaderNew(
104652   Fts3Table *p,                   /* Virtual table handle */
104653   sqlite3_stmt *pStmt,            /* See above */
104654   int iAge,                       /* Segment "age". */
104655   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
104656 ){
104657   return sqlite3Fts3SegReaderNew(p, iAge, 
104658       sqlite3_column_int64(pStmt, 1),
104659       sqlite3_column_int64(pStmt, 2),
104660       sqlite3_column_int64(pStmt, 3),
104661       sqlite3_column_blob(pStmt, 4),
104662       sqlite3_column_bytes(pStmt, 4),
104663       ppReader
104664   );
104665 }
104666
104667 /*
104668 ** Compare the entries pointed to by two Fts3SegReader structures. 
104669 ** Comparison is as follows:
104670 **
104671 **   1) EOF is greater than not EOF.
104672 **
104673 **   2) The current terms (if any) are compared using memcmp(). If one
104674 **      term is a prefix of another, the longer term is considered the
104675 **      larger.
104676 **
104677 **   3) By segment age. An older segment is considered larger.
104678 */
104679 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
104680   int rc;
104681   if( pLhs->aNode && pRhs->aNode ){
104682     int rc2 = pLhs->nTerm - pRhs->nTerm;
104683     if( rc2<0 ){
104684       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
104685     }else{
104686       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
104687     }
104688     if( rc==0 ){
104689       rc = rc2;
104690     }
104691   }else{
104692     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
104693   }
104694   if( rc==0 ){
104695     rc = pRhs->iIdx - pLhs->iIdx;
104696   }
104697   assert( rc!=0 );
104698   return rc;
104699 }
104700
104701 /*
104702 ** A different comparison function for SegReader structures. In this
104703 ** version, it is assumed that each SegReader points to an entry in
104704 ** a doclist for identical terms. Comparison is made as follows:
104705 **
104706 **   1) EOF (end of doclist in this case) is greater than not EOF.
104707 **
104708 **   2) By current docid.
104709 **
104710 **   3) By segment age. An older segment is considered larger.
104711 */
104712 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
104713   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
104714   if( rc==0 ){
104715     if( pLhs->iDocid==pRhs->iDocid ){
104716       rc = pRhs->iIdx - pLhs->iIdx;
104717     }else{
104718       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
104719     }
104720   }
104721   assert( pLhs->aNode && pRhs->aNode );
104722   return rc;
104723 }
104724
104725 /*
104726 ** Compare the term that the Fts3SegReader object passed as the first argument
104727 ** points to with the term specified by arguments zTerm and nTerm. 
104728 **
104729 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
104730 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
104731 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
104732 */
104733 static int fts3SegReaderTermCmp(
104734   Fts3SegReader *pSeg,            /* Segment reader object */
104735   const char *zTerm,              /* Term to compare to */
104736   int nTerm                       /* Size of term zTerm in bytes */
104737 ){
104738   int res = 0;
104739   if( pSeg->aNode ){
104740     if( pSeg->nTerm>nTerm ){
104741       res = memcmp(pSeg->zTerm, zTerm, nTerm);
104742     }else{
104743       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
104744     }
104745     if( res==0 ){
104746       res = pSeg->nTerm-nTerm;
104747     }
104748   }
104749   return res;
104750 }
104751
104752 /*
104753 ** Argument apSegment is an array of nSegment elements. It is known that
104754 ** the final (nSegment-nSuspect) members are already in sorted order
104755 ** (according to the comparison function provided). This function shuffles
104756 ** the array around until all entries are in sorted order.
104757 */
104758 static void fts3SegReaderSort(
104759   Fts3SegReader **apSegment,                     /* Array to sort entries of */
104760   int nSegment,                                  /* Size of apSegment array */
104761   int nSuspect,                                  /* Unsorted entry count */
104762   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
104763 ){
104764   int i;                          /* Iterator variable */
104765
104766   assert( nSuspect<=nSegment );
104767
104768   if( nSuspect==nSegment ) nSuspect--;
104769   for(i=nSuspect-1; i>=0; i--){
104770     int j;
104771     for(j=i; j<(nSegment-1); j++){
104772       Fts3SegReader *pTmp;
104773       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
104774       pTmp = apSegment[j+1];
104775       apSegment[j+1] = apSegment[j];
104776       apSegment[j] = pTmp;
104777     }
104778   }
104779
104780 #ifndef NDEBUG
104781   /* Check that the list really is sorted now. */
104782   for(i=0; i<(nSuspect-1); i++){
104783     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
104784   }
104785 #endif
104786 }
104787
104788 /* 
104789 ** Insert a record into the %_segments table.
104790 */
104791 static int fts3WriteSegment(
104792   Fts3Table *p,                   /* Virtual table handle */
104793   sqlite3_int64 iBlock,           /* Block id for new block */
104794   char *z,                        /* Pointer to buffer containing block data */
104795   int n                           /* Size of buffer z in bytes */
104796 ){
104797   sqlite3_stmt *pStmt;
104798   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
104799   if( rc==SQLITE_OK ){
104800     sqlite3_bind_int64(pStmt, 1, iBlock);
104801     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
104802     sqlite3_step(pStmt);
104803     rc = sqlite3_reset(pStmt);
104804   }
104805   return rc;
104806 }
104807
104808 /* 
104809 ** Insert a record into the %_segdir table.
104810 */
104811 static int fts3WriteSegdir(
104812   Fts3Table *p,                   /* Virtual table handle */
104813   int iLevel,                     /* Value for "level" field */
104814   int iIdx,                       /* Value for "idx" field */
104815   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
104816   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
104817   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
104818   char *zRoot,                    /* Blob value for "root" field */
104819   int nRoot                       /* Number of bytes in buffer zRoot */
104820 ){
104821   sqlite3_stmt *pStmt;
104822   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
104823   if( rc==SQLITE_OK ){
104824     sqlite3_bind_int(pStmt, 1, iLevel);
104825     sqlite3_bind_int(pStmt, 2, iIdx);
104826     sqlite3_bind_int64(pStmt, 3, iStartBlock);
104827     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
104828     sqlite3_bind_int64(pStmt, 5, iEndBlock);
104829     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
104830     sqlite3_step(pStmt);
104831     rc = sqlite3_reset(pStmt);
104832   }
104833   return rc;
104834 }
104835
104836 /*
104837 ** Return the size of the common prefix (if any) shared by zPrev and
104838 ** zNext, in bytes. For example, 
104839 **
104840 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
104841 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
104842 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
104843 */
104844 static int fts3PrefixCompress(
104845   const char *zPrev,              /* Buffer containing previous term */
104846   int nPrev,                      /* Size of buffer zPrev in bytes */
104847   const char *zNext,              /* Buffer containing next term */
104848   int nNext                       /* Size of buffer zNext in bytes */
104849 ){
104850   int n;
104851   UNUSED_PARAMETER(nNext);
104852   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
104853   return n;
104854 }
104855
104856 /*
104857 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
104858 ** (according to memcmp) than the previous term.
104859 */
104860 static int fts3NodeAddTerm(
104861   Fts3Table *p,               /* Virtual table handle */
104862   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
104863   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
104864   const char *zTerm,              /* Pointer to buffer containing term */
104865   int nTerm                       /* Size of term in bytes */
104866 ){
104867   SegmentNode *pTree = *ppTree;
104868   int rc;
104869   SegmentNode *pNew;
104870
104871   /* First try to append the term to the current node. Return early if 
104872   ** this is possible.
104873   */
104874   if( pTree ){
104875     int nData = pTree->nData;     /* Current size of node in bytes */
104876     int nReq = nData;             /* Required space after adding zTerm */
104877     int nPrefix;                  /* Number of bytes of prefix compression */
104878     int nSuffix;                  /* Suffix length */
104879
104880     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
104881     nSuffix = nTerm-nPrefix;
104882
104883     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
104884     if( nReq<=p->nNodeSize || !pTree->zTerm ){
104885
104886       if( nReq>p->nNodeSize ){
104887         /* An unusual case: this is the first term to be added to the node
104888         ** and the static node buffer (p->nNodeSize bytes) is not large
104889         ** enough. Use a separately malloced buffer instead This wastes
104890         ** p->nNodeSize bytes, but since this scenario only comes about when
104891         ** the database contain two terms that share a prefix of almost 2KB, 
104892         ** this is not expected to be a serious problem. 
104893         */
104894         assert( pTree->aData==(char *)&pTree[1] );
104895         pTree->aData = (char *)sqlite3_malloc(nReq);
104896         if( !pTree->aData ){
104897           return SQLITE_NOMEM;
104898         }
104899       }
104900
104901       if( pTree->zTerm ){
104902         /* There is no prefix-length field for first term in a node */
104903         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
104904       }
104905
104906       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
104907       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
104908       pTree->nData = nData + nSuffix;
104909       pTree->nEntry++;
104910
104911       if( isCopyTerm ){
104912         if( pTree->nMalloc<nTerm ){
104913           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
104914           if( !zNew ){
104915             return SQLITE_NOMEM;
104916           }
104917           pTree->nMalloc = nTerm*2;
104918           pTree->zMalloc = zNew;
104919         }
104920         pTree->zTerm = pTree->zMalloc;
104921         memcpy(pTree->zTerm, zTerm, nTerm);
104922         pTree->nTerm = nTerm;
104923       }else{
104924         pTree->zTerm = (char *)zTerm;
104925         pTree->nTerm = nTerm;
104926       }
104927       return SQLITE_OK;
104928     }
104929   }
104930
104931   /* If control flows to here, it was not possible to append zTerm to the
104932   ** current node. Create a new node (a right-sibling of the current node).
104933   ** If this is the first node in the tree, the term is added to it.
104934   **
104935   ** Otherwise, the term is not added to the new node, it is left empty for
104936   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
104937   ** has no parent, one is created here.
104938   */
104939   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
104940   if( !pNew ){
104941     return SQLITE_NOMEM;
104942   }
104943   memset(pNew, 0, sizeof(SegmentNode));
104944   pNew->nData = 1 + FTS3_VARINT_MAX;
104945   pNew->aData = (char *)&pNew[1];
104946
104947   if( pTree ){
104948     SegmentNode *pParent = pTree->pParent;
104949     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
104950     if( pTree->pParent==0 ){
104951       pTree->pParent = pParent;
104952     }
104953     pTree->pRight = pNew;
104954     pNew->pLeftmost = pTree->pLeftmost;
104955     pNew->pParent = pParent;
104956     pNew->zMalloc = pTree->zMalloc;
104957     pNew->nMalloc = pTree->nMalloc;
104958     pTree->zMalloc = 0;
104959   }else{
104960     pNew->pLeftmost = pNew;
104961     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
104962   }
104963
104964   *ppTree = pNew;
104965   return rc;
104966 }
104967
104968 /*
104969 ** Helper function for fts3NodeWrite().
104970 */
104971 static int fts3TreeFinishNode(
104972   SegmentNode *pTree, 
104973   int iHeight, 
104974   sqlite3_int64 iLeftChild
104975 ){
104976   int nStart;
104977   assert( iHeight>=1 && iHeight<128 );
104978   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
104979   pTree->aData[nStart] = (char)iHeight;
104980   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
104981   return nStart;
104982 }
104983
104984 /*
104985 ** Write the buffer for the segment node pTree and all of its peers to the
104986 ** database. Then call this function recursively to write the parent of 
104987 ** pTree and its peers to the database. 
104988 **
104989 ** Except, if pTree is a root node, do not write it to the database. Instead,
104990 ** set output variables *paRoot and *pnRoot to contain the root node.
104991 **
104992 ** If successful, SQLITE_OK is returned and output variable *piLast is
104993 ** set to the largest blockid written to the database (or zero if no
104994 ** blocks were written to the db). Otherwise, an SQLite error code is 
104995 ** returned.
104996 */
104997 static int fts3NodeWrite(
104998   Fts3Table *p,                   /* Virtual table handle */
104999   SegmentNode *pTree,             /* SegmentNode handle */
105000   int iHeight,                    /* Height of this node in tree */
105001   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
105002   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
105003   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
105004   char **paRoot,                  /* OUT: Data for root node */
105005   int *pnRoot                     /* OUT: Size of root node in bytes */
105006 ){
105007   int rc = SQLITE_OK;
105008
105009   if( !pTree->pParent ){
105010     /* Root node of the tree. */
105011     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
105012     *piLast = iFree-1;
105013     *pnRoot = pTree->nData - nStart;
105014     *paRoot = &pTree->aData[nStart];
105015   }else{
105016     SegmentNode *pIter;
105017     sqlite3_int64 iNextFree = iFree;
105018     sqlite3_int64 iNextLeaf = iLeaf;
105019     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
105020       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
105021       int nWrite = pIter->nData - nStart;
105022   
105023       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
105024       iNextFree++;
105025       iNextLeaf += (pIter->nEntry+1);
105026     }
105027     if( rc==SQLITE_OK ){
105028       assert( iNextLeaf==iFree );
105029       rc = fts3NodeWrite(
105030           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
105031       );
105032     }
105033   }
105034
105035   return rc;
105036 }
105037
105038 /*
105039 ** Free all memory allocations associated with the tree pTree.
105040 */
105041 static void fts3NodeFree(SegmentNode *pTree){
105042   if( pTree ){
105043     SegmentNode *p = pTree->pLeftmost;
105044     fts3NodeFree(p->pParent);
105045     while( p ){
105046       SegmentNode *pRight = p->pRight;
105047       if( p->aData!=(char *)&p[1] ){
105048         sqlite3_free(p->aData);
105049       }
105050       assert( pRight==0 || p->zMalloc==0 );
105051       sqlite3_free(p->zMalloc);
105052       sqlite3_free(p);
105053       p = pRight;
105054     }
105055   }
105056 }
105057
105058 /*
105059 ** Add a term to the segment being constructed by the SegmentWriter object
105060 ** *ppWriter. When adding the first term to a segment, *ppWriter should
105061 ** be passed NULL. This function will allocate a new SegmentWriter object
105062 ** and return it via the input/output variable *ppWriter in this case.
105063 **
105064 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
105065 */
105066 static int fts3SegWriterAdd(
105067   Fts3Table *p,                   /* Virtual table handle */
105068   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
105069   int isCopyTerm,                 /* True if buffer zTerm must be copied */
105070   const char *zTerm,              /* Pointer to buffer containing term */
105071   int nTerm,                      /* Size of term in bytes */
105072   const char *aDoclist,           /* Pointer to buffer containing doclist */
105073   int nDoclist                    /* Size of doclist in bytes */
105074 ){
105075   int nPrefix;                    /* Size of term prefix in bytes */
105076   int nSuffix;                    /* Size of term suffix in bytes */
105077   int nReq;                       /* Number of bytes required on leaf page */
105078   int nData;
105079   SegmentWriter *pWriter = *ppWriter;
105080
105081   if( !pWriter ){
105082     int rc;
105083     sqlite3_stmt *pStmt;
105084
105085     /* Allocate the SegmentWriter structure */
105086     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
105087     if( !pWriter ) return SQLITE_NOMEM;
105088     memset(pWriter, 0, sizeof(SegmentWriter));
105089     *ppWriter = pWriter;
105090
105091     /* Allocate a buffer in which to accumulate data */
105092     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
105093     if( !pWriter->aData ) return SQLITE_NOMEM;
105094     pWriter->nSize = p->nNodeSize;
105095
105096     /* Find the next free blockid in the %_segments table */
105097     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
105098     if( rc!=SQLITE_OK ) return rc;
105099     if( SQLITE_ROW==sqlite3_step(pStmt) ){
105100       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
105101       pWriter->iFirst = pWriter->iFree;
105102     }
105103     rc = sqlite3_reset(pStmt);
105104     if( rc!=SQLITE_OK ) return rc;
105105   }
105106   nData = pWriter->nData;
105107
105108   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
105109   nSuffix = nTerm-nPrefix;
105110
105111   /* Figure out how many bytes are required by this new entry */
105112   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
105113     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
105114     nSuffix +                               /* Term suffix */
105115     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
105116     nDoclist;                               /* Doclist data */
105117
105118   if( nData>0 && nData+nReq>p->nNodeSize ){
105119     int rc;
105120
105121     /* The current leaf node is full. Write it out to the database. */
105122     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
105123     if( rc!=SQLITE_OK ) return rc;
105124
105125     /* Add the current term to the interior node tree. The term added to
105126     ** the interior tree must:
105127     **
105128     **   a) be greater than the largest term on the leaf node just written
105129     **      to the database (still available in pWriter->zTerm), and
105130     **
105131     **   b) be less than or equal to the term about to be added to the new
105132     **      leaf node (zTerm/nTerm).
105133     **
105134     ** In other words, it must be the prefix of zTerm 1 byte longer than
105135     ** the common prefix (if any) of zTerm and pWriter->zTerm.
105136     */
105137     assert( nPrefix<nTerm );
105138     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
105139     if( rc!=SQLITE_OK ) return rc;
105140
105141     nData = 0;
105142     pWriter->nTerm = 0;
105143
105144     nPrefix = 0;
105145     nSuffix = nTerm;
105146     nReq = 1 +                              /* varint containing prefix size */
105147       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
105148       nTerm +                               /* Term suffix */
105149       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
105150       nDoclist;                             /* Doclist data */
105151   }
105152
105153   /* If the buffer currently allocated is too small for this entry, realloc
105154   ** the buffer to make it large enough.
105155   */
105156   if( nReq>pWriter->nSize ){
105157     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
105158     if( !aNew ) return SQLITE_NOMEM;
105159     pWriter->aData = aNew;
105160     pWriter->nSize = nReq;
105161   }
105162   assert( nData+nReq<=pWriter->nSize );
105163
105164   /* Append the prefix-compressed term and doclist to the buffer. */
105165   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
105166   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
105167   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
105168   nData += nSuffix;
105169   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
105170   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
105171   pWriter->nData = nData + nDoclist;
105172
105173   /* Save the current term so that it can be used to prefix-compress the next.
105174   ** If the isCopyTerm parameter is true, then the buffer pointed to by
105175   ** zTerm is transient, so take a copy of the term data. Otherwise, just
105176   ** store a copy of the pointer.
105177   */
105178   if( isCopyTerm ){
105179     if( nTerm>pWriter->nMalloc ){
105180       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
105181       if( !zNew ){
105182         return SQLITE_NOMEM;
105183       }
105184       pWriter->nMalloc = nTerm*2;
105185       pWriter->zMalloc = zNew;
105186       pWriter->zTerm = zNew;
105187     }
105188     assert( pWriter->zTerm==pWriter->zMalloc );
105189     memcpy(pWriter->zTerm, zTerm, nTerm);
105190   }else{
105191     pWriter->zTerm = (char *)zTerm;
105192   }
105193   pWriter->nTerm = nTerm;
105194
105195   return SQLITE_OK;
105196 }
105197
105198 /*
105199 ** Flush all data associated with the SegmentWriter object pWriter to the
105200 ** database. This function must be called after all terms have been added
105201 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
105202 ** returned. Otherwise, an SQLite error code.
105203 */
105204 static int fts3SegWriterFlush(
105205   Fts3Table *p,                   /* Virtual table handle */
105206   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
105207   int iLevel,                     /* Value for 'level' column of %_segdir */
105208   int iIdx                        /* Value for 'idx' column of %_segdir */
105209 ){
105210   int rc;                         /* Return code */
105211   if( pWriter->pTree ){
105212     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
105213     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
105214     char *zRoot = NULL;           /* Pointer to buffer containing root node */
105215     int nRoot = 0;                /* Size of buffer zRoot */
105216
105217     iLastLeaf = pWriter->iFree;
105218     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
105219     if( rc==SQLITE_OK ){
105220       rc = fts3NodeWrite(p, pWriter->pTree, 1,
105221           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
105222     }
105223     if( rc==SQLITE_OK ){
105224       rc = fts3WriteSegdir(
105225           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
105226     }
105227   }else{
105228     /* The entire tree fits on the root node. Write it to the segdir table. */
105229     rc = fts3WriteSegdir(
105230         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
105231   }
105232   return rc;
105233 }
105234
105235 /*
105236 ** Release all memory held by the SegmentWriter object passed as the 
105237 ** first argument.
105238 */
105239 static void fts3SegWriterFree(SegmentWriter *pWriter){
105240   if( pWriter ){
105241     sqlite3_free(pWriter->aData);
105242     sqlite3_free(pWriter->zMalloc);
105243     fts3NodeFree(pWriter->pTree);
105244     sqlite3_free(pWriter);
105245   }
105246 }
105247
105248 /*
105249 ** The first value in the apVal[] array is assumed to contain an integer.
105250 ** This function tests if there exist any documents with docid values that
105251 ** are different from that integer. i.e. if deleting the document with docid
105252 ** apVal[0] would mean the FTS3 table were empty.
105253 **
105254 ** If successful, *pisEmpty is set to true if the table is empty except for
105255 ** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
105256 ** error occurs, an SQLite error code is returned.
105257 */
105258 static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
105259   sqlite3_stmt *pStmt;
105260   int rc;
105261   rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
105262   if( rc==SQLITE_OK ){
105263     if( SQLITE_ROW==sqlite3_step(pStmt) ){
105264       *pisEmpty = sqlite3_column_int(pStmt, 0);
105265     }
105266     rc = sqlite3_reset(pStmt);
105267   }
105268   return rc;
105269 }
105270
105271 /*
105272 ** Set *pnSegment to the number of segments of level iLevel in the database.
105273 **
105274 ** Return SQLITE_OK if successful, or an SQLite error code if not.
105275 */
105276 static int fts3SegmentCount(Fts3Table *p, int iLevel, int *pnSegment){
105277   sqlite3_stmt *pStmt;
105278   int rc;
105279
105280   assert( iLevel>=0 );
105281   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_COUNT, &pStmt, 0);
105282   if( rc!=SQLITE_OK ) return rc;
105283   sqlite3_bind_int(pStmt, 1, iLevel);
105284   if( SQLITE_ROW==sqlite3_step(pStmt) ){
105285     *pnSegment = sqlite3_column_int(pStmt, 0);
105286   }
105287   return sqlite3_reset(pStmt);
105288 }
105289
105290 /*
105291 ** Set *pnSegment to the total number of segments in the database. Set
105292 ** *pnMax to the largest segment level in the database (segment levels
105293 ** are stored in the 'level' column of the %_segdir table).
105294 **
105295 ** Return SQLITE_OK if successful, or an SQLite error code if not.
105296 */
105297 static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
105298   sqlite3_stmt *pStmt;
105299   int rc;
105300
105301   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
105302   if( rc!=SQLITE_OK ) return rc;
105303   if( SQLITE_ROW==sqlite3_step(pStmt) ){
105304     *pnSegment = sqlite3_column_int(pStmt, 0);
105305     *pnMax = sqlite3_column_int(pStmt, 1);
105306   }
105307   return sqlite3_reset(pStmt);
105308 }
105309
105310 /*
105311 ** This function is used after merging multiple segments into a single large
105312 ** segment to delete the old, now redundant, segment b-trees. Specifically,
105313 ** it:
105314 ** 
105315 **   1) Deletes all %_segments entries for the segments associated with 
105316 **      each of the SegReader objects in the array passed as the third 
105317 **      argument, and
105318 **
105319 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
105320 **      entries regardless of level if (iLevel<0).
105321 **
105322 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
105323 */
105324 static int fts3DeleteSegdir(
105325   Fts3Table *p,                   /* Virtual table handle */
105326   int iLevel,                     /* Level of %_segdir entries to delete */
105327   Fts3SegReader **apSegment,      /* Array of SegReader objects */
105328   int nReader                     /* Size of array apSegment */
105329 ){
105330   int rc;                         /* Return Code */
105331   int i;                          /* Iterator variable */
105332   sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
105333
105334   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
105335   for(i=0; rc==SQLITE_OK && i<nReader; i++){
105336     Fts3SegReader *pSegment = apSegment[i];
105337     if( pSegment->iStartBlock ){
105338       sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
105339       sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
105340       sqlite3_step(pDelete);
105341       rc = sqlite3_reset(pDelete);
105342     }
105343   }
105344   if( rc!=SQLITE_OK ){
105345     return rc;
105346   }
105347
105348   if( iLevel>=0 ){
105349     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
105350     if( rc==SQLITE_OK ){
105351       sqlite3_bind_int(pDelete, 1, iLevel);
105352       sqlite3_step(pDelete);
105353       rc = sqlite3_reset(pDelete);
105354     }
105355   }else{
105356     rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGDIR, 0);
105357   }
105358
105359   return rc;
105360 }
105361
105362 /*
105363 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
105364 ** a position list that may (or may not) feature multiple columns. This
105365 ** function adjusts the pointer *ppList and the length *pnList so that they
105366 ** identify the subset of the position list that corresponds to column iCol.
105367 **
105368 ** If there are no entries in the input position list for column iCol, then
105369 ** *pnList is set to zero before returning.
105370 */
105371 static void fts3ColumnFilter(
105372   int iCol,                       /* Column to filter on */
105373   char **ppList,                  /* IN/OUT: Pointer to position list */
105374   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
105375 ){
105376   char *pList = *ppList;
105377   int nList = *pnList;
105378   char *pEnd = &pList[nList];
105379   int iCurrent = 0;
105380   char *p = pList;
105381
105382   assert( iCol>=0 );
105383   while( 1 ){
105384     char c = 0;
105385     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
105386   
105387     if( iCol==iCurrent ){
105388       nList = (int)(p - pList);
105389       break;
105390     }
105391
105392     nList -= (int)(p - pList);
105393     pList = p;
105394     if( nList==0 ){
105395       break;
105396     }
105397     p = &pList[1];
105398     p += sqlite3Fts3GetVarint32(p, &iCurrent);
105399   }
105400
105401   *ppList = pList;
105402   *pnList = nList;
105403 }
105404
105405 /*
105406 ** sqlite3Fts3SegReaderIterate() callback used when merging multiple 
105407 ** segments to create a single, larger segment.
105408 */
105409 static int fts3MergeCallback(
105410   Fts3Table *p,                   /* FTS3 Virtual table handle */
105411   void *pContext,                 /* Pointer to SegmentWriter* to write with */
105412   char *zTerm,                    /* Term to write to the db */
105413   int nTerm,                      /* Number of bytes in zTerm */
105414   char *aDoclist,                 /* Doclist associated with zTerm */
105415   int nDoclist                    /* Number of bytes in doclist */
105416 ){
105417   SegmentWriter **ppW = (SegmentWriter **)pContext;
105418   return fts3SegWriterAdd(p, ppW, 1, zTerm, nTerm, aDoclist, nDoclist);
105419 }
105420
105421 /*
105422 ** sqlite3Fts3SegReaderIterate() callback used when flushing the contents
105423 ** of the pending-terms hash table to the database.
105424 */
105425 static int fts3FlushCallback(
105426   Fts3Table *p,                   /* FTS3 Virtual table handle */
105427   void *pContext,                 /* Pointer to SegmentWriter* to write with */
105428   char *zTerm,                    /* Term to write to the db */
105429   int nTerm,                      /* Number of bytes in zTerm */
105430   char *aDoclist,                 /* Doclist associated with zTerm */
105431   int nDoclist                    /* Number of bytes in doclist */
105432 ){
105433   SegmentWriter **ppW = (SegmentWriter **)pContext;
105434   return fts3SegWriterAdd(p, ppW, 0, zTerm, nTerm, aDoclist, nDoclist);
105435 }
105436
105437 /*
105438 ** This function is used to iterate through a contiguous set of terms 
105439 ** stored in the full-text index. It merges data contained in one or 
105440 ** more segments to support this.
105441 **
105442 ** The second argument is passed an array of pointers to SegReader objects
105443 ** allocated with sqlite3Fts3SegReaderNew(). This function merges the range 
105444 ** of terms selected by each SegReader. If a single term is present in
105445 ** more than one segment, the associated doclists are merged. For each
105446 ** term and (possibly merged) doclist in the merged range, the callback
105447 ** function xFunc is invoked with its arguments set as follows.
105448 **
105449 **   arg 0: Copy of 'p' parameter passed to this function
105450 **   arg 1: Copy of 'pContext' parameter passed to this function
105451 **   arg 2: Pointer to buffer containing term
105452 **   arg 3: Size of arg 2 buffer in bytes
105453 **   arg 4: Pointer to buffer containing doclist
105454 **   arg 5: Size of arg 2 buffer in bytes
105455 **
105456 ** The 4th argument to this function is a pointer to a structure of type
105457 ** Fts3SegFilter, defined in fts3Int.h. The contents of this structure
105458 ** further restrict the range of terms that callbacks are made for and
105459 ** modify the behaviour of this function. See comments above structure
105460 ** definition for details.
105461 */
105462 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
105463   Fts3Table *p,                   /* Virtual table handle */
105464   Fts3SegReader **apSegment,      /* Array of Fts3SegReader objects */
105465   int nSegment,                   /* Size of apSegment array */
105466   Fts3SegFilter *pFilter,         /* Restrictions on range of iteration */
105467   int (*xFunc)(Fts3Table *, void *, char *, int, char *, int),  /* Callback */
105468   void *pContext                  /* Callback context (2nd argument) */
105469 ){
105470   int i;                          /* Iterator variable */
105471   char *aBuffer = 0;              /* Buffer to merge doclists in */
105472   int nAlloc = 0;                 /* Allocated size of aBuffer buffer */
105473   int rc = SQLITE_OK;             /* Return code */
105474
105475   int isIgnoreEmpty =  (pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
105476   int isRequirePos =   (pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
105477   int isColFilter =    (pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
105478   int isPrefix =       (pFilter->flags & FTS3_SEGMENT_PREFIX);
105479
105480   /* If there are zero segments, this function is a no-op. This scenario
105481   ** comes about only when reading from an empty database.
105482   */
105483   if( nSegment==0 ) goto finished;
105484
105485   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
105486   ** for, then advance each segment iterator until it points to a term of
105487   ** equal or greater value than the specified term. This prevents many
105488   ** unnecessary merge/sort operations for the case where single segment
105489   ** b-tree leaf nodes contain more than one term.
105490   */
105491   if( pFilter->zTerm ){
105492     int nTerm = pFilter->nTerm;
105493     const char *zTerm = pFilter->zTerm;
105494     for(i=0; i<nSegment; i++){
105495       Fts3SegReader *pSeg = apSegment[i];
105496       while( fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 ){
105497         rc = fts3SegReaderNext(pSeg);
105498         if( rc!=SQLITE_OK ) goto finished; }
105499     }
105500   }
105501
105502   fts3SegReaderSort(apSegment, nSegment, nSegment, fts3SegReaderCmp);
105503   while( apSegment[0]->aNode ){
105504     int nTerm = apSegment[0]->nTerm;
105505     char *zTerm = apSegment[0]->zTerm;
105506     int nMerge = 1;
105507
105508     /* If this is a prefix-search, and if the term that apSegment[0] points
105509     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
105510     ** required callbacks have been made. In this case exit early.
105511     **
105512     ** Similarly, if this is a search for an exact match, and the first term
105513     ** of segment apSegment[0] is not a match, exit early.
105514     */
105515     if( pFilter->zTerm ){
105516       if( nTerm<pFilter->nTerm 
105517        || (!isPrefix && nTerm>pFilter->nTerm)
105518        || memcmp(zTerm, pFilter->zTerm, pFilter->nTerm) 
105519     ){
105520         goto finished;
105521       }
105522     }
105523
105524     while( nMerge<nSegment 
105525         && apSegment[nMerge]->aNode
105526         && apSegment[nMerge]->nTerm==nTerm 
105527         && 0==memcmp(zTerm, apSegment[nMerge]->zTerm, nTerm)
105528     ){
105529       nMerge++;
105530     }
105531
105532     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
105533     if( nMerge==1 && !isIgnoreEmpty ){
105534       Fts3SegReader *p0 = apSegment[0];
105535       rc = xFunc(p, pContext, zTerm, nTerm, p0->aDoclist, p0->nDoclist);
105536       if( rc!=SQLITE_OK ) goto finished;
105537     }else{
105538       int nDoclist = 0;           /* Size of doclist */
105539       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
105540
105541       /* The current term of the first nMerge entries in the array
105542       ** of Fts3SegReader objects is the same. The doclists must be merged
105543       ** and a single term added to the new segment.
105544       */
105545       for(i=0; i<nMerge; i++){
105546         fts3SegReaderFirstDocid(apSegment[i]);
105547       }
105548       fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
105549       while( apSegment[0]->pOffsetList ){
105550         int j;                    /* Number of segments that share a docid */
105551         char *pList;
105552         int nList;
105553         int nByte;
105554         sqlite3_int64 iDocid = apSegment[0]->iDocid;
105555         fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
105556         j = 1;
105557         while( j<nMerge
105558             && apSegment[j]->pOffsetList
105559             && apSegment[j]->iDocid==iDocid
105560         ){
105561           fts3SegReaderNextDocid(apSegment[j], 0, 0);
105562           j++;
105563         }
105564
105565         if( isColFilter ){
105566           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
105567         }
105568
105569         if( !isIgnoreEmpty || nList>0 ){
105570           nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
105571           if( nDoclist+nByte>nAlloc ){
105572             char *aNew;
105573             nAlloc = nDoclist+nByte*2;
105574             aNew = sqlite3_realloc(aBuffer, nAlloc);
105575             if( !aNew ){
105576               rc = SQLITE_NOMEM;
105577               goto finished;
105578             }
105579             aBuffer = aNew;
105580           }
105581           nDoclist += sqlite3Fts3PutVarint(&aBuffer[nDoclist], iDocid-iPrev);
105582           iPrev = iDocid;
105583           if( isRequirePos ){
105584             memcpy(&aBuffer[nDoclist], pList, nList);
105585             nDoclist += nList;
105586             aBuffer[nDoclist++] = '\0';
105587           }
105588         }
105589
105590         fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
105591       }
105592
105593       if( nDoclist>0 ){
105594         rc = xFunc(p, pContext, zTerm, nTerm, aBuffer, nDoclist);
105595         if( rc!=SQLITE_OK ) goto finished;
105596       }
105597     }
105598
105599     /* If there is a term specified to filter on, and this is not a prefix
105600     ** search, return now. The callback that corresponds to the required
105601     ** term (if such a term exists in the index) has already been made.
105602     */
105603     if( pFilter->zTerm && !isPrefix ){
105604       goto finished;
105605     }
105606
105607     for(i=0; i<nMerge; i++){
105608       rc = fts3SegReaderNext(apSegment[i]);
105609       if( rc!=SQLITE_OK ) goto finished;
105610     }
105611     fts3SegReaderSort(apSegment, nSegment, nMerge, fts3SegReaderCmp);
105612   }
105613
105614  finished:
105615   sqlite3_free(aBuffer);
105616   return rc;
105617 }
105618
105619 /*
105620 ** Merge all level iLevel segments in the database into a single 
105621 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
105622 ** single segment with a level equal to the numerically largest level 
105623 ** currently present in the database.
105624 **
105625 ** If this function is called with iLevel<0, but there is only one
105626 ** segment in the database, SQLITE_DONE is returned immediately. 
105627 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
105628 ** an SQLite error code is returned.
105629 */
105630 static int fts3SegmentMerge(Fts3Table *p, int iLevel){
105631   int i;                          /* Iterator variable */
105632   int rc;                         /* Return code */
105633   int iIdx;                       /* Index of new segment */
105634   int iNewLevel;                  /* Level to create new segment at */
105635   sqlite3_stmt *pStmt = 0;
105636   SegmentWriter *pWriter = 0;
105637   int nSegment = 0;               /* Number of segments being merged */
105638   Fts3SegReader **apSegment = 0;  /* Array of Segment iterators */
105639   Fts3SegReader *pPending = 0;    /* Iterator for pending-terms */
105640   Fts3SegFilter filter;           /* Segment term filter condition */
105641
105642   if( iLevel<0 ){
105643     /* This call is to merge all segments in the database to a single
105644     ** segment. The level of the new segment is equal to the the numerically 
105645     ** greatest segment level currently present in the database. The index
105646     ** of the new segment is always 0.
105647     */
105648     iIdx = 0;
105649     rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pPending);
105650     if( rc!=SQLITE_OK ) goto finished;
105651     rc = fts3SegmentCountMax(p, &nSegment, &iNewLevel);
105652     if( rc!=SQLITE_OK ) goto finished;
105653     nSegment += (pPending!=0);
105654     if( nSegment<=1 ){
105655       return SQLITE_DONE;
105656     }
105657   }else{
105658     /* This call is to merge all segments at level iLevel. Find the next
105659     ** available segment index at level iLevel+1. The call to
105660     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
105661     ** a single iLevel+2 segment if necessary.
105662     */
105663     iNewLevel = iLevel+1;
105664     rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
105665     if( rc!=SQLITE_OK ) goto finished;
105666     rc = fts3SegmentCount(p, iLevel, &nSegment);
105667     if( rc!=SQLITE_OK ) goto finished;
105668   }
105669   assert( nSegment>0 );
105670   assert( iNewLevel>=0 );
105671
105672   /* Allocate space for an array of pointers to segment iterators. */
105673   apSegment = (Fts3SegReader**)sqlite3_malloc(sizeof(Fts3SegReader *)*nSegment);
105674   if( !apSegment ){
105675     rc = SQLITE_NOMEM;
105676     goto finished;
105677   }
105678   memset(apSegment, 0, sizeof(Fts3SegReader *)*nSegment);
105679
105680   /* Allocate a Fts3SegReader structure for each segment being merged. A 
105681   ** Fts3SegReader stores the state data required to iterate through all 
105682   ** entries on all leaves of a single segment. 
105683   */
105684   assert( SQL_SELECT_LEVEL+1==SQL_SELECT_ALL_LEVEL);
105685   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL+(iLevel<0), &pStmt, 0);
105686   if( rc!=SQLITE_OK ) goto finished;
105687   sqlite3_bind_int(pStmt, 1, iLevel);
105688   for(i=0; SQLITE_ROW==(sqlite3_step(pStmt)); i++){
105689     rc = fts3SegReaderNew(p, pStmt, i, &apSegment[i]);
105690     if( rc!=SQLITE_OK ){
105691       goto finished;
105692     }
105693   }
105694   rc = sqlite3_reset(pStmt);
105695   if( pPending ){
105696     apSegment[i] = pPending;
105697     pPending = 0;
105698   }
105699   pStmt = 0;
105700   if( rc!=SQLITE_OK ) goto finished;
105701
105702   memset(&filter, 0, sizeof(Fts3SegFilter));
105703   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
105704   filter.flags |= (iLevel<0 ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
105705   rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment,
105706       &filter, fts3MergeCallback, (void *)&pWriter
105707   );
105708   if( rc!=SQLITE_OK ) goto finished;
105709
105710   rc = fts3DeleteSegdir(p, iLevel, apSegment, nSegment);
105711   if( rc==SQLITE_OK ){
105712     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
105713   }
105714
105715  finished:
105716   fts3SegWriterFree(pWriter);
105717   if( apSegment ){
105718     for(i=0; i<nSegment; i++){
105719       sqlite3Fts3SegReaderFree(p, apSegment[i]);
105720     }
105721     sqlite3_free(apSegment);
105722   }
105723   sqlite3Fts3SegReaderFree(p, pPending);
105724   sqlite3_reset(pStmt);
105725   return rc;
105726 }
105727
105728
105729 /* 
105730 ** Flush the contents of pendingTerms to a level 0 segment.
105731 */
105732 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
105733   int rc;                         /* Return Code */
105734   int idx;                        /* Index of new segment created */
105735   SegmentWriter *pWriter = 0;     /* Used to write the segment */
105736   Fts3SegReader *pReader = 0;     /* Used to iterate through the hash table */
105737
105738   /* Allocate a SegReader object to iterate through the contents of the
105739   ** pending-terms table. If an error occurs, or if there are no terms
105740   ** in the pending-terms table, return immediately.
105741   */
105742   rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pReader);
105743   if( rc!=SQLITE_OK || pReader==0 ){
105744     return rc;
105745   }
105746
105747   /* Determine the next index at level 0. If level 0 is already full, this
105748   ** call may merge all existing level 0 segments into a single level 1
105749   ** segment.
105750   */
105751   rc = fts3AllocateSegdirIdx(p, 0, &idx);
105752
105753   /* If no errors have occured, iterate through the contents of the 
105754   ** pending-terms hash table using the Fts3SegReader iterator. The callback
105755   ** writes each term (along with its doclist) to the database via the
105756   ** SegmentWriter handle pWriter.
105757   */
105758   if( rc==SQLITE_OK ){
105759     void *c = (void *)&pWriter;   /* SegReaderIterate() callback context */
105760     Fts3SegFilter f;              /* SegReaderIterate() parameters */
105761
105762     memset(&f, 0, sizeof(Fts3SegFilter));
105763     f.flags = FTS3_SEGMENT_REQUIRE_POS;
105764     rc = sqlite3Fts3SegReaderIterate(p, &pReader, 1, &f, fts3FlushCallback, c);
105765   }
105766   assert( pWriter || rc!=SQLITE_OK );
105767
105768   /* If no errors have occured, flush the SegmentWriter object to the
105769   ** database. Then delete the SegmentWriter and Fts3SegReader objects
105770   ** allocated by this function.
105771   */
105772   if( rc==SQLITE_OK ){
105773     rc = fts3SegWriterFlush(p, pWriter, 0, idx);
105774   }
105775   fts3SegWriterFree(pWriter);
105776   sqlite3Fts3SegReaderFree(p, pReader);
105777
105778   if( rc==SQLITE_OK ){
105779     sqlite3Fts3PendingTermsClear(p);
105780   }
105781   return rc;
105782 }
105783
105784 /*
105785 ** Handle a 'special' INSERT of the form:
105786 **
105787 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
105788 **
105789 ** Argument pVal contains the result of <expr>. Currently the only 
105790 ** meaningful value to insert is the text 'optimize'.
105791 */
105792 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
105793   int rc;                         /* Return Code */
105794   const char *zVal = (const char *)sqlite3_value_text(pVal);
105795   int nVal = sqlite3_value_bytes(pVal);
105796
105797   if( !zVal ){
105798     return SQLITE_NOMEM;
105799   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
105800     rc = fts3SegmentMerge(p, -1);
105801     if( rc==SQLITE_DONE ){
105802       rc = SQLITE_OK;
105803     }else{
105804       sqlite3Fts3PendingTermsClear(p);
105805     }
105806 #ifdef SQLITE_TEST
105807   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
105808     p->nNodeSize = atoi(&zVal[9]);
105809     rc = SQLITE_OK;
105810   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
105811     p->nMaxPendingData = atoi(&zVal[11]);
105812     rc = SQLITE_OK;
105813 #endif
105814   }else{
105815     rc = SQLITE_ERROR;
105816   }
105817
105818   return rc;
105819 }
105820
105821 /*
105822 ** This function does the work for the xUpdate method of FTS3 virtual
105823 ** tables.
105824 */
105825 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
105826   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
105827   int nArg,                       /* Size of argument array */
105828   sqlite3_value **apVal,          /* Array of arguments */
105829   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
105830 ){
105831   Fts3Table *p = (Fts3Table *)pVtab;
105832   int rc = SQLITE_OK;             /* Return Code */
105833   int isRemove = 0;               /* True for an UPDATE or DELETE */
105834   sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
105835
105836
105837   /* If this is a DELETE or UPDATE operation, remove the old record. */
105838   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
105839     int isEmpty;
105840     rc = fts3IsEmpty(p, apVal, &isEmpty);
105841     if( rc==SQLITE_OK ){
105842       if( isEmpty ){
105843         /* Deleting this row means the whole table is empty. In this case
105844         ** delete the contents of all three tables and throw away any
105845         ** data in the pendingTerms hash table.
105846         */
105847         rc = fts3DeleteAll(p);
105848       }else{
105849         isRemove = 1;
105850         iRemove = sqlite3_value_int64(apVal[0]);
105851         rc = fts3PendingTermsDocid(p, iRemove);
105852         if( rc==SQLITE_OK ){
105853           rc = fts3DeleteTerms(p, apVal);
105854           if( rc==SQLITE_OK ){
105855             rc = fts3SqlExec(p, SQL_DELETE_CONTENT, apVal);
105856           }
105857         }
105858       }
105859     }
105860   }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
105861     return fts3SpecialInsert(p, apVal[p->nColumn+2]);
105862   }
105863   
105864   /* If this is an INSERT or UPDATE operation, insert the new record. */
105865   if( nArg>1 && rc==SQLITE_OK ){
105866     rc = fts3InsertData(p, apVal, pRowid);
105867     if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
105868       rc = fts3PendingTermsDocid(p, *pRowid);
105869     }
105870     if( rc==SQLITE_OK ){
105871       rc = fts3InsertTerms(p, apVal);
105872     }
105873   }
105874
105875   return rc;
105876 }
105877
105878 /* 
105879 ** Flush any data in the pending-terms hash table to disk. If successful,
105880 ** merge all segments in the database (including the new segment, if 
105881 ** there was any data to flush) into a single segment. 
105882 */
105883 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
105884   int rc;
105885   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
105886   if( rc==SQLITE_OK ){
105887     rc = fts3SegmentMerge(p, -1);
105888     if( rc==SQLITE_OK ){
105889       rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
105890       if( rc==SQLITE_OK ){
105891         sqlite3Fts3PendingTermsClear(p);
105892       }
105893     }else{
105894       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
105895       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
105896     }
105897   }
105898   return rc;
105899 }
105900
105901 #endif
105902
105903 /************** End of fts3_write.c ******************************************/
105904 /************** Begin file fts3_snippet.c ************************************/
105905 /*
105906 ** 2009 Oct 23
105907 **
105908 ** The author disclaims copyright to this source code.  In place of
105909 ** a legal notice, here is a blessing:
105910 **
105911 **    May you do good and not evil.
105912 **    May you find forgiveness for yourself and forgive others.
105913 **    May you share freely, never taking more than you give.
105914 **
105915 ******************************************************************************
105916 */
105917
105918 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
105919
105920
105921 typedef struct Snippet Snippet;
105922
105923 /*
105924 ** An instance of the following structure keeps track of generated
105925 ** matching-word offset information and snippets.
105926 */
105927 struct Snippet {
105928   int nMatch;                     /* Total number of matches */
105929   int nAlloc;                     /* Space allocated for aMatch[] */
105930   struct snippetMatch {  /* One entry for each matching term */
105931     char snStatus;       /* Status flag for use while constructing snippets */
105932     short int nByte;     /* Number of bytes in the term */
105933     short int iCol;      /* The column that contains the match */
105934     short int iTerm;     /* The index in Query.pTerms[] of the matching term */
105935     int iToken;          /* The index of the matching document token */
105936     int iStart;          /* The offset to the first character of the term */
105937   } *aMatch;                      /* Points to space obtained from malloc */
105938   char *zOffset;                  /* Text rendering of aMatch[] */
105939   int nOffset;                    /* strlen(zOffset) */
105940   char *zSnippet;                 /* Snippet text */
105941   int nSnippet;                   /* strlen(zSnippet) */
105942 };
105943
105944
105945 /* It is not safe to call isspace(), tolower(), or isalnum() on
105946 ** hi-bit-set characters.  This is the same solution used in the
105947 ** tokenizer.
105948 */
105949 static int fts3snippetIsspace(char c){
105950   return (c&0x80)==0 ? isspace(c) : 0;
105951 }
105952
105953
105954 /*
105955 ** A StringBuffer object holds a zero-terminated string that grows
105956 ** arbitrarily by appending.  Space to hold the string is obtained
105957 ** from sqlite3_malloc().  After any memory allocation failure, 
105958 ** StringBuffer.z is set to NULL and no further allocation is attempted.
105959 */
105960 typedef struct StringBuffer {
105961   char *z;         /* Text of the string.  Space from malloc. */
105962   int nUsed;       /* Number bytes of z[] used, not counting \000 terminator */
105963   int nAlloc;      /* Bytes allocated for z[] */
105964 } StringBuffer;
105965
105966
105967 /*
105968 ** Initialize a new StringBuffer.
105969 */
105970 static void fts3SnippetSbInit(StringBuffer *p){
105971   p->nAlloc = 100;
105972   p->nUsed = 0;
105973   p->z = sqlite3_malloc( p->nAlloc );
105974 }
105975
105976 /*
105977 ** Append text to the string buffer.
105978 */
105979 static void fts3SnippetAppend(StringBuffer *p, const char *zNew, int nNew){
105980   if( p->z==0 ) return;
105981   if( nNew<0 ) nNew = (int)strlen(zNew);
105982   if( p->nUsed + nNew >= p->nAlloc ){
105983     int nAlloc;
105984     char *zNew;
105985
105986     nAlloc = p->nUsed + nNew + p->nAlloc;
105987     zNew = sqlite3_realloc(p->z, nAlloc);
105988     if( zNew==0 ){
105989       sqlite3_free(p->z);
105990       p->z = 0;
105991       return;
105992     }
105993     p->z = zNew;
105994     p->nAlloc = nAlloc;
105995   }
105996   memcpy(&p->z[p->nUsed], zNew, nNew);
105997   p->nUsed += nNew;
105998   p->z[p->nUsed] = 0;
105999 }
106000
106001 /* If the StringBuffer ends in something other than white space, add a
106002 ** single space character to the end.
106003 */
106004 static void fts3SnippetAppendWhiteSpace(StringBuffer *p){
106005   if( p->z && p->nUsed && !fts3snippetIsspace(p->z[p->nUsed-1]) ){
106006     fts3SnippetAppend(p, " ", 1);
106007   }
106008 }
106009
106010 /* Remove white space from the end of the StringBuffer */
106011 static void fts3SnippetTrimWhiteSpace(StringBuffer *p){
106012   if( p->z ){
106013     while( p->nUsed && fts3snippetIsspace(p->z[p->nUsed-1]) ){
106014       p->nUsed--;
106015     }
106016     p->z[p->nUsed] = 0;
106017   }
106018 }
106019
106020 /* 
106021 ** Release all memory associated with the Snippet structure passed as
106022 ** an argument.
106023 */
106024 static void fts3SnippetFree(Snippet *p){
106025   if( p ){
106026     sqlite3_free(p->aMatch);
106027     sqlite3_free(p->zOffset);
106028     sqlite3_free(p->zSnippet);
106029     sqlite3_free(p);
106030   }
106031 }
106032
106033 /*
106034 ** Append a single entry to the p->aMatch[] log.
106035 */
106036 static int snippetAppendMatch(
106037   Snippet *p,               /* Append the entry to this snippet */
106038   int iCol, int iTerm,      /* The column and query term */
106039   int iToken,               /* Matching token in document */
106040   int iStart, int nByte     /* Offset and size of the match */
106041 ){
106042   int i;
106043   struct snippetMatch *pMatch;
106044   if( p->nMatch+1>=p->nAlloc ){
106045     struct snippetMatch *pNew;
106046     p->nAlloc = p->nAlloc*2 + 10;
106047     pNew = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
106048     if( pNew==0 ){
106049       p->aMatch = 0;
106050       p->nMatch = 0;
106051       p->nAlloc = 0;
106052       return SQLITE_NOMEM;
106053     }
106054     p->aMatch = pNew;
106055   }
106056   i = p->nMatch++;
106057   pMatch = &p->aMatch[i];
106058   pMatch->iCol = (short)iCol;
106059   pMatch->iTerm = (short)iTerm;
106060   pMatch->iToken = iToken;
106061   pMatch->iStart = iStart;
106062   pMatch->nByte = (short)nByte;
106063   return SQLITE_OK;
106064 }
106065
106066 /*
106067 ** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
106068 */
106069 #define FTS3_ROTOR_SZ   (32)
106070 #define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
106071
106072 /*
106073 ** Function to iterate through the tokens of a compiled expression.
106074 **
106075 ** Except, skip all tokens on the right-hand side of a NOT operator.
106076 ** This function is used to find tokens as part of snippet and offset
106077 ** generation and we do nt want snippets and offsets to report matches
106078 ** for tokens on the RHS of a NOT.
106079 */
106080 static int fts3NextExprToken(Fts3Expr **ppExpr, int *piToken){
106081   Fts3Expr *p = *ppExpr;
106082   int iToken = *piToken;
106083   if( iToken<0 ){
106084     /* In this case the expression p is the root of an expression tree.
106085     ** Move to the first token in the expression tree.
106086     */
106087     while( p->pLeft ){
106088       p = p->pLeft;
106089     }
106090     iToken = 0;
106091   }else{
106092     assert(p && p->eType==FTSQUERY_PHRASE );
106093     if( iToken<(p->pPhrase->nToken-1) ){
106094       iToken++;
106095     }else{
106096       iToken = 0;
106097       while( p->pParent && p->pParent->pLeft!=p ){
106098         assert( p->pParent->pRight==p );
106099         p = p->pParent;
106100       }
106101       p = p->pParent;
106102       if( p ){
106103         assert( p->pRight!=0 );
106104         p = p->pRight;
106105         while( p->pLeft ){
106106           p = p->pLeft;
106107         }
106108       }
106109     }
106110   }
106111
106112   *ppExpr = p;
106113   *piToken = iToken;
106114   return p?1:0;
106115 }
106116
106117 /*
106118 ** Return TRUE if the expression node pExpr is located beneath the
106119 ** RHS of a NOT operator.
106120 */
106121 static int fts3ExprBeneathNot(Fts3Expr *p){
106122   Fts3Expr *pParent;
106123   while( p ){
106124     pParent = p->pParent;
106125     if( pParent && pParent->eType==FTSQUERY_NOT && pParent->pRight==p ){
106126       return 1;
106127     }
106128     p = pParent;
106129   }
106130   return 0;
106131 }
106132
106133 /*
106134 ** Add entries to pSnippet->aMatch[] for every match that occurs against
106135 ** document zDoc[0..nDoc-1] which is stored in column iColumn.
106136 */
106137 static int snippetOffsetsOfColumn(
106138   Fts3Cursor *pCur,         /* The fulltest search cursor */
106139   Snippet *pSnippet,             /* The Snippet object to be filled in */
106140   int iColumn,                   /* Index of fulltext table column */
106141   const char *zDoc,              /* Text of the fulltext table column */
106142   int nDoc                       /* Length of zDoc in bytes */
106143 ){
106144   const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
106145   sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
106146   sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
106147   Fts3Table *pVtab;                /* The full text index */
106148   int nColumn;                         /* Number of columns in the index */
106149   int i, j;                            /* Loop counters */
106150   int rc;                              /* Return code */
106151   unsigned int match, prevMatch;       /* Phrase search bitmasks */
106152   const char *zToken;                  /* Next token from the tokenizer */
106153   int nToken;                          /* Size of zToken */
106154   int iBegin, iEnd, iPos;              /* Offsets of beginning and end */
106155
106156   /* The following variables keep a circular buffer of the last
106157   ** few tokens */
106158   unsigned int iRotor = 0;             /* Index of current token */
106159   int iRotorBegin[FTS3_ROTOR_SZ];      /* Beginning offset of token */
106160   int iRotorLen[FTS3_ROTOR_SZ];        /* Length of token */
106161
106162   pVtab =  (Fts3Table *)pCur->base.pVtab;
106163   nColumn = pVtab->nColumn;
106164   pTokenizer = pVtab->pTokenizer;
106165   pTModule = pTokenizer->pModule;
106166   rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
106167   if( rc ) return rc;
106168   pTCursor->pTokenizer = pTokenizer;
106169
106170   prevMatch = 0;
106171   while( (rc = pTModule->xNext(pTCursor, &zToken, &nToken,
106172                                &iBegin, &iEnd, &iPos))==SQLITE_OK ){
106173     Fts3Expr *pIter = pCur->pExpr;
106174     int iIter = -1;
106175     iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
106176     iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
106177     match = 0;
106178     for(i=0; i<(FTS3_ROTOR_SZ-1) && fts3NextExprToken(&pIter, &iIter); i++){
106179       int nPhrase;                    /* Number of tokens in current phrase */
106180       struct PhraseToken *pToken;     /* Current token */
106181       int iCol;                       /* Column index */
106182
106183       if( fts3ExprBeneathNot(pIter) ) continue;
106184       nPhrase = pIter->pPhrase->nToken;
106185       pToken = &pIter->pPhrase->aToken[iIter];
106186       iCol = pIter->pPhrase->iColumn;
106187       if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
106188       if( pToken->n>nToken ) continue;
106189       if( !pToken->isPrefix && pToken->n<nToken ) continue;
106190       assert( pToken->n<=nToken );
106191       if( memcmp(pToken->z, zToken, pToken->n) ) continue;
106192       if( iIter>0 && (prevMatch & (1<<i))==0 ) continue;
106193       match |= 1<<i;
106194       if( i==(FTS3_ROTOR_SZ-2) || nPhrase==iIter+1 ){
106195         for(j=nPhrase-1; j>=0; j--){
106196           int k = (iRotor-j) & FTS3_ROTOR_MASK;
106197           rc = snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
106198                                   iRotorBegin[k], iRotorLen[k]);
106199           if( rc ) goto end_offsets_of_column;
106200         }
106201       }
106202     }
106203     prevMatch = match<<1;
106204     iRotor++;
106205   }
106206 end_offsets_of_column:
106207   pTModule->xClose(pTCursor);  
106208   return rc==SQLITE_DONE ? SQLITE_OK : rc;
106209 }
106210
106211 /*
106212 ** Remove entries from the pSnippet structure to account for the NEAR
106213 ** operator. When this is called, pSnippet contains the list of token 
106214 ** offsets produced by treating all NEAR operators as AND operators.
106215 ** This function removes any entries that should not be present after
106216 ** accounting for the NEAR restriction. For example, if the queried
106217 ** document is:
106218 **
106219 **     "A B C D E A"
106220 **
106221 ** and the query is:
106222 ** 
106223 **     A NEAR/0 E
106224 **
106225 ** then when this function is called the Snippet contains token offsets
106226 ** 0, 4 and 5. This function removes the "0" entry (because the first A
106227 ** is not near enough to an E).
106228 **
106229 ** When this function is called, the value pointed to by parameter piLeft is
106230 ** the integer id of the left-most token in the expression tree headed by
106231 ** pExpr. This function increments *piLeft by the total number of tokens
106232 ** in the expression tree headed by pExpr.
106233 **
106234 ** Return 1 if any trimming occurs.  Return 0 if no trimming is required.
106235 */
106236 static int trimSnippetOffsets(
106237   Fts3Expr *pExpr,      /* The search expression */
106238   Snippet *pSnippet,    /* The set of snippet offsets to be trimmed */
106239   int *piLeft           /* Index of left-most token in pExpr */
106240 ){
106241   if( pExpr ){
106242     if( trimSnippetOffsets(pExpr->pLeft, pSnippet, piLeft) ){
106243       return 1;
106244     }
106245
106246     switch( pExpr->eType ){
106247       case FTSQUERY_PHRASE:
106248         *piLeft += pExpr->pPhrase->nToken;
106249         break;
106250       case FTSQUERY_NEAR: {
106251         /* The right-hand-side of a NEAR operator is always a phrase. The
106252         ** left-hand-side is either a phrase or an expression tree that is 
106253         ** itself headed by a NEAR operator. The following initializations
106254         ** set local variable iLeft to the token number of the left-most
106255         ** token in the right-hand phrase, and iRight to the right most
106256         ** token in the same phrase. For example, if we had:
106257         **
106258         **     <col> MATCH '"abc def" NEAR/2 "ghi jkl"'
106259         **
106260         ** then iLeft will be set to 2 (token number of ghi) and nToken will
106261         ** be set to 4.
106262         */
106263         Fts3Expr *pLeft = pExpr->pLeft;
106264         Fts3Expr *pRight = pExpr->pRight;
106265         int iLeft = *piLeft;
106266         int nNear = pExpr->nNear;
106267         int nToken = pRight->pPhrase->nToken;
106268         int jj, ii;
106269         if( pLeft->eType==FTSQUERY_NEAR ){
106270           pLeft = pLeft->pRight;
106271         }
106272         assert( pRight->eType==FTSQUERY_PHRASE );
106273         assert( pLeft->eType==FTSQUERY_PHRASE );
106274         nToken += pLeft->pPhrase->nToken;
106275
106276         for(ii=0; ii<pSnippet->nMatch; ii++){
106277           struct snippetMatch *p = &pSnippet->aMatch[ii];
106278           if( p->iTerm==iLeft ){
106279             int isOk = 0;
106280             /* Snippet ii is an occurence of query term iLeft in the document.
106281             ** It occurs at position (p->iToken) of the document. We now
106282             ** search for an instance of token (iLeft-1) somewhere in the 
106283             ** range (p->iToken - nNear)...(p->iToken + nNear + nToken) within 
106284             ** the set of snippetMatch structures. If one is found, proceed. 
106285             ** If one cannot be found, then remove snippets ii..(ii+N-1) 
106286             ** from the matching snippets, where N is the number of tokens 
106287             ** in phrase pRight->pPhrase.
106288             */
106289             for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
106290               struct snippetMatch *p2 = &pSnippet->aMatch[jj];
106291               if( p2->iTerm==(iLeft-1) ){
106292                 if( p2->iToken>=(p->iToken-nNear-1) 
106293                  && p2->iToken<(p->iToken+nNear+nToken) 
106294                 ){
106295                   isOk = 1;
106296                 }
106297               }
106298             }
106299             if( !isOk ){
106300               int kk;
106301               for(kk=0; kk<pRight->pPhrase->nToken; kk++){
106302                 pSnippet->aMatch[kk+ii].iTerm = -2;
106303               }
106304               return 1;
106305             }
106306           }
106307           if( p->iTerm==(iLeft-1) ){
106308             int isOk = 0;
106309             for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
106310               struct snippetMatch *p2 = &pSnippet->aMatch[jj];
106311               if( p2->iTerm==iLeft ){
106312                 if( p2->iToken<=(p->iToken+nNear+1) 
106313                  && p2->iToken>(p->iToken-nNear-nToken) 
106314                 ){
106315                   isOk = 1;
106316                 }
106317               }
106318             }
106319             if( !isOk ){
106320               int kk;
106321               for(kk=0; kk<pLeft->pPhrase->nToken; kk++){
106322                 pSnippet->aMatch[ii-kk].iTerm = -2;
106323               }
106324               return 1;
106325             }
106326           }
106327         }
106328         break;
106329       }
106330     }
106331
106332     if( trimSnippetOffsets(pExpr->pRight, pSnippet, piLeft) ){
106333       return 1;
106334     }
106335   }
106336   return 0;
106337 }
106338
106339 /*
106340 ** Compute all offsets for the current row of the query.  
106341 ** If the offsets have already been computed, this routine is a no-op.
106342 */
106343 static int snippetAllOffsets(Fts3Cursor *pCsr, Snippet **ppSnippet){
106344   Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;  /* The FTS3 virtual table */
106345   int nColumn;           /* Number of columns.  Docid does count */
106346   int iColumn;           /* Index of of a column */
106347   int i;                 /* Loop index */
106348   int iFirst;            /* First column to search */
106349   int iLast;             /* Last coumn to search */
106350   int iTerm = 0;
106351   Snippet *pSnippet;
106352   int rc = SQLITE_OK;
106353
106354   if( pCsr->pExpr==0 ){
106355     return SQLITE_OK;
106356   }
106357
106358   pSnippet = (Snippet *)sqlite3_malloc(sizeof(Snippet));
106359   *ppSnippet = pSnippet;
106360   if( !pSnippet ){
106361     return SQLITE_NOMEM;
106362   }
106363   memset(pSnippet, 0, sizeof(Snippet));
106364
106365   nColumn = p->nColumn;
106366   iColumn = (pCsr->eSearch - 2);
106367   if( iColumn<0 || iColumn>=nColumn ){
106368     /* Look for matches over all columns of the full-text index */
106369     iFirst = 0;
106370     iLast = nColumn-1;
106371   }else{
106372     /* Look for matches in the iColumn-th column of the index only */
106373     iFirst = iColumn;
106374     iLast = iColumn;
106375   }
106376   for(i=iFirst; rc==SQLITE_OK && i<=iLast; i++){
106377     const char *zDoc;
106378     int nDoc;
106379     zDoc = (const char*)sqlite3_column_text(pCsr->pStmt, i+1);
106380     nDoc = sqlite3_column_bytes(pCsr->pStmt, i+1);
106381     if( zDoc==0 && sqlite3_column_type(pCsr->pStmt, i+1)!=SQLITE_NULL ){
106382       rc = SQLITE_NOMEM;
106383     }else{
106384       rc = snippetOffsetsOfColumn(pCsr, pSnippet, i, zDoc, nDoc);
106385     }
106386   }
106387
106388   while( trimSnippetOffsets(pCsr->pExpr, pSnippet, &iTerm) ){
106389     iTerm = 0;
106390   }
106391
106392   return rc;
106393 }
106394
106395 /*
106396 ** Convert the information in the aMatch[] array of the snippet
106397 ** into the string zOffset[0..nOffset-1]. This string is used as
106398 ** the return of the SQL offsets() function.
106399 */
106400 static void snippetOffsetText(Snippet *p){
106401   int i;
106402   int cnt = 0;
106403   StringBuffer sb;
106404   char zBuf[200];
106405   if( p->zOffset ) return;
106406   fts3SnippetSbInit(&sb);
106407   for(i=0; i<p->nMatch; i++){
106408     struct snippetMatch *pMatch = &p->aMatch[i];
106409     if( pMatch->iTerm>=0 ){
106410       /* If snippetMatch.iTerm is less than 0, then the match was 
106411       ** discarded as part of processing the NEAR operator (see the 
106412       ** trimSnippetOffsetsForNear() function for details). Ignore 
106413       ** it in this case
106414       */
106415       zBuf[0] = ' ';
106416       sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
106417           pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
106418       fts3SnippetAppend(&sb, zBuf, -1);
106419       cnt++;
106420     }
106421   }
106422   p->zOffset = sb.z;
106423   p->nOffset = sb.z ? sb.nUsed : 0;
106424 }
106425
106426 /*
106427 ** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
106428 ** of matching words some of which might be in zDoc.  zDoc is column
106429 ** number iCol.
106430 **
106431 ** iBreak is suggested spot in zDoc where we could begin or end an
106432 ** excerpt.  Return a value similar to iBreak but possibly adjusted
106433 ** to be a little left or right so that the break point is better.
106434 */
106435 static int wordBoundary(
106436   int iBreak,                   /* The suggested break point */
106437   const char *zDoc,             /* Document text */
106438   int nDoc,                     /* Number of bytes in zDoc[] */
106439   struct snippetMatch *aMatch,  /* Matching words */
106440   int nMatch,                   /* Number of entries in aMatch[] */
106441   int iCol                      /* The column number for zDoc[] */
106442 ){
106443   int i;
106444   if( iBreak<=10 ){
106445     return 0;
106446   }
106447   if( iBreak>=nDoc-10 ){
106448     return nDoc;
106449   }
106450   for(i=0; ALWAYS(i<nMatch) && aMatch[i].iCol<iCol; i++){}
106451   while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
106452   if( i<nMatch ){
106453     if( aMatch[i].iStart<iBreak+10 ){
106454       return aMatch[i].iStart;
106455     }
106456     if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
106457       return aMatch[i-1].iStart;
106458     }
106459   }
106460   for(i=1; i<=10; i++){
106461     if( fts3snippetIsspace(zDoc[iBreak-i]) ){
106462       return iBreak - i + 1;
106463     }
106464     if( fts3snippetIsspace(zDoc[iBreak+i]) ){
106465       return iBreak + i + 1;
106466     }
106467   }
106468   return iBreak;
106469 }
106470
106471
106472
106473 /*
106474 ** Allowed values for Snippet.aMatch[].snStatus
106475 */
106476 #define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
106477 #define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */
106478
106479 /*
106480 ** Generate the text of a snippet.
106481 */
106482 static void snippetText(
106483   Fts3Cursor *pCursor,   /* The cursor we need the snippet for */
106484   Snippet *pSnippet,
106485   const char *zStartMark,     /* Markup to appear before each match */
106486   const char *zEndMark,       /* Markup to appear after each match */
106487   const char *zEllipsis       /* Ellipsis mark */
106488 ){
106489   int i, j;
106490   struct snippetMatch *aMatch;
106491   int nMatch;
106492   int nDesired;
106493   StringBuffer sb;
106494   int tailCol;
106495   int tailOffset;
106496   int iCol;
106497   int nDoc;
106498   const char *zDoc;
106499   int iStart, iEnd;
106500   int tailEllipsis = 0;
106501   int iMatch;
106502   
106503
106504   sqlite3_free(pSnippet->zSnippet);
106505   pSnippet->zSnippet = 0;
106506   aMatch = pSnippet->aMatch;
106507   nMatch = pSnippet->nMatch;
106508   fts3SnippetSbInit(&sb);
106509
106510   for(i=0; i<nMatch; i++){
106511     aMatch[i].snStatus = SNIPPET_IGNORE;
106512   }
106513   nDesired = 0;
106514   for(i=0; i<FTS3_ROTOR_SZ; i++){
106515     for(j=0; j<nMatch; j++){
106516       if( aMatch[j].iTerm==i ){
106517         aMatch[j].snStatus = SNIPPET_DESIRED;
106518         nDesired++;
106519         break;
106520       }
106521     }
106522   }
106523
106524   iMatch = 0;
106525   tailCol = -1;
106526   tailOffset = 0;
106527   for(i=0; i<nMatch && nDesired>0; i++){
106528     if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
106529     nDesired--;
106530     iCol = aMatch[i].iCol;
106531     zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
106532     nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
106533     iStart = aMatch[i].iStart - 40;
106534     iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
106535     if( iStart<=10 ){
106536       iStart = 0;
106537     }
106538     if( iCol==tailCol && iStart<=tailOffset+20 ){
106539       iStart = tailOffset;
106540     }
106541     if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
106542       fts3SnippetTrimWhiteSpace(&sb);
106543       fts3SnippetAppendWhiteSpace(&sb);
106544       fts3SnippetAppend(&sb, zEllipsis, -1);
106545       fts3SnippetAppendWhiteSpace(&sb);
106546     }
106547     iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
106548     iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
106549     if( iEnd>=nDoc-10 ){
106550       iEnd = nDoc;
106551       tailEllipsis = 0;
106552     }else{
106553       tailEllipsis = 1;
106554     }
106555     while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
106556     while( iStart<iEnd ){
106557       while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
106558              && aMatch[iMatch].iCol<=iCol ){
106559         iMatch++;
106560       }
106561       if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
106562              && aMatch[iMatch].iCol==iCol ){
106563         fts3SnippetAppend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
106564         iStart = aMatch[iMatch].iStart;
106565         fts3SnippetAppend(&sb, zStartMark, -1);
106566         fts3SnippetAppend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
106567         fts3SnippetAppend(&sb, zEndMark, -1);
106568         iStart += aMatch[iMatch].nByte;
106569         for(j=iMatch+1; j<nMatch; j++){
106570           if( aMatch[j].iTerm==aMatch[iMatch].iTerm
106571               && aMatch[j].snStatus==SNIPPET_DESIRED ){
106572             nDesired--;
106573             aMatch[j].snStatus = SNIPPET_IGNORE;
106574           }
106575         }
106576       }else{
106577         fts3SnippetAppend(&sb, &zDoc[iStart], iEnd - iStart);
106578         iStart = iEnd;
106579       }
106580     }
106581     tailCol = iCol;
106582     tailOffset = iEnd;
106583   }
106584   fts3SnippetTrimWhiteSpace(&sb);
106585   if( tailEllipsis ){
106586     fts3SnippetAppendWhiteSpace(&sb);
106587     fts3SnippetAppend(&sb, zEllipsis, -1);
106588   }
106589   pSnippet->zSnippet = sb.z;
106590   pSnippet->nSnippet = sb.z ? sb.nUsed : 0;
106591 }
106592
106593 SQLITE_PRIVATE void sqlite3Fts3Offsets(
106594   sqlite3_context *pCtx,          /* SQLite function call context */
106595   Fts3Cursor *pCsr                /* Cursor object */
106596 ){
106597   Snippet *p;                     /* Snippet structure */
106598   int rc = snippetAllOffsets(pCsr, &p);
106599   if( rc==SQLITE_OK ){
106600     snippetOffsetText(p);
106601     if( p->zOffset ){
106602       sqlite3_result_text(pCtx, p->zOffset, p->nOffset, SQLITE_TRANSIENT);
106603     }else{
106604       sqlite3_result_error_nomem(pCtx);
106605     }
106606   }else{
106607     sqlite3_result_error_nomem(pCtx);
106608   }
106609   fts3SnippetFree(p);
106610 }
106611
106612 SQLITE_PRIVATE void sqlite3Fts3Snippet(
106613   sqlite3_context *pCtx,          /* SQLite function call context */
106614   Fts3Cursor *pCsr,               /* Cursor object */
106615   const char *zStart,             /* Snippet start text - "<b>" */
106616   const char *zEnd,               /* Snippet end text - "</b>" */
106617   const char *zEllipsis           /* Snippet ellipsis text - "<b>...</b>" */
106618 ){
106619   Snippet *p;                     /* Snippet structure */
106620   int rc = snippetAllOffsets(pCsr, &p);
106621   if( rc==SQLITE_OK ){
106622     snippetText(pCsr, p, zStart, zEnd, zEllipsis);
106623     if( p->zSnippet ){
106624       sqlite3_result_text(pCtx, p->zSnippet, p->nSnippet, SQLITE_TRANSIENT);
106625     }else{
106626       sqlite3_result_error_nomem(pCtx);
106627     }
106628   }else{
106629     sqlite3_result_error_nomem(pCtx);
106630   }
106631   fts3SnippetFree(p);
106632 }
106633
106634 /*************************************************************************
106635 ** Below this point is the alternative, experimental snippet() implementation.
106636 */
106637
106638 #define SNIPPET_BUFFER_CHUNK  64
106639 #define SNIPPET_BUFFER_SIZE   SNIPPET_BUFFER_CHUNK*4
106640 #define SNIPPET_BUFFER_MASK   (SNIPPET_BUFFER_SIZE-1)
106641
106642 static void fts3GetDeltaPosition(char **pp, int *piPos){
106643   int iVal;
106644   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
106645   *piPos += (iVal-2);
106646 }
106647
106648 /*
106649 ** Iterate through all phrase nodes in an FTS3 query, except those that
106650 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
106651 ** For each phrase node found, the supplied callback function is invoked.
106652 **
106653 ** If the callback function returns anything other than SQLITE_OK, 
106654 ** the iteration is abandoned and the error code returned immediately.
106655 ** Otherwise, SQLITE_OK is returned after a callback has been made for
106656 ** all eligible phrase nodes.
106657 */
106658 static int fts3ExprIterate(
106659   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
106660   int (*x)(Fts3Expr *, void *),   /* Callback function to invoke for phrases */
106661   void *pCtx                      /* Second argument to pass to callback */
106662 ){
106663   int rc;
106664   int eType = pExpr->eType;
106665   if( eType==FTSQUERY_NOT ){
106666     rc = SQLITE_OK;
106667   }else if( eType!=FTSQUERY_PHRASE ){
106668     assert( pExpr->pLeft && pExpr->pRight );
106669     rc = fts3ExprIterate(pExpr->pLeft, x, pCtx);
106670     if( rc==SQLITE_OK ){
106671       rc = fts3ExprIterate(pExpr->pRight, x, pCtx);
106672     }
106673   }else{
106674     rc = x(pExpr, pCtx);
106675   }
106676   return rc;
106677 }
106678
106679 typedef struct LoadDoclistCtx LoadDoclistCtx;
106680 struct LoadDoclistCtx {
106681   Fts3Table *pTab;                /* FTS3 Table */
106682   int nPhrase;                    /* Number of phrases so far */
106683 };
106684
106685 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, void *ctx){
106686   int rc = SQLITE_OK;
106687   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
106688   p->nPhrase++;
106689   if( pExpr->isLoaded==0 ){
106690     rc = sqlite3Fts3ExprLoadDoclist(p->pTab, pExpr);
106691     pExpr->isLoaded = 1;
106692     if( rc==SQLITE_OK && pExpr->aDoclist ){
106693       pExpr->pCurrent = pExpr->aDoclist;
106694       pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent,&pExpr->iCurrent);
106695     }
106696   }
106697   return rc;
106698 }
106699
106700 static int fts3ExprLoadDoclists(Fts3Cursor *pCsr, int *pnPhrase){
106701   int rc;
106702   LoadDoclistCtx sCtx = {0, 0};
106703   sCtx.pTab = (Fts3Table *)pCsr->base.pVtab;
106704   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
106705   *pnPhrase = sCtx.nPhrase;
106706   return rc;
106707 }
106708
106709 /*
106710 ** Each call to this function populates a chunk of a snippet-buffer 
106711 ** SNIPPET_BUFFER_CHUNK bytes in size.
106712 **
106713 ** Return true if the end of the data has been reached (and all subsequent
106714 ** calls to fts3LoadSnippetBuffer() with the same arguments will be no-ops), 
106715 ** or false otherwise.
106716 */
106717 static int fts3LoadSnippetBuffer(
106718   int iPos,                       /* Document token offset to load data for */
106719   u8 *aBuffer,                    /* Circular snippet buffer to populate */
106720   int nList,                      /* Number of position lists in appList */
106721   char **apList,                  /* IN/OUT: nList position list pointers */
106722   int *aiPrev                     /* IN/OUT: Previous positions read */
106723 ){
106724   int i;
106725   int nFin = 0;
106726
106727   assert( (iPos&(SNIPPET_BUFFER_CHUNK-1))==0 );
106728
106729   memset(&aBuffer[iPos&SNIPPET_BUFFER_MASK], 0, SNIPPET_BUFFER_CHUNK);
106730
106731   for(i=0; i<nList; i++){
106732     int iPrev = aiPrev[i];
106733     char *pList = apList[i];
106734
106735     if( !pList ){
106736       nFin++;
106737       continue;
106738     }
106739
106740     while( iPrev<(iPos+SNIPPET_BUFFER_CHUNK) ){
106741       if( iPrev>=iPos ){
106742         aBuffer[iPrev&SNIPPET_BUFFER_MASK] = (u8)(i+1);
106743       }
106744       if( 0==((*pList)&0xFE) ){
106745         nFin++;
106746         break;
106747       }
106748       fts3GetDeltaPosition(&pList, &iPrev); 
106749     }
106750
106751     aiPrev[i] = iPrev;
106752     apList[i] = pList;
106753   }
106754
106755   return (nFin==nList);
106756 }
106757
106758 typedef struct SnippetCtx SnippetCtx;
106759 struct SnippetCtx {
106760   Fts3Cursor *pCsr;
106761   int iCol;
106762   int iPhrase;
106763   int *aiPrev;
106764   int *anToken;
106765   char **apList;
106766 };
106767
106768 static int fts3SnippetFindPositions(Fts3Expr *pExpr, void *ctx){
106769   SnippetCtx *p = (SnippetCtx *)ctx;
106770   int iPhrase = p->iPhrase++;
106771   char *pCsr;
106772
106773   p->anToken[iPhrase] = pExpr->pPhrase->nToken;
106774   pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
106775
106776   if( pCsr ){
106777     int iVal;
106778     pCsr += sqlite3Fts3GetVarint32(pCsr, &iVal);
106779     p->apList[iPhrase] = pCsr;
106780     p->aiPrev[iPhrase] = iVal-2;
106781   }
106782   return SQLITE_OK;
106783 }
106784
106785 static void fts3SnippetCnt(
106786   int iIdx, 
106787   int nSnippet, 
106788   int *anCnt, 
106789   u8 *aBuffer,
106790   int *anToken,
106791   u64 *pHlmask
106792 ){
106793   int iSub =  (iIdx-1)&SNIPPET_BUFFER_MASK;
106794   int iAdd =  (iIdx+nSnippet-1)&SNIPPET_BUFFER_MASK;
106795   int iSub2 = (iIdx+(nSnippet/3)-1)&SNIPPET_BUFFER_MASK;
106796   int iAdd2 = (iIdx+(nSnippet*2/3)-1)&SNIPPET_BUFFER_MASK;
106797
106798   u64 h = *pHlmask;
106799
106800   anCnt[ aBuffer[iSub]  ]--;
106801   anCnt[ aBuffer[iSub2] ]--;
106802   anCnt[ aBuffer[iAdd]  ]++;
106803   anCnt[ aBuffer[iAdd2] ]++;
106804
106805   h = h >> 1;
106806   if( aBuffer[iAdd] ){
106807     int j;
106808     for(j=anToken[aBuffer[iAdd]-1]; j>=1; j--){
106809       h |= (u64)1 << (nSnippet-j);
106810     }
106811   }
106812   *pHlmask = h;
106813 }
106814
106815 static int fts3SnippetScore(int n, int *anCnt){
106816   int j;
106817   int iScore = 0;
106818   for(j=1; j<=n; j++){
106819     int nCnt = anCnt[j];
106820     iScore += nCnt + (nCnt ? 1000 : 0);
106821   }
106822   return iScore;
106823 }
106824
106825 static int fts3BestSnippet(
106826   int nSnippet,                   /* Desired snippet length */
106827   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
106828   int iCol,                       /* Index of column to create snippet from */
106829   int *piPos,                     /* OUT: Starting token for best snippet */
106830   u64 *pHlmask                    /* OUT: Highlight mask for best snippet */
106831 ){
106832   int rc;                         /* Return Code */
106833   u8 aBuffer[SNIPPET_BUFFER_SIZE];/* Circular snippet buffer */
106834   int *aiPrev;                    /* Used by fts3LoadSnippetBuffer() */
106835   int *anToken;                   /* Number of tokens in each phrase */
106836   char **apList;                  /* Array of position lists */
106837   int *anCnt;                     /* Running totals of phrase occurences */
106838   int nList;
106839
106840   int i;
106841
106842   u64 hlmask = 0;                 /* Current mask of highlighted terms */
106843   u64 besthlmask = 0;             /* Mask of highlighted terms for iBestPos */
106844   int iBestPos = 0;               /* Starting position of 'best' snippet */
106845   int iBestScore = 0;             /* Score of best snippet higher->better */
106846   SnippetCtx sCtx;
106847
106848   /* Iterate through the phrases in the expression to count them. The same
106849   ** callback makes sure the doclists are loaded for each phrase.
106850   */
106851   rc = fts3ExprLoadDoclists(pCsr, &nList);
106852   if( rc!=SQLITE_OK ){
106853     return rc;
106854   }
106855
106856   /* Now that it is known how many phrases there are, allocate and zero
106857   ** the required arrays using malloc().
106858   */
106859   apList = sqlite3_malloc(
106860       sizeof(u8*)*nList +         /* apList */
106861       sizeof(int)*(nList) +       /* anToken */
106862       sizeof(int)*nList +         /* aiPrev */
106863       sizeof(int)*(nList+1)       /* anCnt */
106864   );
106865   if( !apList ){
106866     return SQLITE_NOMEM;
106867   }
106868   memset(apList, 0, sizeof(u8*)*nList+sizeof(int)*nList+sizeof(int)*nList);
106869   anToken = (int *)&apList[nList];
106870   aiPrev = &anToken[nList];
106871   anCnt = &aiPrev[nList];
106872
106873   /* Initialize the contents of the aiPrev and aiList arrays. */
106874   sCtx.pCsr = pCsr;
106875   sCtx.iCol = iCol;
106876   sCtx.apList = apList;
106877   sCtx.aiPrev = aiPrev;
106878   sCtx.anToken = anToken;
106879   sCtx.iPhrase = 0;
106880   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sCtx);
106881
106882   /* Load the first two chunks of data into the buffer. */
106883   memset(aBuffer, 0, SNIPPET_BUFFER_SIZE);
106884   fts3LoadSnippetBuffer(0, aBuffer, nList, apList, aiPrev);
106885   fts3LoadSnippetBuffer(SNIPPET_BUFFER_CHUNK, aBuffer, nList, apList, aiPrev);
106886
106887   /* Set the initial contents of the highlight-mask and anCnt[] array. */
106888   for(i=1-nSnippet; i<=0; i++){
106889     fts3SnippetCnt(i, nSnippet, anCnt, aBuffer, anToken, &hlmask);
106890   }
106891   iBestScore = fts3SnippetScore(nList, anCnt);
106892   besthlmask = hlmask;
106893   iBestPos = 0;
106894
106895   for(i=1; 1; i++){
106896     int iScore;
106897
106898     if( 0==(i&(SNIPPET_BUFFER_CHUNK-1)) ){
106899       int iLoad = i + SNIPPET_BUFFER_CHUNK;
106900       if( fts3LoadSnippetBuffer(iLoad, aBuffer, nList, apList, aiPrev) ) break;
106901     }
106902
106903     /* Figure out how highly a snippet starting at token offset i scores
106904     ** according to fts3SnippetScore(). If it is higher than any previously
106905     ** considered position, save the current position, score and hlmask as 
106906     ** the best snippet candidate found so far.
106907     */
106908     fts3SnippetCnt(i, nSnippet, anCnt, aBuffer, anToken, &hlmask);
106909     iScore = fts3SnippetScore(nList, anCnt);
106910     if( iScore>iBestScore ){
106911       iBestPos = i;
106912       iBestScore = iScore;
106913       besthlmask = hlmask;
106914     }
106915   }
106916
106917   sqlite3_free(apList);
106918   *piPos = iBestPos;
106919   *pHlmask = besthlmask;
106920   return SQLITE_OK;
106921 }
106922
106923 typedef struct StrBuffer StrBuffer;
106924 struct StrBuffer {
106925   char *z;
106926   int n;
106927   int nAlloc;
106928 };
106929
106930 static int fts3StringAppend(
106931   StrBuffer *pStr, 
106932   const char *zAppend, 
106933   int nAppend
106934 ){
106935   if( nAppend<0 ){
106936     nAppend = (int)strlen(zAppend);
106937   }
106938
106939   if( pStr->n+nAppend+1>=pStr->nAlloc ){
106940     int nAlloc = pStr->nAlloc+nAppend+100;
106941     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
106942     if( !zNew ){
106943       return SQLITE_NOMEM;
106944     }
106945     pStr->z = zNew;
106946     pStr->nAlloc = nAlloc;
106947   }
106948
106949   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
106950   pStr->n += nAppend;
106951   pStr->z[pStr->n] = '\0';
106952
106953   return SQLITE_OK;
106954 }
106955
106956 static int fts3SnippetText(
106957   Fts3Cursor *pCsr,               /* FTS3 Cursor */
106958   const char *zDoc,               /* Document to extract snippet from */
106959   int nDoc,                       /* Size of zDoc in bytes */
106960   int nSnippet,                   /* Number of tokens in extracted snippet */
106961   int iPos,                       /* Index of first document token in snippet */
106962   u64 hlmask,                     /* Bitmask of terms to highlight in snippet */
106963   const char *zOpen,              /* String inserted before highlighted term */
106964   const char *zClose,             /* String inserted after highlighted term */
106965   const char *zEllipsis,
106966   char **pzSnippet                /* OUT: Snippet text */
106967 ){
106968   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
106969   int rc;                         /* Return code */
106970   int iCurrent = 0;
106971   int iStart = 0;
106972   int iEnd;
106973
106974   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
106975   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
106976   const char *ZDUMMY;             /* Dummy arguments used with tokenizer */
106977   int DUMMY1, DUMMY2, DUMMY3;     /* Dummy arguments used with tokenizer */
106978
106979   StrBuffer res = {0, 0, 0};   /* Result string */
106980
106981   /* Open a token cursor on the document. Read all tokens up to and 
106982   ** including token iPos (the first token of the snippet). Set variable
106983   ** iStart to the byte offset in zDoc of the start of token iPos.
106984   */
106985   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
106986   rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
106987   while( rc==SQLITE_OK && iCurrent<iPos ){
106988     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iStart, &DUMMY2, &iCurrent);
106989   }
106990   iEnd = iStart;
106991
106992   if( rc==SQLITE_OK && iStart>0 ){
106993     rc = fts3StringAppend(&res, zEllipsis, -1);
106994   }
106995
106996   while( rc==SQLITE_OK ){
106997     int iBegin;
106998     int iFin;
106999     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
107000
107001     if( rc==SQLITE_OK ){
107002       if( iCurrent>=(iPos+nSnippet) ){
107003         rc = SQLITE_DONE;
107004       }else{
107005         iEnd = iFin;
107006         if( hlmask & ((u64)1 << (iCurrent-iPos)) ){
107007           if( fts3StringAppend(&res, &zDoc[iStart], iBegin-iStart)
107008            || fts3StringAppend(&res, zOpen, -1)
107009            || fts3StringAppend(&res, &zDoc[iBegin], iEnd-iBegin)
107010            || fts3StringAppend(&res, zClose, -1)
107011           ){
107012             rc = SQLITE_NOMEM;
107013           }
107014           iStart = iEnd;
107015         }
107016       }
107017     }
107018   }
107019   assert( rc!=SQLITE_OK );
107020   if( rc==SQLITE_DONE ){
107021     rc = fts3StringAppend(&res, &zDoc[iStart], iEnd-iStart);
107022     if( rc==SQLITE_OK ){
107023       rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
107024       if( rc==SQLITE_OK ){
107025         rc = fts3StringAppend(&res, zEllipsis, -1);
107026       }else if( rc==SQLITE_DONE ){
107027         rc = fts3StringAppend(&res, &zDoc[iEnd], -1);
107028       }
107029     }
107030   }
107031
107032   pMod->xClose(pC);
107033   if( rc!=SQLITE_OK ){
107034     sqlite3_free(res.z);
107035   }else{
107036     *pzSnippet = res.z;
107037   }
107038   return rc;
107039 }
107040
107041
107042 /*
107043 ** An instance of this structure is used to collect the 'global' part of
107044 ** the matchinfo statistics. The 'global' part consists of the following:
107045 **
107046 **   1. The number of phrases in the query (nPhrase).
107047 **
107048 **   2. The number of columns in the FTS3 table (nCol).
107049 **
107050 **   3. A matrix of (nPhrase*nCol) integers containing the sum of the
107051 **      number of hits for each phrase in each column across all rows
107052 **      of the table.
107053 **
107054 ** The total size of the global matchinfo array, assuming the number of
107055 ** columns is N and the number of phrases is P is:
107056 **
107057 **   2 + P*(N+1)
107058 **
107059 ** The number of hits for the 3rd phrase in the second column is found
107060 ** using the expression:
107061 **
107062 **   aGlobal[2 + P*(1+2) + 1]
107063 */
107064 typedef struct MatchInfo MatchInfo;
107065 struct MatchInfo {
107066   Fts3Table *pTab;                /* FTS3 Table */
107067   Fts3Cursor *pCursor;            /* FTS3 Cursor */
107068   int iPhrase;                    /* Number of phrases so far */
107069   int nCol;                       /* Number of columns in table */
107070   u32 *aGlobal;                   /* Pre-allocated buffer */
107071 };
107072
107073 /*
107074 ** This function is used to count the entries in a column-list (delta-encoded
107075 ** list of term offsets within a single column of a single row).
107076 */
107077 static int fts3ColumnlistCount(char **ppCollist){
107078   char *pEnd = *ppCollist;
107079   char c = 0;
107080   int nEntry = 0;
107081
107082   /* A column-list is terminated by either a 0x01 or 0x00. */
107083   while( 0xFE & (*pEnd | c) ){
107084     c = *pEnd++ & 0x80;
107085     if( !c ) nEntry++;
107086   }
107087
107088   *ppCollist = pEnd;
107089   return nEntry;
107090 }
107091
107092 static void fts3LoadColumnlistCounts(char **pp, u32 *aOut){
107093   char *pCsr = *pp;
107094   while( *pCsr ){
107095     sqlite3_int64 iCol = 0;
107096     if( *pCsr==0x01 ){
107097       pCsr++;
107098       pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
107099     }
107100     aOut[iCol] += fts3ColumnlistCount(&pCsr);
107101   }
107102   pCsr++;
107103   *pp = pCsr;
107104 }
107105
107106 /*
107107 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
107108 ** for a single query.
107109 */
107110 static int fts3ExprGlobalMatchinfoCb(
107111   Fts3Expr *pExpr,                /* Phrase expression node */
107112   void *pCtx                      /* Pointer to MatchInfo structure */
107113 ){
107114   MatchInfo *p = (MatchInfo *)pCtx;
107115   char *pCsr;
107116   char *pEnd;
107117   const int iStart = 2 + p->nCol*p->iPhrase;
107118
107119   assert( pExpr->isLoaded );
107120
107121   /* Fill in the global hit count matrix row for this phrase. */
107122   pCsr = pExpr->aDoclist;
107123   pEnd = &pExpr->aDoclist[pExpr->nDoclist];
107124   while( pCsr<pEnd ){
107125     while( *pCsr++ & 0x80 );
107126     fts3LoadColumnlistCounts(&pCsr, &p->aGlobal[iStart]);
107127   }
107128
107129   p->iPhrase++;
107130   return SQLITE_OK;
107131 }
107132
107133 static int fts3ExprLocalMatchinfoCb(
107134   Fts3Expr *pExpr,                /* Phrase expression node */
107135   void *pCtx                      /* Pointer to MatchInfo structure */
107136 ){
107137   MatchInfo *p = (MatchInfo *)pCtx;
107138   int iPhrase = p->iPhrase++;
107139
107140   if( pExpr->aDoclist ){
107141     char *pCsr;
107142     int iOffset = 2 + p->nCol*(p->aGlobal[0]+iPhrase);
107143
107144     memset(&p->aGlobal[iOffset], 0, p->nCol*sizeof(u32));
107145     pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
107146     if( pCsr ) fts3LoadColumnlistCounts(&pCsr, &p->aGlobal[iOffset]);
107147   }
107148
107149   return SQLITE_OK;
107150 }
107151
107152 /*
107153 ** Populate pCsr->aMatchinfo[] with data for the current row. The 'matchinfo'
107154 ** data is an array of 32-bit unsigned integers (C type u32).
107155 */
107156 static int fts3GetMatchinfo(Fts3Cursor *pCsr){
107157   MatchInfo g;
107158   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
107159   if( pCsr->aMatchinfo==0 ){
107160     int rc;
107161     int nPhrase;
107162     int nMatchinfo;
107163
107164     g.pTab = pTab;
107165     g.nCol = pTab->nColumn;
107166     g.iPhrase = 0;
107167     rc = fts3ExprLoadDoclists(pCsr, &nPhrase);
107168     if( rc!=SQLITE_OK ){
107169       return rc;
107170     }
107171
107172     nMatchinfo = 2 + 2*g.nCol*nPhrase;
107173
107174     g.iPhrase = 0;
107175     g.aGlobal = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo);
107176     if( !g.aGlobal ){ 
107177       return SQLITE_NOMEM;
107178     }
107179     memset(g.aGlobal, 0, sizeof(u32)*nMatchinfo);
107180
107181     g.aGlobal[0] = nPhrase;
107182     g.aGlobal[1] = g.nCol;
107183     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprGlobalMatchinfoCb, (void *)&g);
107184
107185     pCsr->aMatchinfo = g.aGlobal;
107186   }
107187
107188   g.pTab = pTab;
107189   g.pCursor = pCsr;
107190   g.nCol = pTab->nColumn;
107191   g.iPhrase = 0;
107192   g.aGlobal = pCsr->aMatchinfo;
107193
107194   if( pCsr->isMatchinfoOk ){
107195     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLocalMatchinfoCb, (void *)&g);
107196     pCsr->isMatchinfoOk = 0;
107197   }
107198
107199   return SQLITE_OK;
107200 }
107201
107202 SQLITE_PRIVATE void sqlite3Fts3Snippet2(
107203   sqlite3_context *pCtx,          /* SQLite function call context */
107204   Fts3Cursor *pCsr,               /* Cursor object */
107205   const char *zStart,             /* Snippet start text - "<b>" */
107206   const char *zEnd,               /* Snippet end text - "</b>" */
107207   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
107208   int iCol,                       /* Extract snippet from this column */
107209   int nToken                      /* Approximate number of tokens in snippet */
107210 ){
107211   int rc;
107212   int iPos = 0;
107213   u64 hlmask = 0;
107214   char *z = 0;
107215   int nDoc;
107216   const char *zDoc;
107217
107218   rc = fts3BestSnippet(nToken, pCsr, iCol, &iPos, &hlmask);
107219
107220   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
107221   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
107222
107223   if( rc==SQLITE_OK ){
107224     rc = fts3SnippetText(
107225         pCsr, zDoc, nDoc, nToken, iPos, hlmask, zStart, zEnd, zEllipsis, &z);
107226   }
107227   if( rc!=SQLITE_OK ){
107228     sqlite3_result_error_code(pCtx, rc);
107229   }else{
107230     sqlite3_result_text(pCtx, z, -1, sqlite3_free);
107231   }
107232 }
107233
107234 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *pContext, Fts3Cursor *pCsr){
107235   int rc = fts3GetMatchinfo(pCsr);
107236   if( rc!=SQLITE_OK ){
107237     sqlite3_result_error_code(pContext, rc);
107238   }else{
107239     int n = sizeof(u32)*(2+pCsr->aMatchinfo[0]*pCsr->aMatchinfo[1]*2);
107240     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
107241   }
107242 }
107243
107244 #endif
107245
107246 /************** End of fts3_snippet.c ****************************************/
107247 /************** Begin file rtree.c *******************************************/
107248 /*
107249 ** 2001 September 15
107250 **
107251 ** The author disclaims copyright to this source code.  In place of
107252 ** a legal notice, here is a blessing:
107253 **
107254 **    May you do good and not evil.
107255 **    May you find forgiveness for yourself and forgive others.
107256 **    May you share freely, never taking more than you give.
107257 **
107258 *************************************************************************
107259 ** This file contains code for implementations of the r-tree and r*-tree
107260 ** algorithms packaged as an SQLite virtual table module.
107261 */
107262
107263 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
107264
107265 /*
107266 ** This file contains an implementation of a couple of different variants
107267 ** of the r-tree algorithm. See the README file for further details. The 
107268 ** same data-structure is used for all, but the algorithms for insert and
107269 ** delete operations vary. The variants used are selected at compile time 
107270 ** by defining the following symbols:
107271 */
107272
107273 /* Either, both or none of the following may be set to activate 
107274 ** r*tree variant algorithms.
107275 */
107276 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
107277 #define VARIANT_RSTARTREE_REINSERT      1
107278
107279 /* 
107280 ** Exactly one of the following must be set to 1.
107281 */
107282 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
107283 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
107284 #define VARIANT_RSTARTREE_SPLIT         1
107285
107286 #define VARIANT_GUTTMAN_SPLIT \
107287         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
107288
107289 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
107290   #define PickNext QuadraticPickNext
107291   #define PickSeeds QuadraticPickSeeds
107292   #define AssignCells splitNodeGuttman
107293 #endif
107294 #if VARIANT_GUTTMAN_LINEAR_SPLIT
107295   #define PickNext LinearPickNext
107296   #define PickSeeds LinearPickSeeds
107297   #define AssignCells splitNodeGuttman
107298 #endif
107299 #if VARIANT_RSTARTREE_SPLIT
107300   #define AssignCells splitNodeStartree
107301 #endif
107302
107303
107304 #ifndef SQLITE_CORE
107305   SQLITE_EXTENSION_INIT1
107306 #else
107307 #endif
107308
107309
107310 #ifndef SQLITE_AMALGAMATION
107311 typedef sqlite3_int64 i64;
107312 typedef unsigned char u8;
107313 typedef unsigned int u32;
107314 #endif
107315
107316 typedef struct Rtree Rtree;
107317 typedef struct RtreeCursor RtreeCursor;
107318 typedef struct RtreeNode RtreeNode;
107319 typedef struct RtreeCell RtreeCell;
107320 typedef struct RtreeConstraint RtreeConstraint;
107321 typedef union RtreeCoord RtreeCoord;
107322
107323 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
107324 #define RTREE_MAX_DIMENSIONS 5
107325
107326 /* Size of hash table Rtree.aHash. This hash table is not expected to
107327 ** ever contain very many entries, so a fixed number of buckets is 
107328 ** used.
107329 */
107330 #define HASHSIZE 128
107331
107332 /* 
107333 ** An rtree virtual-table object.
107334 */
107335 struct Rtree {
107336   sqlite3_vtab base;
107337   sqlite3 *db;                /* Host database connection */
107338   int iNodeSize;              /* Size in bytes of each node in the node table */
107339   int nDim;                   /* Number of dimensions */
107340   int nBytesPerCell;          /* Bytes consumed per cell */
107341   int iDepth;                 /* Current depth of the r-tree structure */
107342   char *zDb;                  /* Name of database containing r-tree table */
107343   char *zName;                /* Name of r-tree table */ 
107344   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
107345   int nBusy;                  /* Current number of users of this structure */
107346
107347   /* List of nodes removed during a CondenseTree operation. List is
107348   ** linked together via the pointer normally used for hash chains -
107349   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
107350   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
107351   */
107352   RtreeNode *pDeleted;
107353   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
107354
107355   /* Statements to read/write/delete a record from xxx_node */
107356   sqlite3_stmt *pReadNode;
107357   sqlite3_stmt *pWriteNode;
107358   sqlite3_stmt *pDeleteNode;
107359
107360   /* Statements to read/write/delete a record from xxx_rowid */
107361   sqlite3_stmt *pReadRowid;
107362   sqlite3_stmt *pWriteRowid;
107363   sqlite3_stmt *pDeleteRowid;
107364
107365   /* Statements to read/write/delete a record from xxx_parent */
107366   sqlite3_stmt *pReadParent;
107367   sqlite3_stmt *pWriteParent;
107368   sqlite3_stmt *pDeleteParent;
107369
107370   int eCoordType;
107371 };
107372
107373 /* Possible values for eCoordType: */
107374 #define RTREE_COORD_REAL32 0
107375 #define RTREE_COORD_INT32  1
107376
107377 /*
107378 ** The minimum number of cells allowed for a node is a third of the 
107379 ** maximum. In Gutman's notation:
107380 **
107381 **     m = M/3
107382 **
107383 ** If an R*-tree "Reinsert" operation is required, the same number of
107384 ** cells are removed from the overfull node and reinserted into the tree.
107385 */
107386 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
107387 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
107388 #define RTREE_MAXCELLS 51
107389
107390 /* 
107391 ** An rtree cursor object.
107392 */
107393 struct RtreeCursor {
107394   sqlite3_vtab_cursor base;
107395   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
107396   int iCell;                        /* Index of current cell in pNode */
107397   int iStrategy;                    /* Copy of idxNum search parameter */
107398   int nConstraint;                  /* Number of entries in aConstraint */
107399   RtreeConstraint *aConstraint;     /* Search constraints. */
107400 };
107401
107402 union RtreeCoord {
107403   float f;
107404   int i;
107405 };
107406
107407 /*
107408 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
107409 ** formatted as a double. This macro assumes that local variable pRtree points
107410 ** to the Rtree structure associated with the RtreeCoord.
107411 */
107412 #define DCOORD(coord) (                           \
107413   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
107414     ((double)coord.f) :                           \
107415     ((double)coord.i)                             \
107416 )
107417
107418 /*
107419 ** A search constraint.
107420 */
107421 struct RtreeConstraint {
107422   int iCoord;                       /* Index of constrained coordinate */
107423   int op;                           /* Constraining operation */
107424   double rValue;                    /* Constraint value. */
107425 };
107426
107427 /* Possible values for RtreeConstraint.op */
107428 #define RTREE_EQ 0x41
107429 #define RTREE_LE 0x42
107430 #define RTREE_LT 0x43
107431 #define RTREE_GE 0x44
107432 #define RTREE_GT 0x45
107433
107434 /* 
107435 ** An rtree structure node.
107436 **
107437 ** Data format (RtreeNode.zData):
107438 **
107439 **   1. If the node is the root node (node 1), then the first 2 bytes
107440 **      of the node contain the tree depth as a big-endian integer.
107441 **      For non-root nodes, the first 2 bytes are left unused.
107442 **
107443 **   2. The next 2 bytes contain the number of entries currently 
107444 **      stored in the node.
107445 **
107446 **   3. The remainder of the node contains the node entries. Each entry
107447 **      consists of a single 8-byte integer followed by an even number
107448 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
107449 **      of a record. For internal nodes it is the node number of a
107450 **      child page.
107451 */
107452 struct RtreeNode {
107453   RtreeNode *pParent;               /* Parent node */
107454   i64 iNode;
107455   int nRef;
107456   int isDirty;
107457   u8 *zData;
107458   RtreeNode *pNext;                 /* Next node in this hash chain */
107459 };
107460 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
107461
107462 /* 
107463 ** Structure to store a deserialized rtree record.
107464 */
107465 struct RtreeCell {
107466   i64 iRowid;
107467   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
107468 };
107469
107470 #ifndef MAX
107471 # define MAX(x,y) ((x) < (y) ? (y) : (x))
107472 #endif
107473 #ifndef MIN
107474 # define MIN(x,y) ((x) > (y) ? (y) : (x))
107475 #endif
107476
107477 /*
107478 ** Functions to deserialize a 16 bit integer, 32 bit real number and
107479 ** 64 bit integer. The deserialized value is returned.
107480 */
107481 static int readInt16(u8 *p){
107482   return (p[0]<<8) + p[1];
107483 }
107484 static void readCoord(u8 *p, RtreeCoord *pCoord){
107485   u32 i = (
107486     (((u32)p[0]) << 24) + 
107487     (((u32)p[1]) << 16) + 
107488     (((u32)p[2]) <<  8) + 
107489     (((u32)p[3]) <<  0)
107490   );
107491   *(u32 *)pCoord = i;
107492 }
107493 static i64 readInt64(u8 *p){
107494   return (
107495     (((i64)p[0]) << 56) + 
107496     (((i64)p[1]) << 48) + 
107497     (((i64)p[2]) << 40) + 
107498     (((i64)p[3]) << 32) + 
107499     (((i64)p[4]) << 24) + 
107500     (((i64)p[5]) << 16) + 
107501     (((i64)p[6]) <<  8) + 
107502     (((i64)p[7]) <<  0)
107503   );
107504 }
107505
107506 /*
107507 ** Functions to serialize a 16 bit integer, 32 bit real number and
107508 ** 64 bit integer. The value returned is the number of bytes written
107509 ** to the argument buffer (always 2, 4 and 8 respectively).
107510 */
107511 static int writeInt16(u8 *p, int i){
107512   p[0] = (i>> 8)&0xFF;
107513   p[1] = (i>> 0)&0xFF;
107514   return 2;
107515 }
107516 static int writeCoord(u8 *p, RtreeCoord *pCoord){
107517   u32 i;
107518   assert( sizeof(RtreeCoord)==4 );
107519   assert( sizeof(u32)==4 );
107520   i = *(u32 *)pCoord;
107521   p[0] = (i>>24)&0xFF;
107522   p[1] = (i>>16)&0xFF;
107523   p[2] = (i>> 8)&0xFF;
107524   p[3] = (i>> 0)&0xFF;
107525   return 4;
107526 }
107527 static int writeInt64(u8 *p, i64 i){
107528   p[0] = (i>>56)&0xFF;
107529   p[1] = (i>>48)&0xFF;
107530   p[2] = (i>>40)&0xFF;
107531   p[3] = (i>>32)&0xFF;
107532   p[4] = (i>>24)&0xFF;
107533   p[5] = (i>>16)&0xFF;
107534   p[6] = (i>> 8)&0xFF;
107535   p[7] = (i>> 0)&0xFF;
107536   return 8;
107537 }
107538
107539 /*
107540 ** Increment the reference count of node p.
107541 */
107542 static void nodeReference(RtreeNode *p){
107543   if( p ){
107544     p->nRef++;
107545   }
107546 }
107547
107548 /*
107549 ** Clear the content of node p (set all bytes to 0x00).
107550 */
107551 static void nodeZero(Rtree *pRtree, RtreeNode *p){
107552   if( p ){
107553     memset(&p->zData[2], 0, pRtree->iNodeSize-2);
107554     p->isDirty = 1;
107555   }
107556 }
107557
107558 /*
107559 ** Given a node number iNode, return the corresponding key to use
107560 ** in the Rtree.aHash table.
107561 */
107562 static int nodeHash(i64 iNode){
107563   return (
107564     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
107565     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
107566   ) % HASHSIZE;
107567 }
107568
107569 /*
107570 ** Search the node hash table for node iNode. If found, return a pointer
107571 ** to it. Otherwise, return 0.
107572 */
107573 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
107574   RtreeNode *p;
107575   assert( iNode!=0 );
107576   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
107577   return p;
107578 }
107579
107580 /*
107581 ** Add node pNode to the node hash table.
107582 */
107583 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
107584   if( pNode ){
107585     int iHash;
107586     assert( pNode->pNext==0 );
107587     iHash = nodeHash(pNode->iNode);
107588     pNode->pNext = pRtree->aHash[iHash];
107589     pRtree->aHash[iHash] = pNode;
107590   }
107591 }
107592
107593 /*
107594 ** Remove node pNode from the node hash table.
107595 */
107596 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
107597   RtreeNode **pp;
107598   if( pNode->iNode!=0 ){
107599     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
107600     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
107601     *pp = pNode->pNext;
107602     pNode->pNext = 0;
107603   }
107604 }
107605
107606 /*
107607 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
107608 ** indicating that node has not yet been assigned a node number. It is
107609 ** assigned a node number when nodeWrite() is called to write the
107610 ** node contents out to the database.
107611 */
107612 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
107613   RtreeNode *pNode;
107614   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
107615   if( pNode ){
107616     memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
107617     pNode->zData = (u8 *)&pNode[1];
107618     pNode->nRef = 1;
107619     pNode->pParent = pParent;
107620     pNode->isDirty = 1;
107621     nodeReference(pParent);
107622   }
107623   return pNode;
107624 }
107625
107626 /*
107627 ** Obtain a reference to an r-tree node.
107628 */
107629 static int
107630 nodeAcquire(
107631   Rtree *pRtree,             /* R-tree structure */
107632   i64 iNode,                 /* Node number to load */
107633   RtreeNode *pParent,        /* Either the parent node or NULL */
107634   RtreeNode **ppNode         /* OUT: Acquired node */
107635 ){
107636   int rc;
107637   RtreeNode *pNode;
107638
107639   /* Check if the requested node is already in the hash table. If so,
107640   ** increase its reference count and return it.
107641   */
107642   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
107643     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
107644     if( pParent && !pNode->pParent ){
107645       nodeReference(pParent);
107646       pNode->pParent = pParent;
107647     }
107648     pNode->nRef++;
107649     *ppNode = pNode;
107650     return SQLITE_OK;
107651   }
107652
107653   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
107654   if( !pNode ){
107655     *ppNode = 0;
107656     return SQLITE_NOMEM;
107657   }
107658   pNode->pParent = pParent;
107659   pNode->zData = (u8 *)&pNode[1];
107660   pNode->nRef = 1;
107661   pNode->iNode = iNode;
107662   pNode->isDirty = 0;
107663   pNode->pNext = 0;
107664
107665   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
107666   rc = sqlite3_step(pRtree->pReadNode);
107667   if( rc==SQLITE_ROW ){
107668     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
107669     memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
107670     nodeReference(pParent);
107671   }else{
107672     sqlite3_free(pNode);
107673     pNode = 0;
107674   }
107675
107676   *ppNode = pNode;
107677   rc = sqlite3_reset(pRtree->pReadNode);
107678
107679   if( rc==SQLITE_OK && iNode==1 ){
107680     pRtree->iDepth = readInt16(pNode->zData);
107681   }
107682
107683   assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
107684   nodeHashInsert(pRtree, pNode);
107685
107686   return rc;
107687 }
107688
107689 /*
107690 ** Overwrite cell iCell of node pNode with the contents of pCell.
107691 */
107692 static void nodeOverwriteCell(
107693   Rtree *pRtree, 
107694   RtreeNode *pNode,  
107695   RtreeCell *pCell, 
107696   int iCell
107697 ){
107698   int ii;
107699   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
107700   p += writeInt64(p, pCell->iRowid);
107701   for(ii=0; ii<(pRtree->nDim*2); ii++){
107702     p += writeCoord(p, &pCell->aCoord[ii]);
107703   }
107704   pNode->isDirty = 1;
107705 }
107706
107707 /*
107708 ** Remove cell the cell with index iCell from node pNode.
107709 */
107710 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
107711   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
107712   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
107713   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
107714   memmove(pDst, pSrc, nByte);
107715   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
107716   pNode->isDirty = 1;
107717 }
107718
107719 /*
107720 ** Insert the contents of cell pCell into node pNode. If the insert
107721 ** is successful, return SQLITE_OK.
107722 **
107723 ** If there is not enough free space in pNode, return SQLITE_FULL.
107724 */
107725 static int
107726 nodeInsertCell(
107727   Rtree *pRtree, 
107728   RtreeNode *pNode, 
107729   RtreeCell *pCell 
107730 ){
107731   int nCell;                    /* Current number of cells in pNode */
107732   int nMaxCell;                 /* Maximum number of cells for pNode */
107733
107734   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
107735   nCell = NCELL(pNode);
107736
107737   assert(nCell<=nMaxCell);
107738
107739   if( nCell<nMaxCell ){
107740     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
107741     writeInt16(&pNode->zData[2], nCell+1);
107742     pNode->isDirty = 1;
107743   }
107744
107745   return (nCell==nMaxCell);
107746 }
107747
107748 /*
107749 ** If the node is dirty, write it out to the database.
107750 */
107751 static int
107752 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
107753   int rc = SQLITE_OK;
107754   if( pNode->isDirty ){
107755     sqlite3_stmt *p = pRtree->pWriteNode;
107756     if( pNode->iNode ){
107757       sqlite3_bind_int64(p, 1, pNode->iNode);
107758     }else{
107759       sqlite3_bind_null(p, 1);
107760     }
107761     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
107762     sqlite3_step(p);
107763     pNode->isDirty = 0;
107764     rc = sqlite3_reset(p);
107765     if( pNode->iNode==0 && rc==SQLITE_OK ){
107766       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
107767       nodeHashInsert(pRtree, pNode);
107768     }
107769   }
107770   return rc;
107771 }
107772
107773 /*
107774 ** Release a reference to a node. If the node is dirty and the reference
107775 ** count drops to zero, the node data is written to the database.
107776 */
107777 static int
107778 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
107779   int rc = SQLITE_OK;
107780   if( pNode ){
107781     assert( pNode->nRef>0 );
107782     pNode->nRef--;
107783     if( pNode->nRef==0 ){
107784       if( pNode->iNode==1 ){
107785         pRtree->iDepth = -1;
107786       }
107787       if( pNode->pParent ){
107788         rc = nodeRelease(pRtree, pNode->pParent);
107789       }
107790       if( rc==SQLITE_OK ){
107791         rc = nodeWrite(pRtree, pNode);
107792       }
107793       nodeHashDelete(pRtree, pNode);
107794       sqlite3_free(pNode);
107795     }
107796   }
107797   return rc;
107798 }
107799
107800 /*
107801 ** Return the 64-bit integer value associated with cell iCell of
107802 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
107803 ** an internal node, then the 64-bit integer is a child page number.
107804 */
107805 static i64 nodeGetRowid(
107806   Rtree *pRtree, 
107807   RtreeNode *pNode, 
107808   int iCell
107809 ){
107810   assert( iCell<NCELL(pNode) );
107811   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
107812 }
107813
107814 /*
107815 ** Return coordinate iCoord from cell iCell in node pNode.
107816 */
107817 static void nodeGetCoord(
107818   Rtree *pRtree, 
107819   RtreeNode *pNode, 
107820   int iCell,
107821   int iCoord,
107822   RtreeCoord *pCoord           /* Space to write result to */
107823 ){
107824   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
107825 }
107826
107827 /*
107828 ** Deserialize cell iCell of node pNode. Populate the structure pointed
107829 ** to by pCell with the results.
107830 */
107831 static void nodeGetCell(
107832   Rtree *pRtree, 
107833   RtreeNode *pNode, 
107834   int iCell,
107835   RtreeCell *pCell
107836 ){
107837   int ii;
107838   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
107839   for(ii=0; ii<pRtree->nDim*2; ii++){
107840     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
107841   }
107842 }
107843
107844
107845 /* Forward declaration for the function that does the work of
107846 ** the virtual table module xCreate() and xConnect() methods.
107847 */
107848 static int rtreeInit(
107849   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
107850 );
107851
107852 /* 
107853 ** Rtree virtual table module xCreate method.
107854 */
107855 static int rtreeCreate(
107856   sqlite3 *db,
107857   void *pAux,
107858   int argc, const char *const*argv,
107859   sqlite3_vtab **ppVtab,
107860   char **pzErr
107861 ){
107862   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
107863 }
107864
107865 /* 
107866 ** Rtree virtual table module xConnect method.
107867 */
107868 static int rtreeConnect(
107869   sqlite3 *db,
107870   void *pAux,
107871   int argc, const char *const*argv,
107872   sqlite3_vtab **ppVtab,
107873   char **pzErr
107874 ){
107875   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
107876 }
107877
107878 /*
107879 ** Increment the r-tree reference count.
107880 */
107881 static void rtreeReference(Rtree *pRtree){
107882   pRtree->nBusy++;
107883 }
107884
107885 /*
107886 ** Decrement the r-tree reference count. When the reference count reaches
107887 ** zero the structure is deleted.
107888 */
107889 static void rtreeRelease(Rtree *pRtree){
107890   pRtree->nBusy--;
107891   if( pRtree->nBusy==0 ){
107892     sqlite3_finalize(pRtree->pReadNode);
107893     sqlite3_finalize(pRtree->pWriteNode);
107894     sqlite3_finalize(pRtree->pDeleteNode);
107895     sqlite3_finalize(pRtree->pReadRowid);
107896     sqlite3_finalize(pRtree->pWriteRowid);
107897     sqlite3_finalize(pRtree->pDeleteRowid);
107898     sqlite3_finalize(pRtree->pReadParent);
107899     sqlite3_finalize(pRtree->pWriteParent);
107900     sqlite3_finalize(pRtree->pDeleteParent);
107901     sqlite3_free(pRtree);
107902   }
107903 }
107904
107905 /* 
107906 ** Rtree virtual table module xDisconnect method.
107907 */
107908 static int rtreeDisconnect(sqlite3_vtab *pVtab){
107909   rtreeRelease((Rtree *)pVtab);
107910   return SQLITE_OK;
107911 }
107912
107913 /* 
107914 ** Rtree virtual table module xDestroy method.
107915 */
107916 static int rtreeDestroy(sqlite3_vtab *pVtab){
107917   Rtree *pRtree = (Rtree *)pVtab;
107918   int rc;
107919   char *zCreate = sqlite3_mprintf(
107920     "DROP TABLE '%q'.'%q_node';"
107921     "DROP TABLE '%q'.'%q_rowid';"
107922     "DROP TABLE '%q'.'%q_parent';",
107923     pRtree->zDb, pRtree->zName, 
107924     pRtree->zDb, pRtree->zName,
107925     pRtree->zDb, pRtree->zName
107926   );
107927   if( !zCreate ){
107928     rc = SQLITE_NOMEM;
107929   }else{
107930     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
107931     sqlite3_free(zCreate);
107932   }
107933   if( rc==SQLITE_OK ){
107934     rtreeRelease(pRtree);
107935   }
107936
107937   return rc;
107938 }
107939
107940 /* 
107941 ** Rtree virtual table module xOpen method.
107942 */
107943 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
107944   int rc = SQLITE_NOMEM;
107945   RtreeCursor *pCsr;
107946
107947   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
107948   if( pCsr ){
107949     memset(pCsr, 0, sizeof(RtreeCursor));
107950     pCsr->base.pVtab = pVTab;
107951     rc = SQLITE_OK;
107952   }
107953   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
107954
107955   return rc;
107956 }
107957
107958 /* 
107959 ** Rtree virtual table module xClose method.
107960 */
107961 static int rtreeClose(sqlite3_vtab_cursor *cur){
107962   Rtree *pRtree = (Rtree *)(cur->pVtab);
107963   int rc;
107964   RtreeCursor *pCsr = (RtreeCursor *)cur;
107965   sqlite3_free(pCsr->aConstraint);
107966   rc = nodeRelease(pRtree, pCsr->pNode);
107967   sqlite3_free(pCsr);
107968   return rc;
107969 }
107970
107971 /*
107972 ** Rtree virtual table module xEof method.
107973 **
107974 ** Return non-zero if the cursor does not currently point to a valid 
107975 ** record (i.e if the scan has finished), or zero otherwise.
107976 */
107977 static int rtreeEof(sqlite3_vtab_cursor *cur){
107978   RtreeCursor *pCsr = (RtreeCursor *)cur;
107979   return (pCsr->pNode==0);
107980 }
107981
107982 /* 
107983 ** Cursor pCursor currently points to a cell in a non-leaf page.
107984 ** Return true if the sub-tree headed by the cell is filtered
107985 ** (excluded) by the constraints in the pCursor->aConstraint[] 
107986 ** array, or false otherwise.
107987 */
107988 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
107989   RtreeCell cell;
107990   int ii;
107991   int bRes = 0;
107992
107993   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
107994   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
107995     RtreeConstraint *p = &pCursor->aConstraint[ii];
107996     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
107997     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
107998
107999     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
108000         || p->op==RTREE_GT || p->op==RTREE_EQ
108001     );
108002
108003     switch( p->op ){
108004       case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
108005       case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
108006       case RTREE_EQ: 
108007         bRes = (p->rValue>cell_max || p->rValue<cell_min);
108008         break;
108009     }
108010   }
108011
108012   return bRes;
108013 }
108014
108015 /* 
108016 ** Return true if the cell that cursor pCursor currently points to
108017 ** would be filtered (excluded) by the constraints in the 
108018 ** pCursor->aConstraint[] array, or false otherwise.
108019 **
108020 ** This function assumes that the cell is part of a leaf node.
108021 */
108022 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
108023   RtreeCell cell;
108024   int ii;
108025
108026   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
108027   for(ii=0; ii<pCursor->nConstraint; ii++){
108028     RtreeConstraint *p = &pCursor->aConstraint[ii];
108029     double coord = DCOORD(cell.aCoord[p->iCoord]);
108030     int res;
108031     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
108032         || p->op==RTREE_GT || p->op==RTREE_EQ
108033     );
108034     switch( p->op ){
108035       case RTREE_LE: res = (coord<=p->rValue); break;
108036       case RTREE_LT: res = (coord<p->rValue);  break;
108037       case RTREE_GE: res = (coord>=p->rValue); break;
108038       case RTREE_GT: res = (coord>p->rValue);  break;
108039       case RTREE_EQ: res = (coord==p->rValue); break;
108040     }
108041
108042     if( !res ) return 1;
108043   }
108044
108045   return 0;
108046 }
108047
108048 /*
108049 ** Cursor pCursor currently points at a node that heads a sub-tree of
108050 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
108051 ** to point to the left-most cell of the sub-tree that matches the 
108052 ** configured constraints.
108053 */
108054 static int descendToCell(
108055   Rtree *pRtree, 
108056   RtreeCursor *pCursor, 
108057   int iHeight,
108058   int *pEof                 /* OUT: Set to true if cannot descend */
108059 ){
108060   int isEof;
108061   int rc;
108062   int ii;
108063   RtreeNode *pChild;
108064   sqlite3_int64 iRowid;
108065
108066   RtreeNode *pSavedNode = pCursor->pNode;
108067   int iSavedCell = pCursor->iCell;
108068
108069   assert( iHeight>=0 );
108070
108071   if( iHeight==0 ){
108072     isEof = testRtreeEntry(pRtree, pCursor);
108073   }else{
108074     isEof = testRtreeCell(pRtree, pCursor);
108075   }
108076   if( isEof || iHeight==0 ){
108077     *pEof = isEof;
108078     return SQLITE_OK;
108079   }
108080
108081   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
108082   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
108083   if( rc!=SQLITE_OK ){
108084     return rc;
108085   }
108086
108087   nodeRelease(pRtree, pCursor->pNode);
108088   pCursor->pNode = pChild;
108089   isEof = 1;
108090   for(ii=0; isEof && ii<NCELL(pChild); ii++){
108091     pCursor->iCell = ii;
108092     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
108093     if( rc!=SQLITE_OK ){
108094       return rc;
108095     }
108096   }
108097
108098   if( isEof ){
108099     assert( pCursor->pNode==pChild );
108100     nodeReference(pSavedNode);
108101     nodeRelease(pRtree, pChild);
108102     pCursor->pNode = pSavedNode;
108103     pCursor->iCell = iSavedCell;
108104   }
108105
108106   *pEof = isEof;
108107   return SQLITE_OK;
108108 }
108109
108110 /*
108111 ** One of the cells in node pNode is guaranteed to have a 64-bit 
108112 ** integer value equal to iRowid. Return the index of this cell.
108113 */
108114 static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
108115   int ii;
108116   for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
108117     assert( ii<(NCELL(pNode)-1) );
108118   }
108119   return ii;
108120 }
108121
108122 /*
108123 ** Return the index of the cell containing a pointer to node pNode
108124 ** in its parent. If pNode is the root node, return -1.
108125 */
108126 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
108127   RtreeNode *pParent = pNode->pParent;
108128   if( pParent ){
108129     return nodeRowidIndex(pRtree, pParent, pNode->iNode);
108130   }
108131   return -1;
108132 }
108133
108134 /* 
108135 ** Rtree virtual table module xNext method.
108136 */
108137 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
108138   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
108139   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
108140   int rc = SQLITE_OK;
108141
108142   if( pCsr->iStrategy==1 ){
108143     /* This "scan" is a direct lookup by rowid. There is no next entry. */
108144     nodeRelease(pRtree, pCsr->pNode);
108145     pCsr->pNode = 0;
108146   }
108147
108148   else if( pCsr->pNode ){
108149     /* Move to the next entry that matches the configured constraints. */
108150     int iHeight = 0;
108151     while( pCsr->pNode ){
108152       RtreeNode *pNode = pCsr->pNode;
108153       int nCell = NCELL(pNode);
108154       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
108155         int isEof;
108156         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
108157         if( rc!=SQLITE_OK || !isEof ){
108158           return rc;
108159         }
108160       }
108161       pCsr->pNode = pNode->pParent;
108162       pCsr->iCell = nodeParentIndex(pRtree, pNode);
108163       nodeReference(pCsr->pNode);
108164       nodeRelease(pRtree, pNode);
108165       iHeight++;
108166     }
108167   }
108168
108169   return rc;
108170 }
108171
108172 /* 
108173 ** Rtree virtual table module xRowid method.
108174 */
108175 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
108176   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
108177   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
108178
108179   assert(pCsr->pNode);
108180   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
108181
108182   return SQLITE_OK;
108183 }
108184
108185 /* 
108186 ** Rtree virtual table module xColumn method.
108187 */
108188 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
108189   Rtree *pRtree = (Rtree *)cur->pVtab;
108190   RtreeCursor *pCsr = (RtreeCursor *)cur;
108191
108192   if( i==0 ){
108193     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
108194     sqlite3_result_int64(ctx, iRowid);
108195   }else{
108196     RtreeCoord c;
108197     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
108198     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
108199       sqlite3_result_double(ctx, c.f);
108200     }else{
108201       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
108202       sqlite3_result_int(ctx, c.i);
108203     }
108204   }
108205
108206   return SQLITE_OK;
108207 }
108208
108209 /* 
108210 ** Use nodeAcquire() to obtain the leaf node containing the record with 
108211 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
108212 ** return SQLITE_OK. If there is no such record in the table, set
108213 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
108214 ** to zero and return an SQLite error code.
108215 */
108216 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
108217   int rc;
108218   *ppLeaf = 0;
108219   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
108220   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
108221     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
108222     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
108223     sqlite3_reset(pRtree->pReadRowid);
108224   }else{
108225     rc = sqlite3_reset(pRtree->pReadRowid);
108226   }
108227   return rc;
108228 }
108229
108230
108231 /* 
108232 ** Rtree virtual table module xFilter method.
108233 */
108234 static int rtreeFilter(
108235   sqlite3_vtab_cursor *pVtabCursor, 
108236   int idxNum, const char *idxStr,
108237   int argc, sqlite3_value **argv
108238 ){
108239   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
108240   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
108241
108242   RtreeNode *pRoot = 0;
108243   int ii;
108244   int rc = SQLITE_OK;
108245
108246   rtreeReference(pRtree);
108247
108248   sqlite3_free(pCsr->aConstraint);
108249   pCsr->aConstraint = 0;
108250   pCsr->iStrategy = idxNum;
108251
108252   if( idxNum==1 ){
108253     /* Special case - lookup by rowid. */
108254     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
108255     i64 iRowid = sqlite3_value_int64(argv[0]);
108256     rc = findLeafNode(pRtree, iRowid, &pLeaf);
108257     pCsr->pNode = pLeaf; 
108258     if( pLeaf && rc==SQLITE_OK ){
108259       pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
108260     }
108261   }else{
108262     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
108263     ** with the configured constraints. 
108264     */
108265     if( argc>0 ){
108266       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
108267       pCsr->nConstraint = argc;
108268       if( !pCsr->aConstraint ){
108269         rc = SQLITE_NOMEM;
108270       }else{
108271         assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
108272         for(ii=0; ii<argc; ii++){
108273           RtreeConstraint *p = &pCsr->aConstraint[ii];
108274           p->op = idxStr[ii*2];
108275           p->iCoord = idxStr[ii*2+1]-'a';
108276           p->rValue = sqlite3_value_double(argv[ii]);
108277         }
108278       }
108279     }
108280   
108281     if( rc==SQLITE_OK ){
108282       pCsr->pNode = 0;
108283       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
108284     }
108285     if( rc==SQLITE_OK ){
108286       int isEof = 1;
108287       int nCell = NCELL(pRoot);
108288       pCsr->pNode = pRoot;
108289       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
108290         assert( pCsr->pNode==pRoot );
108291         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
108292         if( !isEof ){
108293           break;
108294         }
108295       }
108296       if( rc==SQLITE_OK && isEof ){
108297         assert( pCsr->pNode==pRoot );
108298         nodeRelease(pRtree, pRoot);
108299         pCsr->pNode = 0;
108300       }
108301       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
108302     }
108303   }
108304
108305   rtreeRelease(pRtree);
108306   return rc;
108307 }
108308
108309 /*
108310 ** Rtree virtual table module xBestIndex method. There are three
108311 ** table scan strategies to choose from (in order from most to 
108312 ** least desirable):
108313 **
108314 **   idxNum     idxStr        Strategy
108315 **   ------------------------------------------------
108316 **     1        Unused        Direct lookup by rowid.
108317 **     2        See below     R-tree query.
108318 **     3        Unused        Full table scan.
108319 **   ------------------------------------------------
108320 **
108321 ** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
108322 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
108323 ** constraint used. The first two bytes of idxStr correspond to 
108324 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
108325 ** (argvIndex==1) etc.
108326 **
108327 ** The first of each pair of bytes in idxStr identifies the constraint
108328 ** operator as follows:
108329 **
108330 **   Operator    Byte Value
108331 **   ----------------------
108332 **      =        0x41 ('A')
108333 **     <=        0x42 ('B')
108334 **      <        0x43 ('C')
108335 **     >=        0x44 ('D')
108336 **      >        0x45 ('E')
108337 **   ----------------------
108338 **
108339 ** The second of each pair of bytes identifies the coordinate column
108340 ** to which the constraint applies. The leftmost coordinate column
108341 ** is 'a', the second from the left 'b' etc.
108342 */
108343 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
108344   int rc = SQLITE_OK;
108345   int ii, cCol;
108346
108347   int iIdx = 0;
108348   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
108349   memset(zIdxStr, 0, sizeof(zIdxStr));
108350
108351   assert( pIdxInfo->idxStr==0 );
108352   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
108353     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
108354
108355     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
108356       /* We have an equality constraint on the rowid. Use strategy 1. */
108357       int jj;
108358       for(jj=0; jj<ii; jj++){
108359         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
108360         pIdxInfo->aConstraintUsage[jj].omit = 0;
108361       }
108362       pIdxInfo->idxNum = 1;
108363       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
108364       pIdxInfo->aConstraintUsage[jj].omit = 1;
108365
108366       /* This strategy involves a two rowid lookups on an B-Tree structures
108367       ** and then a linear search of an R-Tree node. This should be 
108368       ** considered almost as quick as a direct rowid lookup (for which 
108369       ** sqlite uses an internal cost of 0.0).
108370       */ 
108371       pIdxInfo->estimatedCost = 10.0;
108372       return SQLITE_OK;
108373     }
108374
108375     if( p->usable && p->iColumn>0 ){
108376       u8 op = 0;
108377       switch( p->op ){
108378         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
108379         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
108380         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
108381         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
108382         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
108383       }
108384       if( op ){
108385         /* Make sure this particular constraint has not been used before.
108386         ** If it has been used before, ignore it.
108387         **
108388         ** A <= or < can be used if there is a prior >= or >.
108389         ** A >= or > can be used if there is a prior < or <=.
108390         ** A <= or < is disqualified if there is a prior <=, <, or ==.
108391         ** A >= or > is disqualified if there is a prior >=, >, or ==.
108392         ** A == is disqualifed if there is any prior constraint.
108393         */
108394         int j, opmsk;
108395         static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
108396         assert( compatible[RTREE_EQ & 7]==0 );
108397         assert( compatible[RTREE_LT & 7]==1 );
108398         assert( compatible[RTREE_LE & 7]==1 );
108399         assert( compatible[RTREE_GT & 7]==2 );
108400         assert( compatible[RTREE_GE & 7]==2 );
108401         cCol = p->iColumn - 1 + 'a';
108402         opmsk = compatible[op & 7];
108403         for(j=0; j<iIdx; j+=2){
108404           if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
108405             op = 0;
108406             break;
108407           }
108408         }
108409       }
108410       if( op ){
108411         assert( iIdx<sizeof(zIdxStr)-1 );
108412         zIdxStr[iIdx++] = op;
108413         zIdxStr[iIdx++] = cCol;
108414         pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
108415         pIdxInfo->aConstraintUsage[ii].omit = 1;
108416       }
108417     }
108418   }
108419
108420   pIdxInfo->idxNum = 2;
108421   pIdxInfo->needToFreeIdxStr = 1;
108422   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
108423     return SQLITE_NOMEM;
108424   }
108425   assert( iIdx>=0 );
108426   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
108427   return rc;
108428 }
108429
108430 /*
108431 ** Return the N-dimensional volumn of the cell stored in *p.
108432 */
108433 static float cellArea(Rtree *pRtree, RtreeCell *p){
108434   float area = 1.0;
108435   int ii;
108436   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108437     area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
108438   }
108439   return area;
108440 }
108441
108442 /*
108443 ** Return the margin length of cell p. The margin length is the sum
108444 ** of the objects size in each dimension.
108445 */
108446 static float cellMargin(Rtree *pRtree, RtreeCell *p){
108447   float margin = 0.0;
108448   int ii;
108449   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108450     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
108451   }
108452   return margin;
108453 }
108454
108455 /*
108456 ** Store the union of cells p1 and p2 in p1.
108457 */
108458 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
108459   int ii;
108460   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
108461     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108462       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
108463       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
108464     }
108465   }else{
108466     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108467       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
108468       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
108469     }
108470   }
108471 }
108472
108473 /*
108474 ** Return true if the area covered by p2 is a subset of the area covered
108475 ** by p1. False otherwise.
108476 */
108477 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
108478   int ii;
108479   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
108480   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108481     RtreeCoord *a1 = &p1->aCoord[ii];
108482     RtreeCoord *a2 = &p2->aCoord[ii];
108483     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
108484      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
108485     ){
108486       return 0;
108487     }
108488   }
108489   return 1;
108490 }
108491
108492 /*
108493 ** Return the amount cell p would grow by if it were unioned with pCell.
108494 */
108495 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
108496   float area;
108497   RtreeCell cell;
108498   memcpy(&cell, p, sizeof(RtreeCell));
108499   area = cellArea(pRtree, &cell);
108500   cellUnion(pRtree, &cell, pCell);
108501   return (cellArea(pRtree, &cell)-area);
108502 }
108503
108504 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
108505 static float cellOverlap(
108506   Rtree *pRtree, 
108507   RtreeCell *p, 
108508   RtreeCell *aCell, 
108509   int nCell, 
108510   int iExclude
108511 ){
108512   int ii;
108513   float overlap = 0.0;
108514   for(ii=0; ii<nCell; ii++){
108515     if( ii!=iExclude ){
108516       int jj;
108517       float o = 1.0;
108518       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
108519         double x1;
108520         double x2;
108521
108522         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
108523         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
108524
108525         if( x2<x1 ){
108526           o = 0.0;
108527           break;
108528         }else{
108529           o = o * (x2-x1);
108530         }
108531       }
108532       overlap += o;
108533     }
108534   }
108535   return overlap;
108536 }
108537 #endif
108538
108539 #if VARIANT_RSTARTREE_CHOOSESUBTREE
108540 static float cellOverlapEnlargement(
108541   Rtree *pRtree, 
108542   RtreeCell *p, 
108543   RtreeCell *pInsert, 
108544   RtreeCell *aCell, 
108545   int nCell, 
108546   int iExclude
108547 ){
108548   float before;
108549   float after;
108550   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
108551   cellUnion(pRtree, p, pInsert);
108552   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
108553   return after-before;
108554 }
108555 #endif
108556
108557
108558 /*
108559 ** This function implements the ChooseLeaf algorithm from Gutman[84].
108560 ** ChooseSubTree in r*tree terminology.
108561 */
108562 static int ChooseLeaf(
108563   Rtree *pRtree,               /* Rtree table */
108564   RtreeCell *pCell,            /* Cell to insert into rtree */
108565   int iHeight,                 /* Height of sub-tree rooted at pCell */
108566   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
108567 ){
108568   int rc;
108569   int ii;
108570   RtreeNode *pNode;
108571   rc = nodeAcquire(pRtree, 1, 0, &pNode);
108572
108573   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
108574     int iCell;
108575     sqlite3_int64 iBest;
108576
108577     float fMinGrowth;
108578     float fMinArea;
108579     float fMinOverlap;
108580
108581     int nCell = NCELL(pNode);
108582     RtreeCell cell;
108583     RtreeNode *pChild;
108584
108585     RtreeCell *aCell = 0;
108586
108587 #if VARIANT_RSTARTREE_CHOOSESUBTREE
108588     if( ii==(pRtree->iDepth-1) ){
108589       int jj;
108590       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
108591       if( !aCell ){
108592         rc = SQLITE_NOMEM;
108593         nodeRelease(pRtree, pNode);
108594         pNode = 0;
108595         continue;
108596       }
108597       for(jj=0; jj<nCell; jj++){
108598         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
108599       }
108600     }
108601 #endif
108602
108603     /* Select the child node which will be enlarged the least if pCell
108604     ** is inserted into it. Resolve ties by choosing the entry with
108605     ** the smallest area.
108606     */
108607     for(iCell=0; iCell<nCell; iCell++){
108608       float growth;
108609       float area;
108610       float overlap = 0.0;
108611       nodeGetCell(pRtree, pNode, iCell, &cell);
108612       growth = cellGrowth(pRtree, &cell, pCell);
108613       area = cellArea(pRtree, &cell);
108614 #if VARIANT_RSTARTREE_CHOOSESUBTREE
108615       if( ii==(pRtree->iDepth-1) ){
108616         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
108617       }
108618 #endif
108619       if( (iCell==0) 
108620        || (overlap<fMinOverlap) 
108621        || (overlap==fMinOverlap && growth<fMinGrowth)
108622        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
108623       ){
108624         fMinOverlap = overlap;
108625         fMinGrowth = growth;
108626         fMinArea = area;
108627         iBest = cell.iRowid;
108628       }
108629     }
108630
108631     sqlite3_free(aCell);
108632     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
108633     nodeRelease(pRtree, pNode);
108634     pNode = pChild;
108635   }
108636
108637   *ppLeaf = pNode;
108638   return rc;
108639 }
108640
108641 /*
108642 ** A cell with the same content as pCell has just been inserted into
108643 ** the node pNode. This function updates the bounding box cells in
108644 ** all ancestor elements.
108645 */
108646 static void AdjustTree(
108647   Rtree *pRtree,                    /* Rtree table */
108648   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
108649   RtreeCell *pCell                  /* This cell was just inserted */
108650 ){
108651   RtreeNode *p = pNode;
108652   while( p->pParent ){
108653     RtreeCell cell;
108654     RtreeNode *pParent = p->pParent;
108655     int iCell = nodeParentIndex(pRtree, p);
108656
108657     nodeGetCell(pRtree, pParent, iCell, &cell);
108658     if( !cellContains(pRtree, &cell, pCell) ){
108659       cellUnion(pRtree, &cell, pCell);
108660       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
108661     }
108662  
108663     p = pParent;
108664   }
108665 }
108666
108667 /*
108668 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
108669 */
108670 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
108671   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
108672   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
108673   sqlite3_step(pRtree->pWriteRowid);
108674   return sqlite3_reset(pRtree->pWriteRowid);
108675 }
108676
108677 /*
108678 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
108679 */
108680 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
108681   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
108682   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
108683   sqlite3_step(pRtree->pWriteParent);
108684   return sqlite3_reset(pRtree->pWriteParent);
108685 }
108686
108687 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
108688
108689 #if VARIANT_GUTTMAN_LINEAR_SPLIT
108690 /*
108691 ** Implementation of the linear variant of the PickNext() function from
108692 ** Guttman[84].
108693 */
108694 static RtreeCell *LinearPickNext(
108695   Rtree *pRtree,
108696   RtreeCell *aCell, 
108697   int nCell, 
108698   RtreeCell *pLeftBox, 
108699   RtreeCell *pRightBox,
108700   int *aiUsed
108701 ){
108702   int ii;
108703   for(ii=0; aiUsed[ii]; ii++);
108704   aiUsed[ii] = 1;
108705   return &aCell[ii];
108706 }
108707
108708 /*
108709 ** Implementation of the linear variant of the PickSeeds() function from
108710 ** Guttman[84].
108711 */
108712 static void LinearPickSeeds(
108713   Rtree *pRtree,
108714   RtreeCell *aCell, 
108715   int nCell, 
108716   int *piLeftSeed, 
108717   int *piRightSeed
108718 ){
108719   int i;
108720   int iLeftSeed = 0;
108721   int iRightSeed = 1;
108722   float maxNormalInnerWidth = 0.0;
108723
108724   /* Pick two "seed" cells from the array of cells. The algorithm used
108725   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
108726   ** indices of the two seed cells in the array are stored in local
108727   ** variables iLeftSeek and iRightSeed.
108728   */
108729   for(i=0; i<pRtree->nDim; i++){
108730     float x1 = DCOORD(aCell[0].aCoord[i*2]);
108731     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
108732     float x3 = x1;
108733     float x4 = x2;
108734     int jj;
108735
108736     int iCellLeft = 0;
108737     int iCellRight = 0;
108738
108739     for(jj=1; jj<nCell; jj++){
108740       float left = DCOORD(aCell[jj].aCoord[i*2]);
108741       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
108742
108743       if( left<x1 ) x1 = left;
108744       if( right>x4 ) x4 = right;
108745       if( left>x3 ){
108746         x3 = left;
108747         iCellRight = jj;
108748       }
108749       if( right<x2 ){
108750         x2 = right;
108751         iCellLeft = jj;
108752       }
108753     }
108754
108755     if( x4!=x1 ){
108756       float normalwidth = (x3 - x2) / (x4 - x1);
108757       if( normalwidth>maxNormalInnerWidth ){
108758         iLeftSeed = iCellLeft;
108759         iRightSeed = iCellRight;
108760       }
108761     }
108762   }
108763
108764   *piLeftSeed = iLeftSeed;
108765   *piRightSeed = iRightSeed;
108766 }
108767 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
108768
108769 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
108770 /*
108771 ** Implementation of the quadratic variant of the PickNext() function from
108772 ** Guttman[84].
108773 */
108774 static RtreeCell *QuadraticPickNext(
108775   Rtree *pRtree,
108776   RtreeCell *aCell, 
108777   int nCell, 
108778   RtreeCell *pLeftBox, 
108779   RtreeCell *pRightBox,
108780   int *aiUsed
108781 ){
108782   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
108783
108784   int iSelect = -1;
108785   float fDiff;
108786   int ii;
108787   for(ii=0; ii<nCell; ii++){
108788     if( aiUsed[ii]==0 ){
108789       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
108790       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
108791       float diff = FABS(right-left);
108792       if( iSelect<0 || diff>fDiff ){
108793         fDiff = diff;
108794         iSelect = ii;
108795       }
108796     }
108797   }
108798   aiUsed[iSelect] = 1;
108799   return &aCell[iSelect];
108800 }
108801
108802 /*
108803 ** Implementation of the quadratic variant of the PickSeeds() function from
108804 ** Guttman[84].
108805 */
108806 static void QuadraticPickSeeds(
108807   Rtree *pRtree,
108808   RtreeCell *aCell, 
108809   int nCell, 
108810   int *piLeftSeed, 
108811   int *piRightSeed
108812 ){
108813   int ii;
108814   int jj;
108815
108816   int iLeftSeed = 0;
108817   int iRightSeed = 1;
108818   float fWaste = 0.0;
108819
108820   for(ii=0; ii<nCell; ii++){
108821     for(jj=ii+1; jj<nCell; jj++){
108822       float right = cellArea(pRtree, &aCell[jj]);
108823       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
108824       float waste = growth - right;
108825
108826       if( waste>fWaste ){
108827         iLeftSeed = ii;
108828         iRightSeed = jj;
108829         fWaste = waste;
108830       }
108831     }
108832   }
108833
108834   *piLeftSeed = iLeftSeed;
108835   *piRightSeed = iRightSeed;
108836 }
108837 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
108838
108839 /*
108840 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
108841 ** nIdx. The aIdx array contains the set of integers from 0 to 
108842 ** (nIdx-1) in no particular order. This function sorts the values
108843 ** in aIdx according to the indexed values in aDistance. For
108844 ** example, assuming the inputs:
108845 **
108846 **   aIdx      = { 0,   1,   2,   3 }
108847 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
108848 **
108849 ** this function sets the aIdx array to contain:
108850 **
108851 **   aIdx      = { 0,   1,   2,   3 }
108852 **
108853 ** The aSpare array is used as temporary working space by the
108854 ** sorting algorithm.
108855 */
108856 static void SortByDistance(
108857   int *aIdx, 
108858   int nIdx, 
108859   float *aDistance, 
108860   int *aSpare
108861 ){
108862   if( nIdx>1 ){
108863     int iLeft = 0;
108864     int iRight = 0;
108865
108866     int nLeft = nIdx/2;
108867     int nRight = nIdx-nLeft;
108868     int *aLeft = aIdx;
108869     int *aRight = &aIdx[nLeft];
108870
108871     SortByDistance(aLeft, nLeft, aDistance, aSpare);
108872     SortByDistance(aRight, nRight, aDistance, aSpare);
108873
108874     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
108875     aLeft = aSpare;
108876
108877     while( iLeft<nLeft || iRight<nRight ){
108878       if( iLeft==nLeft ){
108879         aIdx[iLeft+iRight] = aRight[iRight];
108880         iRight++;
108881       }else if( iRight==nRight ){
108882         aIdx[iLeft+iRight] = aLeft[iLeft];
108883         iLeft++;
108884       }else{
108885         float fLeft = aDistance[aLeft[iLeft]];
108886         float fRight = aDistance[aRight[iRight]];
108887         if( fLeft<fRight ){
108888           aIdx[iLeft+iRight] = aLeft[iLeft];
108889           iLeft++;
108890         }else{
108891           aIdx[iLeft+iRight] = aRight[iRight];
108892           iRight++;
108893         }
108894       }
108895     }
108896
108897 #if 0
108898     /* Check that the sort worked */
108899     {
108900       int jj;
108901       for(jj=1; jj<nIdx; jj++){
108902         float left = aDistance[aIdx[jj-1]];
108903         float right = aDistance[aIdx[jj]];
108904         assert( left<=right );
108905       }
108906     }
108907 #endif
108908   }
108909 }
108910
108911 /*
108912 ** Arguments aIdx, aCell and aSpare all point to arrays of size
108913 ** nIdx. The aIdx array contains the set of integers from 0 to 
108914 ** (nIdx-1) in no particular order. This function sorts the values
108915 ** in aIdx according to dimension iDim of the cells in aCell. The
108916 ** minimum value of dimension iDim is considered first, the
108917 ** maximum used to break ties.
108918 **
108919 ** The aSpare array is used as temporary working space by the
108920 ** sorting algorithm.
108921 */
108922 static void SortByDimension(
108923   Rtree *pRtree,
108924   int *aIdx, 
108925   int nIdx, 
108926   int iDim, 
108927   RtreeCell *aCell, 
108928   int *aSpare
108929 ){
108930   if( nIdx>1 ){
108931
108932     int iLeft = 0;
108933     int iRight = 0;
108934
108935     int nLeft = nIdx/2;
108936     int nRight = nIdx-nLeft;
108937     int *aLeft = aIdx;
108938     int *aRight = &aIdx[nLeft];
108939
108940     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
108941     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
108942
108943     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
108944     aLeft = aSpare;
108945     while( iLeft<nLeft || iRight<nRight ){
108946       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
108947       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
108948       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
108949       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
108950       if( (iLeft!=nLeft) && ((iRight==nRight)
108951        || (xleft1<xright1)
108952        || (xleft1==xright1 && xleft2<xright2)
108953       )){
108954         aIdx[iLeft+iRight] = aLeft[iLeft];
108955         iLeft++;
108956       }else{
108957         aIdx[iLeft+iRight] = aRight[iRight];
108958         iRight++;
108959       }
108960     }
108961
108962 #if 0
108963     /* Check that the sort worked */
108964     {
108965       int jj;
108966       for(jj=1; jj<nIdx; jj++){
108967         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
108968         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
108969         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
108970         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
108971         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
108972       }
108973     }
108974 #endif
108975   }
108976 }
108977
108978 #if VARIANT_RSTARTREE_SPLIT
108979 /*
108980 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
108981 */
108982 static int splitNodeStartree(
108983   Rtree *pRtree,
108984   RtreeCell *aCell,
108985   int nCell,
108986   RtreeNode *pLeft,
108987   RtreeNode *pRight,
108988   RtreeCell *pBboxLeft,
108989   RtreeCell *pBboxRight
108990 ){
108991   int **aaSorted;
108992   int *aSpare;
108993   int ii;
108994
108995   int iBestDim;
108996   int iBestSplit;
108997   float fBestMargin;
108998
108999   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
109000
109001   aaSorted = (int **)sqlite3_malloc(nByte);
109002   if( !aaSorted ){
109003     return SQLITE_NOMEM;
109004   }
109005
109006   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
109007   memset(aaSorted, 0, nByte);
109008   for(ii=0; ii<pRtree->nDim; ii++){
109009     int jj;
109010     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
109011     for(jj=0; jj<nCell; jj++){
109012       aaSorted[ii][jj] = jj;
109013     }
109014     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
109015   }
109016
109017   for(ii=0; ii<pRtree->nDim; ii++){
109018     float margin = 0.0;
109019     float fBestOverlap;
109020     float fBestArea;
109021     int iBestLeft;
109022     int nLeft;
109023
109024     for(
109025       nLeft=RTREE_MINCELLS(pRtree); 
109026       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
109027       nLeft++
109028     ){
109029       RtreeCell left;
109030       RtreeCell right;
109031       int kk;
109032       float overlap;
109033       float area;
109034
109035       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
109036       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
109037       for(kk=1; kk<(nCell-1); kk++){
109038         if( kk<nLeft ){
109039           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
109040         }else{
109041           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
109042         }
109043       }
109044       margin += cellMargin(pRtree, &left);
109045       margin += cellMargin(pRtree, &right);
109046       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
109047       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
109048       if( (nLeft==RTREE_MINCELLS(pRtree))
109049        || (overlap<fBestOverlap)
109050        || (overlap==fBestOverlap && area<fBestArea)
109051       ){
109052         iBestLeft = nLeft;
109053         fBestOverlap = overlap;
109054         fBestArea = area;
109055       }
109056     }
109057
109058     if( ii==0 || margin<fBestMargin ){
109059       iBestDim = ii;
109060       fBestMargin = margin;
109061       iBestSplit = iBestLeft;
109062     }
109063   }
109064
109065   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
109066   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
109067   for(ii=0; ii<nCell; ii++){
109068     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
109069     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
109070     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
109071     nodeInsertCell(pRtree, pTarget, pCell);
109072     cellUnion(pRtree, pBbox, pCell);
109073   }
109074
109075   sqlite3_free(aaSorted);
109076   return SQLITE_OK;
109077 }
109078 #endif
109079
109080 #if VARIANT_GUTTMAN_SPLIT
109081 /*
109082 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
109083 */
109084 static int splitNodeGuttman(
109085   Rtree *pRtree,
109086   RtreeCell *aCell,
109087   int nCell,
109088   RtreeNode *pLeft,
109089   RtreeNode *pRight,
109090   RtreeCell *pBboxLeft,
109091   RtreeCell *pBboxRight
109092 ){
109093   int iLeftSeed = 0;
109094   int iRightSeed = 1;
109095   int *aiUsed;
109096   int i;
109097
109098   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
109099   if( !aiUsed ){
109100     return SQLITE_NOMEM;
109101   }
109102   memset(aiUsed, 0, sizeof(int)*nCell);
109103
109104   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
109105
109106   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
109107   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
109108   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
109109   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
109110   aiUsed[iLeftSeed] = 1;
109111   aiUsed[iRightSeed] = 1;
109112
109113   for(i=nCell-2; i>0; i--){
109114     RtreeCell *pNext;
109115     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
109116     float diff =  
109117       cellGrowth(pRtree, pBboxLeft, pNext) - 
109118       cellGrowth(pRtree, pBboxRight, pNext)
109119     ;
109120     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
109121      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
109122     ){
109123       nodeInsertCell(pRtree, pRight, pNext);
109124       cellUnion(pRtree, pBboxRight, pNext);
109125     }else{
109126       nodeInsertCell(pRtree, pLeft, pNext);
109127       cellUnion(pRtree, pBboxLeft, pNext);
109128     }
109129   }
109130
109131   sqlite3_free(aiUsed);
109132   return SQLITE_OK;
109133 }
109134 #endif
109135
109136 static int updateMapping(
109137   Rtree *pRtree, 
109138   i64 iRowid, 
109139   RtreeNode *pNode, 
109140   int iHeight
109141 ){
109142   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
109143   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
109144   if( iHeight>0 ){
109145     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
109146     if( pChild ){
109147       nodeRelease(pRtree, pChild->pParent);
109148       nodeReference(pNode);
109149       pChild->pParent = pNode;
109150     }
109151   }
109152   return xSetMapping(pRtree, iRowid, pNode->iNode);
109153 }
109154
109155 static int SplitNode(
109156   Rtree *pRtree,
109157   RtreeNode *pNode,
109158   RtreeCell *pCell,
109159   int iHeight
109160 ){
109161   int i;
109162   int newCellIsRight = 0;
109163
109164   int rc = SQLITE_OK;
109165   int nCell = NCELL(pNode);
109166   RtreeCell *aCell;
109167   int *aiUsed;
109168
109169   RtreeNode *pLeft = 0;
109170   RtreeNode *pRight = 0;
109171
109172   RtreeCell leftbbox;
109173   RtreeCell rightbbox;
109174
109175   /* Allocate an array and populate it with a copy of pCell and 
109176   ** all cells from node pLeft. Then zero the original node.
109177   */
109178   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
109179   if( !aCell ){
109180     rc = SQLITE_NOMEM;
109181     goto splitnode_out;
109182   }
109183   aiUsed = (int *)&aCell[nCell+1];
109184   memset(aiUsed, 0, sizeof(int)*(nCell+1));
109185   for(i=0; i<nCell; i++){
109186     nodeGetCell(pRtree, pNode, i, &aCell[i]);
109187   }
109188   nodeZero(pRtree, pNode);
109189   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
109190   nCell++;
109191
109192   if( pNode->iNode==1 ){
109193     pRight = nodeNew(pRtree, pNode, 1);
109194     pLeft = nodeNew(pRtree, pNode, 1);
109195     pRtree->iDepth++;
109196     pNode->isDirty = 1;
109197     writeInt16(pNode->zData, pRtree->iDepth);
109198   }else{
109199     pLeft = pNode;
109200     pRight = nodeNew(pRtree, pLeft->pParent, 1);
109201     nodeReference(pLeft);
109202   }
109203
109204   if( !pLeft || !pRight ){
109205     rc = SQLITE_NOMEM;
109206     goto splitnode_out;
109207   }
109208
109209   memset(pLeft->zData, 0, pRtree->iNodeSize);
109210   memset(pRight->zData, 0, pRtree->iNodeSize);
109211
109212   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
109213   if( rc!=SQLITE_OK ){
109214     goto splitnode_out;
109215   }
109216
109217   /* Ensure both child nodes have node numbers assigned to them. */
109218   if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
109219    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
109220   ){
109221     goto splitnode_out;
109222   }
109223
109224   rightbbox.iRowid = pRight->iNode;
109225   leftbbox.iRowid = pLeft->iNode;
109226
109227   if( pNode->iNode==1 ){
109228     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
109229     if( rc!=SQLITE_OK ){
109230       goto splitnode_out;
109231     }
109232   }else{
109233     RtreeNode *pParent = pLeft->pParent;
109234     int iCell = nodeParentIndex(pRtree, pLeft);
109235     nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
109236     AdjustTree(pRtree, pParent, &leftbbox);
109237   }
109238   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
109239     goto splitnode_out;
109240   }
109241
109242   for(i=0; i<NCELL(pRight); i++){
109243     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
109244     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
109245     if( iRowid==pCell->iRowid ){
109246       newCellIsRight = 1;
109247     }
109248     if( rc!=SQLITE_OK ){
109249       goto splitnode_out;
109250     }
109251   }
109252   if( pNode->iNode==1 ){
109253     for(i=0; i<NCELL(pLeft); i++){
109254       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
109255       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
109256       if( rc!=SQLITE_OK ){
109257         goto splitnode_out;
109258       }
109259     }
109260   }else if( newCellIsRight==0 ){
109261     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
109262   }
109263
109264   if( rc==SQLITE_OK ){
109265     rc = nodeRelease(pRtree, pRight);
109266     pRight = 0;
109267   }
109268   if( rc==SQLITE_OK ){
109269     rc = nodeRelease(pRtree, pLeft);
109270     pLeft = 0;
109271   }
109272
109273 splitnode_out:
109274   nodeRelease(pRtree, pRight);
109275   nodeRelease(pRtree, pLeft);
109276   sqlite3_free(aCell);
109277   return rc;
109278 }
109279
109280 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
109281   int rc = SQLITE_OK;
109282   if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
109283     sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
109284     if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
109285       i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
109286       rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
109287     }else{
109288       rc = SQLITE_ERROR;
109289     }
109290     sqlite3_reset(pRtree->pReadParent);
109291     if( rc==SQLITE_OK ){
109292       rc = fixLeafParent(pRtree, pLeaf->pParent);
109293     }
109294   }
109295   return rc;
109296 }
109297
109298 static int deleteCell(Rtree *, RtreeNode *, int, int);
109299
109300 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
109301   int rc;
109302   RtreeNode *pParent;
109303   int iCell;
109304
109305   assert( pNode->nRef==1 );
109306
109307   /* Remove the entry in the parent cell. */
109308   iCell = nodeParentIndex(pRtree, pNode);
109309   pParent = pNode->pParent;
109310   pNode->pParent = 0;
109311   if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1)) 
109312    || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
109313   ){
109314     return rc;
109315   }
109316
109317   /* Remove the xxx_node entry. */
109318   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
109319   sqlite3_step(pRtree->pDeleteNode);
109320   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
109321     return rc;
109322   }
109323
109324   /* Remove the xxx_parent entry. */
109325   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
109326   sqlite3_step(pRtree->pDeleteParent);
109327   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
109328     return rc;
109329   }
109330   
109331   /* Remove the node from the in-memory hash table and link it into
109332   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
109333   */
109334   nodeHashDelete(pRtree, pNode);
109335   pNode->iNode = iHeight;
109336   pNode->pNext = pRtree->pDeleted;
109337   pNode->nRef++;
109338   pRtree->pDeleted = pNode;
109339
109340   return SQLITE_OK;
109341 }
109342
109343 static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
109344   RtreeNode *pParent = pNode->pParent;
109345   if( pParent ){
109346     int ii; 
109347     int nCell = NCELL(pNode);
109348     RtreeCell box;                            /* Bounding box for pNode */
109349     nodeGetCell(pRtree, pNode, 0, &box);
109350     for(ii=1; ii<nCell; ii++){
109351       RtreeCell cell;
109352       nodeGetCell(pRtree, pNode, ii, &cell);
109353       cellUnion(pRtree, &box, &cell);
109354     }
109355     box.iRowid = pNode->iNode;
109356     ii = nodeParentIndex(pRtree, pNode);
109357     nodeOverwriteCell(pRtree, pParent, &box, ii);
109358     fixBoundingBox(pRtree, pParent);
109359   }
109360 }
109361
109362 /*
109363 ** Delete the cell at index iCell of node pNode. After removing the
109364 ** cell, adjust the r-tree data structure if required.
109365 */
109366 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
109367   int rc;
109368
109369   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
109370     return rc;
109371   }
109372
109373   /* Remove the cell from the node. This call just moves bytes around
109374   ** the in-memory node image, so it cannot fail.
109375   */
109376   nodeDeleteCell(pRtree, pNode, iCell);
109377
109378   /* If the node is not the tree root and now has less than the minimum
109379   ** number of cells, remove it from the tree. Otherwise, update the
109380   ** cell in the parent node so that it tightly contains the updated
109381   ** node.
109382   */
109383   if( pNode->iNode!=1 ){
109384     RtreeNode *pParent = pNode->pParent;
109385     if( (pParent->iNode!=1 || NCELL(pParent)!=1) 
109386      && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
109387     ){
109388       rc = removeNode(pRtree, pNode, iHeight);
109389     }else{
109390       fixBoundingBox(pRtree, pNode);
109391     }
109392   }
109393
109394   return rc;
109395 }
109396
109397 static int Reinsert(
109398   Rtree *pRtree, 
109399   RtreeNode *pNode, 
109400   RtreeCell *pCell, 
109401   int iHeight
109402 ){
109403   int *aOrder;
109404   int *aSpare;
109405   RtreeCell *aCell;
109406   float *aDistance;
109407   int nCell;
109408   float aCenterCoord[RTREE_MAX_DIMENSIONS];
109409   int iDim;
109410   int ii;
109411   int rc = SQLITE_OK;
109412
109413   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
109414
109415   nCell = NCELL(pNode)+1;
109416
109417   /* Allocate the buffers used by this operation. The allocation is
109418   ** relinquished before this function returns.
109419   */
109420   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
109421     sizeof(RtreeCell) +         /* aCell array */
109422     sizeof(int)       +         /* aOrder array */
109423     sizeof(int)       +         /* aSpare array */
109424     sizeof(float)               /* aDistance array */
109425   ));
109426   if( !aCell ){
109427     return SQLITE_NOMEM;
109428   }
109429   aOrder    = (int *)&aCell[nCell];
109430   aSpare    = (int *)&aOrder[nCell];
109431   aDistance = (float *)&aSpare[nCell];
109432
109433   for(ii=0; ii<nCell; ii++){
109434     if( ii==(nCell-1) ){
109435       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
109436     }else{
109437       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
109438     }
109439     aOrder[ii] = ii;
109440     for(iDim=0; iDim<pRtree->nDim; iDim++){
109441       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
109442       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
109443     }
109444   }
109445   for(iDim=0; iDim<pRtree->nDim; iDim++){
109446     aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
109447   }
109448
109449   for(ii=0; ii<nCell; ii++){
109450     aDistance[ii] = 0.0;
109451     for(iDim=0; iDim<pRtree->nDim; iDim++){
109452       float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
109453           DCOORD(aCell[ii].aCoord[iDim*2]);
109454       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
109455     }
109456   }
109457
109458   SortByDistance(aOrder, nCell, aDistance, aSpare);
109459   nodeZero(pRtree, pNode);
109460
109461   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
109462     RtreeCell *p = &aCell[aOrder[ii]];
109463     nodeInsertCell(pRtree, pNode, p);
109464     if( p->iRowid==pCell->iRowid ){
109465       if( iHeight==0 ){
109466         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
109467       }else{
109468         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
109469       }
109470     }
109471   }
109472   if( rc==SQLITE_OK ){
109473     fixBoundingBox(pRtree, pNode);
109474   }
109475   for(; rc==SQLITE_OK && ii<nCell; ii++){
109476     /* Find a node to store this cell in. pNode->iNode currently contains
109477     ** the height of the sub-tree headed by the cell.
109478     */
109479     RtreeNode *pInsert;
109480     RtreeCell *p = &aCell[aOrder[ii]];
109481     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
109482     if( rc==SQLITE_OK ){
109483       int rc2;
109484       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
109485       rc2 = nodeRelease(pRtree, pInsert);
109486       if( rc==SQLITE_OK ){
109487         rc = rc2;
109488       }
109489     }
109490   }
109491
109492   sqlite3_free(aCell);
109493   return rc;
109494 }
109495
109496 /*
109497 ** Insert cell pCell into node pNode. Node pNode is the head of a 
109498 ** subtree iHeight high (leaf nodes have iHeight==0).
109499 */
109500 static int rtreeInsertCell(
109501   Rtree *pRtree,
109502   RtreeNode *pNode,
109503   RtreeCell *pCell,
109504   int iHeight
109505 ){
109506   int rc = SQLITE_OK;
109507   if( iHeight>0 ){
109508     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
109509     if( pChild ){
109510       nodeRelease(pRtree, pChild->pParent);
109511       nodeReference(pNode);
109512       pChild->pParent = pNode;
109513     }
109514   }
109515   if( nodeInsertCell(pRtree, pNode, pCell) ){
109516 #if VARIANT_RSTARTREE_REINSERT
109517     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
109518       rc = SplitNode(pRtree, pNode, pCell, iHeight);
109519     }else{
109520       pRtree->iReinsertHeight = iHeight;
109521       rc = Reinsert(pRtree, pNode, pCell, iHeight);
109522     }
109523 #else
109524     rc = SplitNode(pRtree, pNode, pCell, iHeight);
109525 #endif
109526   }else{
109527     AdjustTree(pRtree, pNode, pCell);
109528     if( iHeight==0 ){
109529       rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
109530     }else{
109531       rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
109532     }
109533   }
109534   return rc;
109535 }
109536
109537 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
109538   int ii;
109539   int rc = SQLITE_OK;
109540   int nCell = NCELL(pNode);
109541
109542   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
109543     RtreeNode *pInsert;
109544     RtreeCell cell;
109545     nodeGetCell(pRtree, pNode, ii, &cell);
109546
109547     /* Find a node to store this cell in. pNode->iNode currently contains
109548     ** the height of the sub-tree headed by the cell.
109549     */
109550     rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
109551     if( rc==SQLITE_OK ){
109552       int rc2;
109553       rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
109554       rc2 = nodeRelease(pRtree, pInsert);
109555       if( rc==SQLITE_OK ){
109556         rc = rc2;
109557       }
109558     }
109559   }
109560   return rc;
109561 }
109562
109563 /*
109564 ** Select a currently unused rowid for a new r-tree record.
109565 */
109566 static int newRowid(Rtree *pRtree, i64 *piRowid){
109567   int rc;
109568   sqlite3_bind_null(pRtree->pWriteRowid, 1);
109569   sqlite3_bind_null(pRtree->pWriteRowid, 2);
109570   sqlite3_step(pRtree->pWriteRowid);
109571   rc = sqlite3_reset(pRtree->pWriteRowid);
109572   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
109573   return rc;
109574 }
109575
109576 #ifndef NDEBUG
109577 static int hashIsEmpty(Rtree *pRtree){
109578   int ii;
109579   for(ii=0; ii<HASHSIZE; ii++){
109580     assert( !pRtree->aHash[ii] );
109581   }
109582   return 1;
109583 }
109584 #endif
109585
109586 /*
109587 ** The xUpdate method for rtree module virtual tables.
109588 */
109589 static int rtreeUpdate(
109590   sqlite3_vtab *pVtab, 
109591   int nData, 
109592   sqlite3_value **azData, 
109593   sqlite_int64 *pRowid
109594 ){
109595   Rtree *pRtree = (Rtree *)pVtab;
109596   int rc = SQLITE_OK;
109597
109598   rtreeReference(pRtree);
109599
109600   assert(nData>=1);
109601   assert(hashIsEmpty(pRtree));
109602
109603   /* If azData[0] is not an SQL NULL value, it is the rowid of a
109604   ** record to delete from the r-tree table. The following block does
109605   ** just that.
109606   */
109607   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
109608     i64 iDelete;                /* The rowid to delete */
109609     RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
109610     int iCell;                  /* Index of iDelete cell in pLeaf */
109611     RtreeNode *pRoot;
109612
109613     /* Obtain a reference to the root node to initialise Rtree.iDepth */
109614     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
109615
109616     /* Obtain a reference to the leaf node that contains the entry 
109617     ** about to be deleted. 
109618     */
109619     if( rc==SQLITE_OK ){
109620       iDelete = sqlite3_value_int64(azData[0]);
109621       rc = findLeafNode(pRtree, iDelete, &pLeaf);
109622     }
109623
109624     /* Delete the cell in question from the leaf node. */
109625     if( rc==SQLITE_OK ){
109626       int rc2;
109627       iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
109628       rc = deleteCell(pRtree, pLeaf, iCell, 0);
109629       rc2 = nodeRelease(pRtree, pLeaf);
109630       if( rc==SQLITE_OK ){
109631         rc = rc2;
109632       }
109633     }
109634
109635     /* Delete the corresponding entry in the <rtree>_rowid table. */
109636     if( rc==SQLITE_OK ){
109637       sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
109638       sqlite3_step(pRtree->pDeleteRowid);
109639       rc = sqlite3_reset(pRtree->pDeleteRowid);
109640     }
109641
109642     /* Check if the root node now has exactly one child. If so, remove
109643     ** it, schedule the contents of the child for reinsertion and 
109644     ** reduce the tree height by one.
109645     **
109646     ** This is equivalent to copying the contents of the child into
109647     ** the root node (the operation that Gutman's paper says to perform 
109648     ** in this scenario).
109649     */
109650     if( rc==SQLITE_OK && pRtree->iDepth>0 ){
109651       if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
109652         RtreeNode *pChild;
109653         i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
109654         rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
109655         if( rc==SQLITE_OK ){
109656           rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
109657         }
109658         if( rc==SQLITE_OK ){
109659           pRtree->iDepth--;
109660           writeInt16(pRoot->zData, pRtree->iDepth);
109661           pRoot->isDirty = 1;
109662         }
109663       }
109664     }
109665
109666     /* Re-insert the contents of any underfull nodes removed from the tree. */
109667     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
109668       if( rc==SQLITE_OK ){
109669         rc = reinsertNodeContent(pRtree, pLeaf);
109670       }
109671       pRtree->pDeleted = pLeaf->pNext;
109672       sqlite3_free(pLeaf);
109673     }
109674
109675     /* Release the reference to the root node. */
109676     if( rc==SQLITE_OK ){
109677       rc = nodeRelease(pRtree, pRoot);
109678     }else{
109679       nodeRelease(pRtree, pRoot);
109680     }
109681   }
109682
109683   /* If the azData[] array contains more than one element, elements
109684   ** (azData[2]..azData[argc-1]) contain a new record to insert into
109685   ** the r-tree structure.
109686   */
109687   if( rc==SQLITE_OK && nData>1 ){
109688     /* Insert a new record into the r-tree */
109689     RtreeCell cell;
109690     int ii;
109691     RtreeNode *pLeaf;
109692
109693     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
109694     assert( nData==(pRtree->nDim*2 + 3) );
109695     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
109696       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
109697         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
109698         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
109699         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
109700           rc = SQLITE_CONSTRAINT;
109701           goto constraint;
109702         }
109703       }
109704     }else{
109705       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
109706         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
109707         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
109708         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
109709           rc = SQLITE_CONSTRAINT;
109710           goto constraint;
109711         }
109712       }
109713     }
109714
109715     /* Figure out the rowid of the new row. */
109716     if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
109717       rc = newRowid(pRtree, &cell.iRowid);
109718     }else{
109719       cell.iRowid = sqlite3_value_int64(azData[2]);
109720       sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
109721       if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
109722         sqlite3_reset(pRtree->pReadRowid);
109723         rc = SQLITE_CONSTRAINT;
109724         goto constraint;
109725       }
109726       rc = sqlite3_reset(pRtree->pReadRowid);
109727     }
109728
109729     if( rc==SQLITE_OK ){
109730       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
109731     }
109732     if( rc==SQLITE_OK ){
109733       int rc2;
109734       pRtree->iReinsertHeight = -1;
109735       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
109736       rc2 = nodeRelease(pRtree, pLeaf);
109737       if( rc==SQLITE_OK ){
109738         rc = rc2;
109739       }
109740     }
109741   }
109742
109743 constraint:
109744   rtreeRelease(pRtree);
109745   return rc;
109746 }
109747
109748 /*
109749 ** The xRename method for rtree module virtual tables.
109750 */
109751 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
109752   Rtree *pRtree = (Rtree *)pVtab;
109753   int rc = SQLITE_NOMEM;
109754   char *zSql = sqlite3_mprintf(
109755     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
109756     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
109757     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
109758     , pRtree->zDb, pRtree->zName, zNewName 
109759     , pRtree->zDb, pRtree->zName, zNewName 
109760     , pRtree->zDb, pRtree->zName, zNewName
109761   );
109762   if( zSql ){
109763     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
109764     sqlite3_free(zSql);
109765   }
109766   return rc;
109767 }
109768
109769 static sqlite3_module rtreeModule = {
109770   0,                         /* iVersion */
109771   rtreeCreate,                /* xCreate - create a table */
109772   rtreeConnect,               /* xConnect - connect to an existing table */
109773   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
109774   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
109775   rtreeDestroy,               /* xDestroy - Drop a table */
109776   rtreeOpen,                  /* xOpen - open a cursor */
109777   rtreeClose,                 /* xClose - close a cursor */
109778   rtreeFilter,                /* xFilter - configure scan constraints */
109779   rtreeNext,                  /* xNext - advance a cursor */
109780   rtreeEof,                   /* xEof */
109781   rtreeColumn,                /* xColumn - read data */
109782   rtreeRowid,                 /* xRowid - read data */
109783   rtreeUpdate,                /* xUpdate - write data */
109784   0,                          /* xBegin - begin transaction */
109785   0,                          /* xSync - sync transaction */
109786   0,                          /* xCommit - commit transaction */
109787   0,                          /* xRollback - rollback transaction */
109788   0,                          /* xFindFunction - function overloading */
109789   rtreeRename                 /* xRename - rename the table */
109790 };
109791
109792 static int rtreeSqlInit(
109793   Rtree *pRtree, 
109794   sqlite3 *db, 
109795   const char *zDb, 
109796   const char *zPrefix, 
109797   int isCreate
109798 ){
109799   int rc = SQLITE_OK;
109800
109801   #define N_STATEMENT 9
109802   static const char *azSql[N_STATEMENT] = {
109803     /* Read and write the xxx_node table */
109804     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
109805     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
109806     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
109807
109808     /* Read and write the xxx_rowid table */
109809     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
109810     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
109811     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
109812
109813     /* Read and write the xxx_parent table */
109814     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
109815     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
109816     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
109817   };
109818   sqlite3_stmt **appStmt[N_STATEMENT];
109819   int i;
109820
109821   pRtree->db = db;
109822
109823   if( isCreate ){
109824     char *zCreate = sqlite3_mprintf(
109825 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
109826 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
109827 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
109828 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
109829       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
109830     );
109831     if( !zCreate ){
109832       return SQLITE_NOMEM;
109833     }
109834     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
109835     sqlite3_free(zCreate);
109836     if( rc!=SQLITE_OK ){
109837       return rc;
109838     }
109839   }
109840
109841   appStmt[0] = &pRtree->pReadNode;
109842   appStmt[1] = &pRtree->pWriteNode;
109843   appStmt[2] = &pRtree->pDeleteNode;
109844   appStmt[3] = &pRtree->pReadRowid;
109845   appStmt[4] = &pRtree->pWriteRowid;
109846   appStmt[5] = &pRtree->pDeleteRowid;
109847   appStmt[6] = &pRtree->pReadParent;
109848   appStmt[7] = &pRtree->pWriteParent;
109849   appStmt[8] = &pRtree->pDeleteParent;
109850
109851   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
109852     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
109853     if( zSql ){
109854       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
109855     }else{
109856       rc = SQLITE_NOMEM;
109857     }
109858     sqlite3_free(zSql);
109859   }
109860
109861   return rc;
109862 }
109863
109864 /*
109865 ** This routine queries database handle db for the page-size used by
109866 ** database zDb. If successful, the page-size in bytes is written to
109867 ** *piPageSize and SQLITE_OK returned. Otherwise, and an SQLite error 
109868 ** code is returned.
109869 */
109870 static int getPageSize(sqlite3 *db, const char *zDb, int *piPageSize){
109871   int rc = SQLITE_NOMEM;
109872   char *zSql;
109873   sqlite3_stmt *pStmt = 0;
109874
109875   zSql = sqlite3_mprintf("PRAGMA %Q.page_size", zDb);
109876   if( !zSql ){
109877     return SQLITE_NOMEM;
109878   }
109879
109880   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
109881   sqlite3_free(zSql);
109882   if( rc!=SQLITE_OK ){
109883     return rc;
109884   }
109885
109886   if( SQLITE_ROW==sqlite3_step(pStmt) ){
109887     *piPageSize = sqlite3_column_int(pStmt, 0);
109888   }
109889   return sqlite3_finalize(pStmt);
109890 }
109891
109892 /* 
109893 ** This function is the implementation of both the xConnect and xCreate
109894 ** methods of the r-tree virtual table.
109895 **
109896 **   argv[0]   -> module name
109897 **   argv[1]   -> database name
109898 **   argv[2]   -> table name
109899 **   argv[...] -> column names...
109900 */
109901 static int rtreeInit(
109902   sqlite3 *db,                        /* Database connection */
109903   void *pAux,                         /* One of the RTREE_COORD_* constants */
109904   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
109905   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
109906   char **pzErr,                       /* OUT: Error message, if any */
109907   int isCreate                        /* True for xCreate, false for xConnect */
109908 ){
109909   int rc = SQLITE_OK;
109910   int iPageSize = 0;
109911   Rtree *pRtree;
109912   int nDb;              /* Length of string argv[1] */
109913   int nName;            /* Length of string argv[2] */
109914   int eCoordType = (int)pAux;
109915
109916   const char *aErrMsg[] = {
109917     0,                                                    /* 0 */
109918     "Wrong number of columns for an rtree table",         /* 1 */
109919     "Too few columns for an rtree table",                 /* 2 */
109920     "Too many columns for an rtree table"                 /* 3 */
109921   };
109922
109923   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
109924   if( aErrMsg[iErr] ){
109925     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
109926     return SQLITE_ERROR;
109927   }
109928
109929   rc = getPageSize(db, argv[1], &iPageSize);
109930   if( rc!=SQLITE_OK ){
109931     return rc;
109932   }
109933
109934   /* Allocate the sqlite3_vtab structure */
109935   nDb = strlen(argv[1]);
109936   nName = strlen(argv[2]);
109937   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
109938   if( !pRtree ){
109939     return SQLITE_NOMEM;
109940   }
109941   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
109942   pRtree->nBusy = 1;
109943   pRtree->base.pModule = &rtreeModule;
109944   pRtree->zDb = (char *)&pRtree[1];
109945   pRtree->zName = &pRtree->zDb[nDb+1];
109946   pRtree->nDim = (argc-4)/2;
109947   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
109948   pRtree->eCoordType = eCoordType;
109949   memcpy(pRtree->zDb, argv[1], nDb);
109950   memcpy(pRtree->zName, argv[2], nName);
109951
109952   /* Figure out the node size to use. By default, use 64 bytes less than
109953   ** the database page-size. This ensures that each node is stored on
109954   ** a single database page.
109955   **
109956   ** If the databasd page-size is so large that more than RTREE_MAXCELLS
109957   ** entries would fit in a single node, use a smaller node-size.
109958   */
109959   pRtree->iNodeSize = iPageSize-64;
109960   if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
109961     pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
109962   }
109963
109964   /* Create/Connect to the underlying relational database schema. If
109965   ** that is successful, call sqlite3_declare_vtab() to configure
109966   ** the r-tree table schema.
109967   */
109968   if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
109969     *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
109970   }else{
109971     char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
109972     char *zTmp;
109973     int ii;
109974     for(ii=4; zSql && ii<argc; ii++){
109975       zTmp = zSql;
109976       zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
109977       sqlite3_free(zTmp);
109978     }
109979     if( zSql ){
109980       zTmp = zSql;
109981       zSql = sqlite3_mprintf("%s);", zTmp);
109982       sqlite3_free(zTmp);
109983     }
109984     if( !zSql ){
109985       rc = SQLITE_NOMEM;
109986     }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
109987       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
109988     }
109989     sqlite3_free(zSql);
109990   }
109991
109992   if( rc==SQLITE_OK ){
109993     *ppVtab = (sqlite3_vtab *)pRtree;
109994   }else{
109995     rtreeRelease(pRtree);
109996   }
109997   return rc;
109998 }
109999
110000
110001 /*
110002 ** Implementation of a scalar function that decodes r-tree nodes to
110003 ** human readable strings. This can be used for debugging and analysis.
110004 **
110005 ** The scalar function takes two arguments, a blob of data containing
110006 ** an r-tree node, and the number of dimensions the r-tree indexes.
110007 ** For a two-dimensional r-tree structure called "rt", to deserialize
110008 ** all nodes, a statement like:
110009 **
110010 **   SELECT rtreenode(2, data) FROM rt_node;
110011 **
110012 ** The human readable string takes the form of a Tcl list with one
110013 ** entry for each cell in the r-tree node. Each entry is itself a
110014 ** list, containing the 8-byte rowid/pageno followed by the 
110015 ** <num-dimension>*2 coordinates.
110016 */
110017 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
110018   char *zText = 0;
110019   RtreeNode node;
110020   Rtree tree;
110021   int ii;
110022
110023   memset(&node, 0, sizeof(RtreeNode));
110024   memset(&tree, 0, sizeof(Rtree));
110025   tree.nDim = sqlite3_value_int(apArg[0]);
110026   tree.nBytesPerCell = 8 + 8 * tree.nDim;
110027   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
110028
110029   for(ii=0; ii<NCELL(&node); ii++){
110030     char zCell[512];
110031     int nCell = 0;
110032     RtreeCell cell;
110033     int jj;
110034
110035     nodeGetCell(&tree, &node, ii, &cell);
110036     sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
110037     nCell = strlen(zCell);
110038     for(jj=0; jj<tree.nDim*2; jj++){
110039       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
110040       nCell = strlen(zCell);
110041     }
110042
110043     if( zText ){
110044       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
110045       sqlite3_free(zText);
110046       zText = zTextNew;
110047     }else{
110048       zText = sqlite3_mprintf("{%s}", zCell);
110049     }
110050   }
110051   
110052   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
110053 }
110054
110055 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
110056   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
110057    || sqlite3_value_bytes(apArg[0])<2
110058   ){
110059     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
110060   }else{
110061     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
110062     sqlite3_result_int(ctx, readInt16(zBlob));
110063   }
110064 }
110065
110066 /*
110067 ** Register the r-tree module with database handle db. This creates the
110068 ** virtual table module "rtree" and the debugging/analysis scalar 
110069 ** function "rtreenode".
110070 */
110071 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
110072   int rc = SQLITE_OK;
110073
110074   if( rc==SQLITE_OK ){
110075     int utf8 = SQLITE_UTF8;
110076     rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
110077   }
110078   if( rc==SQLITE_OK ){
110079     int utf8 = SQLITE_UTF8;
110080     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
110081   }
110082   if( rc==SQLITE_OK ){
110083     void *c = (void *)RTREE_COORD_REAL32;
110084     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
110085   }
110086   if( rc==SQLITE_OK ){
110087     void *c = (void *)RTREE_COORD_INT32;
110088     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
110089   }
110090
110091   return rc;
110092 }
110093
110094 #if !SQLITE_CORE
110095 SQLITE_API int sqlite3_extension_init(
110096   sqlite3 *db,
110097   char **pzErrMsg,
110098   const sqlite3_api_routines *pApi
110099 ){
110100   SQLITE_EXTENSION_INIT2(pApi)
110101   return sqlite3RtreeInit(db);
110102 }
110103 #endif
110104
110105 #endif
110106
110107 /************** End of rtree.c ***********************************************/
110108 /************** Begin file icu.c *********************************************/
110109 /*
110110 ** 2007 May 6
110111 **
110112 ** The author disclaims copyright to this source code.  In place of
110113 ** a legal notice, here is a blessing:
110114 **
110115 **    May you do good and not evil.
110116 **    May you find forgiveness for yourself and forgive others.
110117 **    May you share freely, never taking more than you give.
110118 **
110119 *************************************************************************
110120 ** $Id: sqlite3.c,v 1.6 2010/01/08 05:42:38 wtc%google.com Exp $
110121 **
110122 ** This file implements an integration between the ICU library 
110123 ** ("International Components for Unicode", an open-source library 
110124 ** for handling unicode data) and SQLite. The integration uses 
110125 ** ICU to provide the following to SQLite:
110126 **
110127 **   * An implementation of the SQL regexp() function (and hence REGEXP
110128 **     operator) using the ICU uregex_XX() APIs.
110129 **
110130 **   * Implementations of the SQL scalar upper() and lower() functions
110131 **     for case mapping.
110132 **
110133 **   * Integration of ICU and SQLite collation seqences.
110134 **
110135 **   * An implementation of the LIKE operator that uses ICU to 
110136 **     provide case-independent matching.
110137 */
110138
110139 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
110140
110141 /* Include ICU headers */
110142 #include <unicode/utypes.h>
110143 #include <unicode/uregex.h>
110144 #include <unicode/ustring.h>
110145 #include <unicode/ucol.h>
110146
110147
110148 #ifndef SQLITE_CORE
110149   SQLITE_EXTENSION_INIT1
110150 #else
110151 #endif
110152
110153 /*
110154 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
110155 ** operator.
110156 */
110157 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
110158 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
110159 #endif
110160
110161 /*
110162 ** Version of sqlite3_free() that is always a function, never a macro.
110163 */
110164 static void xFree(void *p){
110165   sqlite3_free(p);
110166 }
110167
110168 /*
110169 ** Compare two UTF-8 strings for equality where the first string is
110170 ** a "LIKE" expression. Return true (1) if they are the same and 
110171 ** false (0) if they are different.
110172 */
110173 static int icuLikeCompare(
110174   const uint8_t *zPattern,   /* LIKE pattern */
110175   const uint8_t *zString,    /* The UTF-8 string to compare against */
110176   const UChar32 uEsc         /* The escape character */
110177 ){
110178   static const int MATCH_ONE = (UChar32)'_';
110179   static const int MATCH_ALL = (UChar32)'%';
110180
110181   int iPattern = 0;       /* Current byte index in zPattern */
110182   int iString = 0;        /* Current byte index in zString */
110183
110184   int prevEscape = 0;     /* True if the previous character was uEsc */
110185
110186   while( zPattern[iPattern]!=0 ){
110187
110188     /* Read (and consume) the next character from the input pattern. */
110189     UChar32 uPattern;
110190     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
110191     assert(uPattern!=0);
110192
110193     /* There are now 4 possibilities:
110194     **
110195     **     1. uPattern is an unescaped match-all character "%",
110196     **     2. uPattern is an unescaped match-one character "_",
110197     **     3. uPattern is an unescaped escape character, or
110198     **     4. uPattern is to be handled as an ordinary character
110199     */
110200     if( !prevEscape && uPattern==MATCH_ALL ){
110201       /* Case 1. */
110202       uint8_t c;
110203
110204       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
110205       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
110206       ** test string.
110207       */
110208       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
110209         if( c==MATCH_ONE ){
110210           if( zString[iString]==0 ) return 0;
110211           U8_FWD_1_UNSAFE(zString, iString);
110212         }
110213         iPattern++;
110214       }
110215
110216       if( zPattern[iPattern]==0 ) return 1;
110217
110218       while( zString[iString] ){
110219         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
110220           return 1;
110221         }
110222         U8_FWD_1_UNSAFE(zString, iString);
110223       }
110224       return 0;
110225
110226     }else if( !prevEscape && uPattern==MATCH_ONE ){
110227       /* Case 2. */
110228       if( zString[iString]==0 ) return 0;
110229       U8_FWD_1_UNSAFE(zString, iString);
110230
110231     }else if( !prevEscape && uPattern==uEsc){
110232       /* Case 3. */
110233       prevEscape = 1;
110234
110235     }else{
110236       /* Case 4. */
110237       UChar32 uString;
110238       U8_NEXT_UNSAFE(zString, iString, uString);
110239       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
110240       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
110241       if( uString!=uPattern ){
110242         return 0;
110243       }
110244       prevEscape = 0;
110245     }
110246   }
110247
110248   return zString[iString]==0;
110249 }
110250
110251 /*
110252 ** Implementation of the like() SQL function.  This function implements
110253 ** the build-in LIKE operator.  The first argument to the function is the
110254 ** pattern and the second argument is the string.  So, the SQL statements:
110255 **
110256 **       A LIKE B
110257 **
110258 ** is implemented as like(B, A). If there is an escape character E, 
110259 **
110260 **       A LIKE B ESCAPE E
110261 **
110262 ** is mapped to like(B, A, E).
110263 */
110264 static void icuLikeFunc(
110265   sqlite3_context *context, 
110266   int argc, 
110267   sqlite3_value **argv
110268 ){
110269   const unsigned char *zA = sqlite3_value_text(argv[0]);
110270   const unsigned char *zB = sqlite3_value_text(argv[1]);
110271   UChar32 uEsc = 0;
110272
110273   /* Limit the length of the LIKE or GLOB pattern to avoid problems
110274   ** of deep recursion and N*N behavior in patternCompare().
110275   */
110276   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
110277     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
110278     return;
110279   }
110280
110281
110282   if( argc==3 ){
110283     /* The escape character string must consist of a single UTF-8 character.
110284     ** Otherwise, return an error.
110285     */
110286     int nE= sqlite3_value_bytes(argv[2]);
110287     const unsigned char *zE = sqlite3_value_text(argv[2]);
110288     int i = 0;
110289     if( zE==0 ) return;
110290     U8_NEXT(zE, i, nE, uEsc);
110291     if( i!=nE){
110292       sqlite3_result_error(context, 
110293           "ESCAPE expression must be a single character", -1);
110294       return;
110295     }
110296   }
110297
110298   if( zA && zB ){
110299     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
110300   }
110301 }
110302
110303 /*
110304 ** This function is called when an ICU function called from within
110305 ** the implementation of an SQL scalar function returns an error.
110306 **
110307 ** The scalar function context passed as the first argument is 
110308 ** loaded with an error message based on the following two args.
110309 */
110310 static void icuFunctionError(
110311   sqlite3_context *pCtx,       /* SQLite scalar function context */
110312   const char *zName,           /* Name of ICU function that failed */
110313   UErrorCode e                 /* Error code returned by ICU function */
110314 ){
110315   char zBuf[128];
110316   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
110317   zBuf[127] = '\0';
110318   sqlite3_result_error(pCtx, zBuf, -1);
110319 }
110320
110321 /*
110322 ** Function to delete compiled regexp objects. Registered as
110323 ** a destructor function with sqlite3_set_auxdata().
110324 */
110325 static void icuRegexpDelete(void *p){
110326   URegularExpression *pExpr = (URegularExpression *)p;
110327   uregex_close(pExpr);
110328 }
110329
110330 /*
110331 ** Implementation of SQLite REGEXP operator. This scalar function takes
110332 ** two arguments. The first is a regular expression pattern to compile
110333 ** the second is a string to match against that pattern. If either 
110334 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
110335 ** is 1 if the string matches the pattern, or 0 otherwise.
110336 **
110337 ** SQLite maps the regexp() function to the regexp() operator such
110338 ** that the following two are equivalent:
110339 **
110340 **     zString REGEXP zPattern
110341 **     regexp(zPattern, zString)
110342 **
110343 ** Uses the following ICU regexp APIs:
110344 **
110345 **     uregex_open()
110346 **     uregex_matches()
110347 **     uregex_close()
110348 */
110349 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
110350   UErrorCode status = U_ZERO_ERROR;
110351   URegularExpression *pExpr;
110352   UBool res;
110353   const UChar *zString = sqlite3_value_text16(apArg[1]);
110354
110355   /* If the left hand side of the regexp operator is NULL, 
110356   ** then the result is also NULL. 
110357   */
110358   if( !zString ){
110359     return;
110360   }
110361
110362   pExpr = sqlite3_get_auxdata(p, 0);
110363   if( !pExpr ){
110364     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
110365     if( !zPattern ){
110366       return;
110367     }
110368     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
110369
110370     if( U_SUCCESS(status) ){
110371       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
110372     }else{
110373       assert(!pExpr);
110374       icuFunctionError(p, "uregex_open", status);
110375       return;
110376     }
110377   }
110378
110379   /* Configure the text that the regular expression operates on. */
110380   uregex_setText(pExpr, zString, -1, &status);
110381   if( !U_SUCCESS(status) ){
110382     icuFunctionError(p, "uregex_setText", status);
110383     return;
110384   }
110385
110386   /* Attempt the match */
110387   res = uregex_matches(pExpr, 0, &status);
110388   if( !U_SUCCESS(status) ){
110389     icuFunctionError(p, "uregex_matches", status);
110390     return;
110391   }
110392
110393   /* Set the text that the regular expression operates on to a NULL
110394   ** pointer. This is not really necessary, but it is tidier than 
110395   ** leaving the regular expression object configured with an invalid
110396   ** pointer after this function returns.
110397   */
110398   uregex_setText(pExpr, 0, 0, &status);
110399
110400   /* Return 1 or 0. */
110401   sqlite3_result_int(p, res ? 1 : 0);
110402 }
110403
110404 /*
110405 ** Implementations of scalar functions for case mapping - upper() and 
110406 ** lower(). Function upper() converts its input to upper-case (ABC).
110407 ** Function lower() converts to lower-case (abc).
110408 **
110409 ** ICU provides two types of case mapping, "general" case mapping and
110410 ** "language specific". Refer to ICU documentation for the differences
110411 ** between the two.
110412 **
110413 ** To utilise "general" case mapping, the upper() or lower() scalar 
110414 ** functions are invoked with one argument:
110415 **
110416 **     upper('ABC') -> 'abc'
110417 **     lower('abc') -> 'ABC'
110418 **
110419 ** To access ICU "language specific" case mapping, upper() or lower()
110420 ** should be invoked with two arguments. The second argument is the name
110421 ** of the locale to use. Passing an empty string ("") or SQL NULL value
110422 ** as the second argument is the same as invoking the 1 argument version
110423 ** of upper() or lower().
110424 **
110425 **     lower('I', 'en_us') -> 'i'
110426 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
110427 **
110428 ** http://www.icu-project.org/userguide/posix.html#case_mappings
110429 */
110430 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
110431   const UChar *zInput;
110432   UChar *zOutput;
110433   int nInput;
110434   int nOutput;
110435
110436   UErrorCode status = U_ZERO_ERROR;
110437   const char *zLocale = 0;
110438
110439   assert(nArg==1 || nArg==2);
110440   if( nArg==2 ){
110441     zLocale = (const char *)sqlite3_value_text(apArg[1]);
110442   }
110443
110444   zInput = sqlite3_value_text16(apArg[0]);
110445   if( !zInput ){
110446     return;
110447   }
110448   nInput = sqlite3_value_bytes16(apArg[0]);
110449
110450   nOutput = nInput * 2 + 2;
110451   zOutput = sqlite3_malloc(nOutput);
110452   if( !zOutput ){
110453     return;
110454   }
110455
110456   if( sqlite3_user_data(p) ){
110457     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
110458   }else{
110459     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
110460   }
110461
110462   if( !U_SUCCESS(status) ){
110463     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
110464     return;
110465   }
110466
110467   sqlite3_result_text16(p, zOutput, -1, xFree);
110468 }
110469
110470 /*
110471 ** Collation sequence destructor function. The pCtx argument points to
110472 ** a UCollator structure previously allocated using ucol_open().
110473 */
110474 static void icuCollationDel(void *pCtx){
110475   UCollator *p = (UCollator *)pCtx;
110476   ucol_close(p);
110477 }
110478
110479 /*
110480 ** Collation sequence comparison function. The pCtx argument points to
110481 ** a UCollator structure previously allocated using ucol_open().
110482 */
110483 static int icuCollationColl(
110484   void *pCtx,
110485   int nLeft,
110486   const void *zLeft,
110487   int nRight,
110488   const void *zRight
110489 ){
110490   UCollationResult res;
110491   UCollator *p = (UCollator *)pCtx;
110492   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
110493   switch( res ){
110494     case UCOL_LESS:    return -1;
110495     case UCOL_GREATER: return +1;
110496     case UCOL_EQUAL:   return 0;
110497   }
110498   assert(!"Unexpected return value from ucol_strcoll()");
110499   return 0;
110500 }
110501
110502 /*
110503 ** Implementation of the scalar function icu_load_collation().
110504 **
110505 ** This scalar function is used to add ICU collation based collation 
110506 ** types to an SQLite database connection. It is intended to be called
110507 ** as follows:
110508 **
110509 **     SELECT icu_load_collation(<locale>, <collation-name>);
110510 **
110511 ** Where <locale> is a string containing an ICU locale identifier (i.e.
110512 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
110513 ** collation sequence to create.
110514 */
110515 static void icuLoadCollation(
110516   sqlite3_context *p, 
110517   int nArg, 
110518   sqlite3_value **apArg
110519 ){
110520   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
110521   UErrorCode status = U_ZERO_ERROR;
110522   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
110523   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
110524   UCollator *pUCollator;    /* ICU library collation object */
110525   int rc;                   /* Return code from sqlite3_create_collation_x() */
110526
110527   assert(nArg==2);
110528   zLocale = (const char *)sqlite3_value_text(apArg[0]);
110529   zName = (const char *)sqlite3_value_text(apArg[1]);
110530
110531   if( !zLocale || !zName ){
110532     return;
110533   }
110534
110535   pUCollator = ucol_open(zLocale, &status);
110536   if( !U_SUCCESS(status) ){
110537     icuFunctionError(p, "ucol_open", status);
110538     return;
110539   }
110540   assert(p);
110541
110542   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
110543       icuCollationColl, icuCollationDel
110544   );
110545   if( rc!=SQLITE_OK ){
110546     ucol_close(pUCollator);
110547     sqlite3_result_error(p, "Error registering collation function", -1);
110548   }
110549 }
110550
110551 /*
110552 ** Register the ICU extension functions with database db.
110553 */
110554 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
110555   struct IcuScalar {
110556     const char *zName;                        /* Function name */
110557     int nArg;                                 /* Number of arguments */
110558     int enc;                                  /* Optimal text encoding */
110559     void *pContext;                           /* sqlite3_user_data() context */
110560     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
110561   } scalars[] = {
110562     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
110563
110564     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
110565     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
110566     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
110567     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
110568
110569     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
110570     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
110571     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
110572     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
110573
110574     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
110575     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
110576
110577     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
110578   };
110579
110580   int rc = SQLITE_OK;
110581   int i;
110582
110583   for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
110584     struct IcuScalar *p = &scalars[i];
110585     rc = sqlite3_create_function(
110586         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
110587     );
110588   }
110589
110590   return rc;
110591 }
110592
110593 #if !SQLITE_CORE
110594 SQLITE_API int sqlite3_extension_init(
110595   sqlite3 *db, 
110596   char **pzErrMsg,
110597   const sqlite3_api_routines *pApi
110598 ){
110599   SQLITE_EXTENSION_INIT2(pApi)
110600   return sqlite3IcuInit(db);
110601 }
110602 #endif
110603
110604 #endif
110605
110606 /************** End of icu.c *************************************************/
110607 /************** Begin file fts3_icu.c ****************************************/
110608 /*
110609 ** 2007 June 22
110610 **
110611 ** The author disclaims copyright to this source code.  In place of
110612 ** a legal notice, here is a blessing:
110613 **
110614 **    May you do good and not evil.
110615 **    May you find forgiveness for yourself and forgive others.
110616 **    May you share freely, never taking more than you give.
110617 **
110618 *************************************************************************
110619 ** This file implements a tokenizer for fts3 based on the ICU library.
110620 ** 
110621 ** $Id: sqlite3.c,v 1.6 2010/01/08 05:42:38 wtc%google.com Exp $
110622 */
110623
110624 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
110625 #ifdef SQLITE_ENABLE_ICU
110626
110627
110628 #include <unicode/ubrk.h>
110629 #include <unicode/utf16.h>
110630
110631 typedef struct IcuTokenizer IcuTokenizer;
110632 typedef struct IcuCursor IcuCursor;
110633
110634 struct IcuTokenizer {
110635   sqlite3_tokenizer base;
110636   char *zLocale;
110637 };
110638
110639 struct IcuCursor {
110640   sqlite3_tokenizer_cursor base;
110641
110642   UBreakIterator *pIter;      /* ICU break-iterator object */
110643   int nChar;                  /* Number of UChar elements in pInput */
110644   UChar *aChar;               /* Copy of input using utf-16 encoding */
110645   int *aOffset;               /* Offsets of each character in utf-8 input */
110646
110647   int nBuffer;
110648   char *zBuffer;
110649
110650   int iToken;
110651 };
110652
110653 /*
110654 ** Create a new tokenizer instance.
110655 */
110656 static int icuCreate(
110657   int argc,                            /* Number of entries in argv[] */
110658   const char * const *argv,            /* Tokenizer creation arguments */
110659   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
110660 ){
110661   IcuTokenizer *p;
110662   int n = 0;
110663
110664   if( argc>0 ){
110665     n = strlen(argv[0])+1;
110666   }
110667   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
110668   if( !p ){
110669     return SQLITE_NOMEM;
110670   }
110671   memset(p, 0, sizeof(IcuTokenizer));
110672
110673   if( n ){
110674     p->zLocale = (char *)&p[1];
110675     memcpy(p->zLocale, argv[0], n);
110676   }
110677
110678   *ppTokenizer = (sqlite3_tokenizer *)p;
110679
110680   return SQLITE_OK;
110681 }
110682
110683 /*
110684 ** Destroy a tokenizer
110685 */
110686 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
110687   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
110688   sqlite3_free(p);
110689   return SQLITE_OK;
110690 }
110691
110692 /*
110693 ** Prepare to begin tokenizing a particular string.  The input
110694 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
110695 ** used to incrementally tokenize this string is returned in 
110696 ** *ppCursor.
110697 */
110698 static int icuOpen(
110699   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
110700   const char *zInput,                    /* Input string */
110701   int nInput,                            /* Length of zInput in bytes */
110702   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
110703 ){
110704   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
110705   IcuCursor *pCsr;
110706
110707   const int32_t opt = U_FOLD_CASE_DEFAULT;
110708   UErrorCode status = U_ZERO_ERROR;
110709   int nChar;
110710
110711   UChar32 c;
110712   int iInput = 0;
110713   int iOut = 0;
110714
110715   *ppCursor = 0;
110716
110717   if( nInput<0 ){
110718     nInput = strlen(zInput);
110719   }
110720   nChar = nInput+1;
110721   pCsr = (IcuCursor *)sqlite3_malloc(
110722       sizeof(IcuCursor) +                /* IcuCursor */
110723       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
110724       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
110725   );
110726   if( !pCsr ){
110727     return SQLITE_NOMEM;
110728   }
110729   memset(pCsr, 0, sizeof(IcuCursor));
110730   pCsr->aChar = (UChar *)&pCsr[1];
110731   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
110732
110733   pCsr->aOffset[iOut] = iInput;
110734   U8_NEXT(zInput, iInput, nInput, c); 
110735   while( c>0 ){
110736     int isError = 0;
110737     c = u_foldCase(c, opt);
110738     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
110739     if( isError ){
110740       sqlite3_free(pCsr);
110741       return SQLITE_ERROR;
110742     }
110743     pCsr->aOffset[iOut] = iInput;
110744
110745     if( iInput<nInput ){
110746       U8_NEXT(zInput, iInput, nInput, c);
110747     }else{
110748       c = 0;
110749     }
110750   }
110751
110752   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
110753   if( !U_SUCCESS(status) ){
110754     sqlite3_free(pCsr);
110755     return SQLITE_ERROR;
110756   }
110757   pCsr->nChar = iOut;
110758
110759   ubrk_first(pCsr->pIter);
110760   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
110761   return SQLITE_OK;
110762 }
110763
110764 /*
110765 ** Close a tokenization cursor previously opened by a call to icuOpen().
110766 */
110767 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
110768   IcuCursor *pCsr = (IcuCursor *)pCursor;
110769   ubrk_close(pCsr->pIter);
110770   sqlite3_free(pCsr->zBuffer);
110771   sqlite3_free(pCsr);
110772   return SQLITE_OK;
110773 }
110774
110775 /*
110776 ** Extract the next token from a tokenization cursor.
110777 */
110778 static int icuNext(
110779   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
110780   const char **ppToken,               /* OUT: *ppToken is the token text */
110781   int *pnBytes,                       /* OUT: Number of bytes in token */
110782   int *piStartOffset,                 /* OUT: Starting offset of token */
110783   int *piEndOffset,                   /* OUT: Ending offset of token */
110784   int *piPosition                     /* OUT: Position integer of token */
110785 ){
110786   IcuCursor *pCsr = (IcuCursor *)pCursor;
110787
110788   int iStart = 0;
110789   int iEnd = 0;
110790   int nByte = 0;
110791
110792   while( iStart==iEnd ){
110793     UChar32 c;
110794
110795     iStart = ubrk_current(pCsr->pIter);
110796     iEnd = ubrk_next(pCsr->pIter);
110797     if( iEnd==UBRK_DONE ){
110798       return SQLITE_DONE;
110799     }
110800
110801     while( iStart<iEnd ){
110802       int iWhite = iStart;
110803       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
110804       if( u_isspace(c) ){
110805         iStart = iWhite;
110806       }else{
110807         break;
110808       }
110809     }
110810     assert(iStart<=iEnd);
110811   }
110812
110813   do {
110814     UErrorCode status = U_ZERO_ERROR;
110815     if( nByte ){
110816       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
110817       if( !zNew ){
110818         return SQLITE_NOMEM;
110819       }
110820       pCsr->zBuffer = zNew;
110821       pCsr->nBuffer = nByte;
110822     }
110823
110824     u_strToUTF8(
110825         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
110826         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
110827         &status                                  /* Output success/failure */
110828     );
110829   } while( nByte>pCsr->nBuffer );
110830
110831   *ppToken = pCsr->zBuffer;
110832   *pnBytes = nByte;
110833   *piStartOffset = pCsr->aOffset[iStart];
110834   *piEndOffset = pCsr->aOffset[iEnd];
110835   *piPosition = pCsr->iToken++;
110836
110837   return SQLITE_OK;
110838 }
110839
110840 /*
110841 ** The set of routines that implement the simple tokenizer
110842 */
110843 static const sqlite3_tokenizer_module icuTokenizerModule = {
110844   0,                           /* iVersion */
110845   icuCreate,                   /* xCreate  */
110846   icuDestroy,                  /* xCreate  */
110847   icuOpen,                     /* xOpen    */
110848   icuClose,                    /* xClose   */
110849   icuNext,                     /* xNext    */
110850 };
110851
110852 /*
110853 ** Set *ppModule to point at the implementation of the ICU tokenizer.
110854 */
110855 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
110856   sqlite3_tokenizer_module const**ppModule
110857 ){
110858   *ppModule = &icuTokenizerModule;
110859 }
110860
110861 #endif /* defined(SQLITE_ENABLE_ICU) */
110862 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
110863
110864 /************** End of fts3_icu.c ********************************************/